var.c revision 1.71 1 /* $NetBSD: var.c,v 1.71 2018/12/03 06:42:25 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.71 2018/12/03 06:42:25 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, "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, "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 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
483 if (flags & VNOEXPORT)
484 vp->flags &= ~VEXPORT;
485 if (flags & VDOEXPORT)
486 vp->flags &= ~VNOEXPORT;
487 if (vp->flags & VNOEXPORT)
488 flags &= ~VEXPORT;
489 vp->flags |= flags & ~(VNOFUNC | VDOEXPORT);
490 vp->text = s;
491
492 /*
493 * We could roll this to a function, to handle it as
494 * a regular variable function callback, but why bother?
495 */
496 if (vp == &vmpath || (vp == &vmail && ! mpathset()))
497 chkmail(1);
498
499 INTON;
500 return;
501 }
502 /* not found */
503 if (flags & VNOSET) {
504 VTRACE(DBG_VARS, ("new noset\n"));
505 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
506 ckfree(s);
507 return;
508 }
509 vp = ckmalloc(sizeof (*vp));
510 vp->flags = flags & ~(VNOFUNC|VFUNCREF|VDOEXPORT);
511 vp->text = s;
512 vp->name_len = nlen;
513 vp->func = NULL;
514 vp->next = *vpp;
515 *vpp = vp;
516
517 VTRACE(DBG_VARS, ("new [%s] (%d) %#x\n", s, nlen, vp->flags));
518 }
519
520
521
522 /*
523 * Process a linked list of variable assignments.
524 */
525
526 void
527 listsetvar(struct strlist *list, int flags)
528 {
529 struct strlist *lp;
530
531 INTOFF;
532 for (lp = list ; lp ; lp = lp->next) {
533 setvareq(savestr(lp->text), flags);
534 }
535 INTON;
536 }
537
538 void
539 listmklocal(struct strlist *list, int flags)
540 {
541 struct strlist *lp;
542
543 for (lp = list ; lp ; lp = lp->next)
544 mklocal(lp->text, flags);
545 }
546
547
548 /*
549 * Find the value of a variable. Returns NULL if not set.
550 */
551
552 char *
553 lookupvar(const char *name)
554 {
555 struct var *v;
556
557 v = find_var(name, NULL, NULL);
558 if (v == NULL || v->flags & VUNSET)
559 return NULL;
560 if (v->rfunc && (v->flags & VFUNCREF) != 0)
561 return (*v->rfunc)(v) + v->name_len + 1;
562 return v->text + v->name_len + 1;
563 }
564
565
566
567 /*
568 * Search the environment of a builtin command. If the second argument
569 * is nonzero, return the value of a variable even if it hasn't been
570 * exported.
571 */
572
573 char *
574 bltinlookup(const char *name, int doall)
575 {
576 struct strlist *sp;
577 struct var *v;
578
579 for (sp = cmdenviron ; sp ; sp = sp->next) {
580 if (strequal(sp->text, name))
581 return strchr(sp->text, '=') + 1;
582 }
583
584 v = find_var(name, NULL, NULL);
585
586 if (v == NULL || v->flags & VUNSET || (!doall && !(v->flags & VEXPORT)))
587 return NULL;
588 if (v->rfunc && (v->flags & VFUNCREF) != 0)
589 return (*v->rfunc)(v) + v->name_len + 1;
590 return v->text + v->name_len + 1;
591 }
592
593
594
595 /*
596 * Generate a list of exported variables. This routine is used to construct
597 * the third argument to execve when executing a program.
598 */
599
600 char **
601 environment(void)
602 {
603 int nenv;
604 struct var **vpp;
605 struct var *vp;
606 char **env;
607 char **ep;
608
609 nenv = 0;
610 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
611 for (vp = *vpp ; vp ; vp = vp->next)
612 if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT)
613 nenv++;
614 }
615 CTRACE(DBG_VARS, ("environment: %d vars to export\n", nenv));
616 ep = env = stalloc((nenv + 1) * sizeof *env);
617 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
618 for (vp = *vpp ; vp ; vp = vp->next)
619 if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT) {
620 if (vp->rfunc && (vp->flags & VFUNCREF))
621 *ep++ = (*vp->rfunc)(vp);
622 else
623 *ep++ = vp->text;
624 VTRACE(DBG_VARS, ("environment: %s\n", ep[-1]));
625 }
626 }
627 *ep = NULL;
628 return env;
629 }
630
631
632 /*
633 * Called when a shell procedure is invoked to clear out nonexported
634 * variables. It is also necessary to reallocate variables of with
635 * VSTACK set since these are currently allocated on the stack.
636 */
637
638 #ifdef mkinit
639 void shprocvar(void);
640
641 SHELLPROC {
642 shprocvar();
643 }
644 #endif
645
646 void
647 shprocvar(void)
648 {
649 struct var **vpp;
650 struct var *vp, **prev;
651
652 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
653 for (prev = vpp ; (vp = *prev) != NULL ; ) {
654 if ((vp->flags & VEXPORT) == 0) {
655 *prev = vp->next;
656 if ((vp->flags & VTEXTFIXED) == 0)
657 ckfree(vp->text);
658 if ((vp->flags & VSTRFIXED) == 0)
659 ckfree(vp);
660 } else {
661 if (vp->flags & VSTACK) {
662 vp->text = savestr(vp->text);
663 vp->flags &=~ VSTACK;
664 }
665 prev = &vp->next;
666 }
667 }
668 }
669 initvar();
670 }
671
672
673
674 /*
675 * Command to list all variables which are set. Currently this command
676 * is invoked from the set command when the set command is called without
677 * any variables.
678 */
679
680 void
681 print_quoted(const char *p)
682 {
683 const char *q;
684
685 if (p[0] == '\0') {
686 out1fmt("''");
687 return;
688 }
689 if (strcspn(p, "|&;<>()$`\\\"' \t\n*?[]#~=%") == strlen(p)) {
690 out1fmt("%s", p);
691 return;
692 }
693 while (*p) {
694 if (*p == '\'') {
695 out1fmt("\\'");
696 p++;
697 continue;
698 }
699 q = strchr(p, '\'');
700 if (!q) {
701 out1fmt("'%s'", p );
702 return;
703 }
704 out1fmt("'%.*s'", (int)(q - p), p );
705 p = q;
706 }
707 }
708
709 static int
710 sort_var(const void *v_v1, const void *v_v2)
711 {
712 const struct var * const *v1 = v_v1;
713 const struct var * const *v2 = v_v2;
714 char *t1 = (*v1)->text, *t2 = (*v2)->text;
715
716 if (*t1 == *t2) {
717 char *p, *s;
718
719 STARTSTACKSTR(p);
720
721 /*
722 * note: if lengths are equal, strings must be different
723 * so we don't care which string we pick for the \0 in
724 * that case.
725 */
726 if ((strchr(t1, '=') - t1) <= (strchr(t2, '=') - t2)) {
727 s = t1;
728 t1 = p;
729 } else {
730 s = t2;
731 t2 = p;
732 }
733
734 while (*s && *s != '=') {
735 STPUTC(*s, p);
736 s++;
737 }
738 STPUTC('\0', p);
739 }
740
741 return strcoll(t1, t2);
742 }
743
744 /*
745 * POSIX requires that 'set' (but not export or readonly) output the
746 * variables in lexicographic order - by the locale's collating order (sigh).
747 * Maybe we could keep them in an ordered balanced binary tree
748 * instead of hashed lists.
749 * For now just roll 'em through qsort for printing...
750 */
751
752 int
753 showvars(const char *name, int flag, int show_value, const char *xtra)
754 {
755 struct var **vpp;
756 struct var *vp;
757 const char *p;
758
759 static struct var **list; /* static in case we are interrupted */
760 static int list_len;
761 int count = 0;
762
763 if (!list) {
764 list_len = 32;
765 list = ckmalloc(list_len * sizeof *list);
766 }
767
768 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
769 for (vp = *vpp ; vp ; vp = vp->next) {
770 if (flag && !(vp->flags & flag))
771 continue;
772 if (vp->flags & VUNSET && !(show_value & 2))
773 continue;
774 if (count >= list_len) {
775 list = ckrealloc(list,
776 (list_len << 1) * sizeof *list);
777 list_len <<= 1;
778 }
779 list[count++] = vp;
780 }
781 }
782
783 qsort(list, count, sizeof *list, sort_var);
784
785 for (vpp = list; count--; vpp++) {
786 vp = *vpp;
787 if (name)
788 out1fmt("%s ", name);
789 if (xtra)
790 out1fmt("%s ", xtra);
791 p = vp->text;
792 if (vp->rfunc && (vp->flags & VFUNCREF) != 0) {
793 p = (*vp->rfunc)(vp);
794 if (p == NULL)
795 p = vp->text;
796 }
797 for ( ; *p != '=' ; p++)
798 out1c(*p);
799 if (!(vp->flags & VUNSET) && show_value) {
800 out1fmt("=");
801 print_quoted(++p);
802 }
803 out1c('\n');
804 }
805 return 0;
806 }
807
808
809
810 /*
811 * The export and readonly commands.
812 */
813
814 int
815 exportcmd(int argc, char **argv)
816 {
817 struct var *vp;
818 char *name;
819 const char *p;
820 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
821 int pflg = 0;
822 int nflg = 0;
823 int xflg = 0;
824 int res;
825 int c;
826 int f;
827
828 while ((c = nextopt("npx")) != '\0') {
829 switch (c) {
830 case 'p':
831 if (nflg)
832 return 1;
833 pflg = 3;
834 break;
835 case 'n':
836 if (pflg || xflg || flag == VREADONLY)
837 return 1;
838 nflg = 1;
839 break;
840 case 'x':
841 if (nflg || flag == VREADONLY)
842 return 1;
843 flag = VNOEXPORT;
844 xflg = 1;
845 break;
846 default:
847 return 1;
848 }
849 }
850
851 if (nflg && *argptr == NULL)
852 return 1;
853
854 if (pflg || *argptr == NULL) {
855 showvars( pflg ? argv[0] : 0, flag, pflg,
856 pflg && xflg ? "-x" : NULL );
857 return 0;
858 }
859
860 res = 0;
861 while ((name = *argptr++) != NULL) {
862 int len;
863
864 f = flag;
865
866 vp = find_var(name, NULL, &len);
867 p = name + len;
868 if (*p++ != '=')
869 p = NULL;
870
871 if (vp != NULL) {
872 if (nflg)
873 vp->flags &= ~flag;
874 else if (flag&VEXPORT && vp->flags&VNOEXPORT) {
875 sh_warnx("%.*s: not available for export",
876 len, name);
877 res = 1;
878 } else {
879 vp->flags |= flag;
880 if (flag == VNOEXPORT)
881 vp->flags &= ~VEXPORT;
882 }
883 if (p == NULL)
884 continue;
885 }
886
887 if (!nflg || p != NULL)
888 setvar(name, p, f);
889 }
890 return res;
891 }
892
893
894 /*
895 * The "local" command.
896 */
897
898 int
899 localcmd(int argc, char **argv)
900 {
901 char *name;
902 int c;
903 int flags = 0; /*XXX perhaps VUNSET from a -o option value */
904
905 if (! in_function())
906 error("Not in a function");
907
908 /* upper case options, as bash stole all the good ones ... */
909 while ((c = nextopt("INx")) != '\0')
910 switch (c) {
911 case 'I': flags &= ~VUNSET; break;
912 case 'N': flags |= VUNSET; break;
913 case 'x': flags |= VEXPORT; break;
914 }
915
916 while ((name = *argptr++) != NULL) {
917 mklocal(name, flags);
918 }
919 return 0;
920 }
921
922
923 /*
924 * Make a variable a local variable. When a variable is made local, its
925 * value and flags are saved in a localvar structure. The saved values
926 * will be restored when the shell function returns. We handle the name
927 * "-" as a special case.
928 */
929
930 void
931 mklocal(const char *name, int flags)
932 {
933 struct localvar *lvp;
934 struct var **vpp;
935 struct var *vp;
936
937 INTOFF;
938 lvp = ckmalloc(sizeof (struct localvar));
939 if (name[0] == '-' && name[1] == '\0') {
940 char *p;
941 p = ckmalloc(sizeof_optlist);
942 lvp->text = memcpy(p, optlist, sizeof_optlist);
943 vp = NULL;
944 xtrace_clone(0);
945 } else {
946 vp = find_var(name, &vpp, NULL);
947 if (vp == NULL) {
948 flags &= ~VNOEXPORT;
949 if (strchr(name, '='))
950 setvareq(savestr(name),
951 VSTRFIXED | (flags & ~VUNSET));
952 else
953 setvar(name, NULL, VSTRFIXED|flags);
954 vp = *vpp; /* the new variable */
955 lvp->text = NULL;
956 lvp->flags = VUNSET;
957 } else {
958 lvp->text = vp->text;
959 lvp->flags = vp->flags;
960 vp->flags |= VSTRFIXED|VTEXTFIXED;
961 if (flags & (VDOEXPORT | VUNSET))
962 vp->flags &= ~VNOEXPORT;
963 if (vp->flags & VNOEXPORT &&
964 (flags & (VEXPORT|VDOEXPORT|VUNSET)) == VEXPORT)
965 flags &= ~VEXPORT;
966 if (flags & (VNOEXPORT | VUNSET))
967 vp->flags &= ~VEXPORT;
968 flags &= ~VNOEXPORT;
969 if (name[vp->name_len] == '=')
970 setvareq(savestr(name), flags & ~VUNSET);
971 else if (flags & VUNSET)
972 unsetvar(name, 0);
973 else
974 vp->flags |= flags & (VUNSET|VEXPORT);
975
976 if (vp == &line_num) {
977 if (name[vp->name_len] == '=')
978 funclinebase = funclineabs -1;
979 else
980 funclinebase = 0;
981 }
982 }
983 }
984 lvp->vp = vp;
985 lvp->next = localvars;
986 localvars = lvp;
987 INTON;
988 }
989
990
991 /*
992 * Called after a function returns.
993 */
994
995 void
996 poplocalvars(void)
997 {
998 struct localvar *lvp;
999 struct var *vp;
1000
1001 while ((lvp = localvars) != NULL) {
1002 localvars = lvp->next;
1003 vp = lvp->vp;
1004 VTRACE(DBG_VARS, ("poplocalvar %s\n", vp ? vp->text : "-"));
1005 if (vp == NULL) { /* $- saved */
1006 memcpy(optlist, lvp->text, sizeof_optlist);
1007 ckfree(lvp->text);
1008 xtrace_pop();
1009 optschanged();
1010 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
1011 (void)unsetvar(vp->text, 0);
1012 } else {
1013 if (vp->func && (vp->flags & (VNOFUNC|VFUNCREF)) == 0)
1014 (*vp->func)(lvp->text + vp->name_len + 1);
1015 if ((vp->flags & VTEXTFIXED) == 0)
1016 ckfree(vp->text);
1017 vp->flags = lvp->flags;
1018 vp->text = lvp->text;
1019 }
1020 ckfree(lvp);
1021 }
1022 }
1023
1024
1025 int
1026 setvarcmd(int argc, char **argv)
1027 {
1028 if (argc <= 2)
1029 return unsetcmd(argc, argv);
1030 else if (argc == 3)
1031 setvar(argv[1], argv[2], 0);
1032 else
1033 error("List assignment not implemented");
1034 return 0;
1035 }
1036
1037
1038 /*
1039 * The unset builtin command. We unset the function before we unset the
1040 * variable to allow a function to be unset when there is a readonly variable
1041 * with the same name.
1042 */
1043
1044 int
1045 unsetcmd(int argc, char **argv)
1046 {
1047 char **ap;
1048 int i;
1049 int flg_func = 0;
1050 int flg_var = 0;
1051 int flg_x = 0;
1052 int ret = 0;
1053
1054 while ((i = nextopt("efvx")) != '\0') {
1055 switch (i) {
1056 case 'f':
1057 flg_func = 1;
1058 break;
1059 case 'e':
1060 case 'x':
1061 flg_x = (2 >> (i == 'e'));
1062 /* FALLTHROUGH */
1063 case 'v':
1064 flg_var = 1;
1065 break;
1066 }
1067 }
1068
1069 if (flg_func == 0 && flg_var == 0)
1070 flg_var = 1;
1071
1072 for (ap = argptr; *ap ; ap++) {
1073 if (flg_func)
1074 ret |= unsetfunc(*ap);
1075 if (flg_var)
1076 ret |= unsetvar(*ap, flg_x);
1077 }
1078 return ret;
1079 }
1080
1081
1082 /*
1083 * Unset the specified variable.
1084 */
1085
1086 int
1087 unsetvar(const char *s, int unexport)
1088 {
1089 struct var **vpp;
1090 struct var *vp;
1091
1092 vp = find_var(s, &vpp, NULL);
1093 if (vp == NULL)
1094 return 0;
1095
1096 if (vp->flags & VREADONLY && !(unexport & 1))
1097 return 1;
1098
1099 INTOFF;
1100 if (unexport & 1) {
1101 vp->flags &= ~VEXPORT;
1102 } else {
1103 if (vp->text[vp->name_len + 1] != '\0')
1104 setvar(s, nullstr, 0);
1105 if (!(unexport & 2))
1106 vp->flags &= ~VEXPORT;
1107 vp->flags |= VUNSET;
1108 if ((vp->flags&(VEXPORT|VSTRFIXED|VREADONLY|VNOEXPORT)) == 0) {
1109 if ((vp->flags & VTEXTFIXED) == 0)
1110 ckfree(vp->text);
1111 *vpp = vp->next;
1112 ckfree(vp);
1113 }
1114 }
1115 INTON;
1116 return 0;
1117 }
1118
1119
1120 /*
1121 * Returns true if the two strings specify the same varable. The first
1122 * variable name is terminated by '='; the second may be terminated by
1123 * either '=' or '\0'.
1124 */
1125
1126 STATIC int
1127 strequal(const char *p, const char *q)
1128 {
1129 while (*p == *q++) {
1130 if (*p++ == '=')
1131 return 1;
1132 }
1133 if (*p == '=' && *(q - 1) == '\0')
1134 return 1;
1135 return 0;
1136 }
1137
1138 /*
1139 * Search for a variable.
1140 * 'name' may be terminated by '=' or a NUL.
1141 * vppp is set to the pointer to vp, or the list head if vp isn't found
1142 * lenp is set to the number of characters in 'name'
1143 */
1144
1145 STATIC struct var *
1146 find_var(const char *name, struct var ***vppp, int *lenp)
1147 {
1148 unsigned int hashval;
1149 int len;
1150 struct var *vp, **vpp;
1151 const char *p = name;
1152
1153 hashval = 0;
1154 while (*p && *p != '=')
1155 hashval = 2 * hashval + (unsigned char)*p++;
1156
1157 len = p - name;
1158 if (lenp)
1159 *lenp = len;
1160
1161 vpp = &vartab[hashval % VTABSIZE];
1162 if (vppp)
1163 *vppp = vpp;
1164
1165 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
1166 if (vp->name_len != len)
1167 continue;
1168 if (memcmp(vp->text, name, len) != 0)
1169 continue;
1170 if (vppp)
1171 *vppp = vpp;
1172 return vp;
1173 }
1174 return NULL;
1175 }
1176
1177 /*
1178 * The following are the functions that create the values for
1179 * shell variables that are dynamically produced when needed.
1180 *
1181 * The output strings cannot be malloc'd as there is nothing to
1182 * free them - callers assume these are ordinary variables where
1183 * the value returned is vp->text
1184 *
1185 * Each function needs its own storage space, as the results are
1186 * used to create processes' environment, and (if exported) all
1187 * the values will (might) be needed simultaneously.
1188 *
1189 * It is not a problem if a var is updated while nominally in use
1190 * somewhere, all these are intended to be dynamic, the value they
1191 * return is not guaranteed, an updated vaue is just as good.
1192 *
1193 * So, malloc a single buffer for the result of each function,
1194 * grow, and even shrink, it as needed, but once we have one that
1195 * is a suitable size for the actual usage, simply hold it forever.
1196 *
1197 * For a SMALL shell we implement only LINENO, none of the others,
1198 * and give it just a fixed length static buffer for its result.
1199 */
1200
1201 #ifndef SMALL
1202
1203 struct space_reserved { /* record of space allocated for results */
1204 char *b;
1205 int len;
1206 };
1207
1208 /* rough (over-)estimate of the number of bytes needed to hold a number */
1209 static int
1210 digits_in(intmax_t number)
1211 {
1212 int res = 0;
1213
1214 if (number & ~((1LL << 62) - 1))
1215 res = 64; /* enough for 2^200 and a bit more */
1216 else if (number & ~((1LL << 32) - 1))
1217 res = 20; /* enough for 2^64 */
1218 else if (number & ~((1 << 23) - 1))
1219 res = 10; /* enough for 2^32 */
1220 else
1221 res = 8; /* enough for 2^23 or smaller */
1222
1223 return res;
1224 }
1225
1226 static int
1227 make_space(struct space_reserved *m, int bytes)
1228 {
1229 void *p;
1230
1231 if (m->len >= bytes && m->len <= (bytes<<2))
1232 return 1;
1233
1234 bytes = SHELL_ALIGN(bytes);
1235 /* not ckrealloc() - we want failure, not error() here */
1236 p = realloc(m->b, bytes);
1237 if (p == NULL) /* what we had should still be there */
1238 return 0;
1239
1240 m->b = p;
1241 m->len = bytes;
1242 m->b[bytes - 1] = '\0';
1243
1244 return 1;
1245 }
1246 #endif
1247
1248 char *
1249 get_lineno(struct var *vp)
1250 {
1251 #ifdef SMALL
1252 #define length (8 + 10) /* 10 digits is enough for a 32 bit line num */
1253 static char result[length];
1254 #else
1255 static struct space_reserved buf;
1256 #define result buf.b
1257 #define length buf.len
1258 #endif
1259 int ln = line_number;
1260
1261 if (vp->flags & VUNSET)
1262 return NULL;
1263
1264 ln -= funclinebase;
1265
1266 #ifndef SMALL
1267 if (!make_space(&buf, vp->name_len + 2 + digits_in(ln)))
1268 return vp->text;
1269 #endif
1270
1271 snprintf(result, length - 1, "%.*s=%d", vp->name_len, vp->text, ln);
1272 return result;
1273 }
1274 #undef result
1275 #undef length
1276
1277 #ifndef SMALL
1278
1279 char *
1280 get_hostname(struct var *vp)
1281 {
1282 static struct space_reserved buf;
1283
1284 if (vp->flags & VUNSET)
1285 return NULL;
1286
1287 if (!make_space(&buf, vp->name_len + 2 + 256))
1288 return vp->text;
1289
1290 memcpy(buf.b, vp->text, vp->name_len + 1); /* include '=' */
1291 (void)gethostname(buf.b + vp->name_len + 1,
1292 buf.len - vp->name_len - 3);
1293 return buf.b;
1294 }
1295
1296 char *
1297 get_tod(struct var *vp)
1298 {
1299 static struct space_reserved buf; /* space for answers */
1300 static struct space_reserved tzs; /* remember TZ last used */
1301 static timezone_t last_zone; /* timezone data for tzs zone */
1302 const char *fmt;
1303 char *tz;
1304 time_t now;
1305 struct tm tm_now, *tmp;
1306 timezone_t zone = NULL;
1307 static char t_err[] = "time error";
1308 int len;
1309
1310 if (vp->flags & VUNSET)
1311 return NULL;
1312
1313 fmt = lookupvar("ToD_FORMAT");
1314 if (fmt == NULL)
1315 fmt="%T";
1316 tz = lookupvar("TZ");
1317 (void)time(&now);
1318
1319 if (tz != NULL) {
1320 if (tzs.b == NULL || strcmp(tzs.b, tz) != 0) {
1321 if (make_space(&tzs, strlen(tz) + 1)) {
1322 INTOFF;
1323 strcpy(tzs.b, tz);
1324 if (last_zone)
1325 tzfree(last_zone);
1326 last_zone = zone = tzalloc(tz);
1327 INTON;
1328 } else
1329 zone = tzalloc(tz);
1330 } else
1331 zone = last_zone;
1332
1333 tmp = localtime_rz(zone, &now, &tm_now);
1334 } else
1335 tmp = localtime_r(&now, &tm_now);
1336
1337 len = (strlen(fmt) * 4) + vp->name_len + 2;
1338 while (make_space(&buf, len)) {
1339 memcpy(buf.b, vp->text, vp->name_len+1);
1340 if (tmp == NULL) {
1341 if (buf.len >= vp->name_len+2+(int)(sizeof t_err - 1)) {
1342 strcpy(buf.b + vp->name_len + 1, t_err);
1343 if (zone && zone != last_zone)
1344 tzfree(zone);
1345 return buf.b;
1346 }
1347 len = vp->name_len + 4 + sizeof t_err - 1;
1348 continue;
1349 }
1350 if (strftime_z(zone, buf.b + vp->name_len + 1,
1351 buf.len - vp->name_len - 2, fmt, tmp)) {
1352 if (zone && zone != last_zone)
1353 tzfree(zone);
1354 return buf.b;
1355 }
1356 if (len >= 4096) /* Let's be reasonable */
1357 break;
1358 len <<= 1;
1359 }
1360 if (zone && zone != last_zone)
1361 tzfree(zone);
1362 return vp->text;
1363 }
1364
1365 char *
1366 get_seconds(struct var *vp)
1367 {
1368 static struct space_reserved buf;
1369 intmax_t secs;
1370
1371 if (vp->flags & VUNSET)
1372 return NULL;
1373
1374 secs = (intmax_t)time((time_t *)0) - sh_start_time;
1375 if (!make_space(&buf, vp->name_len + 2 + digits_in(secs)))
1376 return vp->text;
1377
1378 snprintf(buf.b, buf.len-1, "%.*s=%jd", vp->name_len, vp->text, secs);
1379 return buf.b;
1380 }
1381
1382 char *
1383 get_euser(struct var *vp)
1384 {
1385 static struct space_reserved buf;
1386 static uid_t lastuid = 0;
1387 uid_t euid;
1388 struct passwd *pw;
1389
1390 if (vp->flags & VUNSET)
1391 return NULL;
1392
1393 euid = geteuid();
1394 if (buf.b != NULL && lastuid == euid)
1395 return buf.b;
1396
1397 pw = getpwuid(euid);
1398 if (pw == NULL)
1399 return vp->text;
1400
1401 if (make_space(&buf, vp->name_len + 2 + strlen(pw->pw_name))) {
1402 lastuid = euid;
1403 snprintf(buf.b, buf.len, "%.*s=%s", vp->name_len, vp->text,
1404 pw->pw_name);
1405 return buf.b;
1406 }
1407
1408 return vp->text;
1409 }
1410
1411 char *
1412 get_random(struct var *vp)
1413 {
1414 static struct space_reserved buf;
1415 static intmax_t random_val = 0;
1416
1417 #ifdef USE_LRAND48
1418 #define random lrand48
1419 #define srandom srand48
1420 #endif
1421
1422 if (vp->flags & VUNSET)
1423 return NULL;
1424
1425 if (vp->text != buf.b) {
1426 /*
1427 * Either initialisation, or a new seed has been set
1428 */
1429 if (vp->text[vp->name_len + 1] == '\0') {
1430 int fd;
1431
1432 /*
1433 * initialisation (without pre-seeding),
1434 * or explictly requesting a truly random seed.
1435 */
1436 fd = open("/dev/urandom", 0);
1437 if (fd == -1) {
1438 out2str("RANDOM initialisation failed\n");
1439 random_val = (getpid()<<3) ^ time((time_t *)0);
1440 } else {
1441 int n;
1442
1443 do {
1444 n = read(fd,&random_val,sizeof random_val);
1445 } while (n != sizeof random_val);
1446 close(fd);
1447 }
1448 } else
1449 /* good enough for today */
1450 random_val = strtoimax(vp->text+vp->name_len+1,NULL,0);
1451
1452 srandom((long)random_val);
1453 }
1454
1455 #if 0
1456 random_val = (random_val + 1) & 0x7FFF; /* 15 bit "random" numbers */
1457 #else
1458 random_val = (random() >> 5) & 0x7FFF;
1459 #endif
1460
1461 if (!make_space(&buf, vp->name_len + 2 + digits_in(random_val)))
1462 return vp->text;
1463
1464 snprintf(buf.b, buf.len-1, "%.*s=%jd", vp->name_len, vp->text,
1465 random_val);
1466
1467 if (buf.b != vp->text && (vp->flags & (VTEXTFIXED|VSTACK)) == 0)
1468 free(vp->text);
1469 vp->flags |= VTEXTFIXED;
1470 vp->text = buf.b;
1471
1472 return vp->text;
1473 #undef random
1474 #undef srandom
1475 }
1476
1477 #endif /* SMALL */
1478