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