121308Sache/*-
221308Sache * SPDX-License-Identifier: BSD-2-Clause
3136644Sache *
421308Sache * Copyright (c) 1998 Michael Smith
521308Sache * All rights reserved.
621308Sache *
721308Sache * Redistribution and use in source and binary forms, with or without
821308Sache * modification, are permitted provided that the following conditions
921308Sache * are met:
1058310Sache * 1. Redistributions of source code must retain the above copyright
1121308Sache *    notice, this list of conditions and the following disclaimer.
1221308Sache * 2. Redistributions in binary form must reproduce the above copyright
1321308Sache *    notice, this list of conditions and the following disclaimer in the
1421308Sache *    documentation and/or other materials provided with the distribution.
1521308Sache *
1621308Sache * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1721308Sache * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1821308Sache * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1921308Sache * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2021308Sache * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2158310Sache * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2221308Sache * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2321308Sache * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2421308Sache * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2521308Sache * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26136644Sache * SUCH DAMAGE.
2721308Sache */
2821308Sache
29136644Sache/*
30136644Sache * The unified bootloader passes us a pointer to a preserved copy of
31136644Sache * bootstrap/kernel environment variables.  We convert them to a
32136644Sache * dynamic array of strings later when the VM subsystem is up.
3321308Sache *
3421308Sache * We make these available through the kenv(2) syscall for userland
3521308Sache * and through kern_getenv()/freeenv() kern_setenv() kern_unsetenv() testenv() for
3621308Sache * the kernel.
3721308Sache */
3821308Sache
3921308Sache#include <sys/param.h>
40136644Sache#include <sys/eventhandler.h>
4135486Sache#include <sys/systm.h>
4235486Sache#include <sys/kenv.h>
4358310Sache#include <sys/kernel.h>
4421308Sache#include <sys/libkern.h>
4521308Sache#include <sys/limits.h>
4621308Sache#include <sys/lock.h>
4721308Sache#include <sys/malloc.h>
4821308Sache#include <sys/mutex.h>
4921308Sache#include <sys/priv.h>
5021308Sache#include <sys/proc.h>
5121308Sache#include <sys/queue.h>
5221308Sache#include <sys/sysent.h>
5321308Sache#include <sys/sysproto.h>
5421308Sache
5521308Sache#include <security/mac/mac_framework.h>
56119610Sache
57119610Sache#include <vm/uma.h>
58119610Sache
5921308Sachestatic char *_getenv_dynamic_locked(const char *name, int *idx);
60136644Sachestatic char *_getenv_dynamic(const char *name, int *idx);
61119610Sache
6258310Sachestatic char *kenv_acquire(const char *name);
63119610Sachestatic void kenv_release(const char *buf);
64119610Sache
65119610Sachestatic MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
66119610Sache
67119610Sache#define KENV_SIZE	512	/* Maximum number of environment strings */
68119610Sache
69119610Sachestatic uma_zone_t kenv_zone;
70119610Sachestatic int	kenv_mvallen = KENV_MVALLEN;
71119610Sache
72119610Sache/* pointer to the config-generated static environment */
73119610Sachechar		*kern_envp;
74119610Sache
75136644Sache/* pointer to the md-static environment */
76119610Sachechar		*md_envp;
7758310Sachestatic int	md_env_len;
7858310Sachestatic int	md_env_pos;
7958310Sache
8058310Sachestatic char	*kernenv_next(char *);
8158310Sache
8226497Sache/* dynamic environment variables */
8326497Sachechar		**kenvp;
8426497Sachestruct mtx	kenv_lock;
8558310Sache
8626497Sache/*
8726497Sache * No need to protect this with a mutex since SYSINITS are single threaded.
8858310Sache */
8926497Sachebool	dynamic_kenv;
9021308Sache
9121308Sache#define KENV_CHECK	if (!dynamic_kenv) \
9221308Sache			    panic("%s: called before SI_SUB_KMEM", __func__)
9321308Sache
9421308Sachestatic int
9521308Sachekenv_dump(struct thread *td, char **envp, int what, char *value, int len)
9621308Sache{
9721308Sache	char *buffer, *senv;
9858310Sache	size_t done, needed, buflen;
9958310Sache	int error;
10026497Sache
101136644Sache	error = 0;
102136644Sache	buffer = NULL;
103136644Sache	done = needed = 0;
104136644Sache
105136644Sache	MPASS(what == KENV_DUMP || what == KENV_DUMP_LOADER ||
106136644Sache	    what == KENV_DUMP_STATIC);
107136644Sache
10821308Sache	/*
10921308Sache	 * For non-dynamic kernel environment, we pass in either md_envp or
11021308Sache	 * kern_envp and we must traverse with kernenv_next().  This shuffling
11121308Sache	 * of pointers simplifies the below loop by only differing in how envp
11221308Sache	 * is modified.
11375406Sache	 */
11421308Sache	if (what != KENV_DUMP) {
11575406Sache		senv = (char *)envp;
11675406Sache		envp = &senv;
11721308Sache	}
11821308Sache
11921308Sache	buflen = len;
12021308Sache	if (buflen > KENV_SIZE * (KENV_MNAMELEN + kenv_mvallen + 2))
12121308Sache		buflen = KENV_SIZE * (KENV_MNAMELEN +
12221308Sache		    kenv_mvallen + 2);
12321308Sache	if (len > 0 && value != NULL)
12475406Sache		buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
12521308Sache
12621308Sache	/* Only take the lock for the dynamic kenv. */
12721308Sache	if (what == KENV_DUMP)
12821308Sache		mtx_lock(&kenv_lock);
12921308Sache	while (*envp != NULL) {
13021308Sache		len = strlen(*envp) + 1;
13121308Sache		needed += len;
13221308Sache		len = min(len, buflen - done);
13321308Sache		/*
134119610Sache		 * If called with a NULL or insufficiently large
13521308Sache		 * buffer, just keep computing the required size.
13621308Sache		 */
13758310Sache		if (value != NULL && buffer != NULL && len > 0) {
13858310Sache			bcopy(*envp, buffer + done, len);
13958310Sache			done += len;
14021308Sache		}
14158310Sache
14221308Sache		/* Advance the pointer depending on the kenv format. */
14321308Sache		if (what == KENV_DUMP)
14421308Sache			envp++;
14521308Sache		else
14621308Sache			senv = kernenv_next(senv);
14721308Sache	}
14821308Sache	if (what == KENV_DUMP)
14921308Sache		mtx_unlock(&kenv_lock);
15021308Sache	if (buffer != NULL) {
15175406Sache		error = copyout(buffer, value, done);
15221308Sache		free(buffer, M_TEMP);
15321308Sache	}
15421308Sache	td->td_retval[0] = ((done == needed) ? 0 : needed);
15521308Sache	return (error);
15621308Sache}
15721308Sache
15821308Sacheint
15921308Sachesys_kenv(struct thread *td, struct kenv_args *uap)
16021308Sache{
16121308Sache	char *name, *value;
16221308Sache	size_t len;
16375406Sache	int error;
16421308Sache
16521308Sache	KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = false"));
166136644Sache
167136644Sache	error = 0;
16858310Sache
16921308Sache	switch (uap->what) {
17035486Sache	case KENV_DUMP:
171136644Sache#ifdef MAC
172136644Sache		error = mac_kenv_check_dump(td->td_ucred);
173136644Sache		if (error)
174136644Sache			return (error);
175136644Sache#endif
176136644Sache		return (kenv_dump(td, kenvp, uap->what, uap->value, uap->len));
177136644Sache	case KENV_DUMP_LOADER:
17821308Sache	case KENV_DUMP_STATIC:
179136644Sache#ifdef MAC
18021308Sache		error = mac_kenv_check_dump(td->td_ucred);
18126497Sache		if (error)
18221308Sache			return (error);
18321308Sache#endif
18421308Sache#ifdef PRESERVE_EARLY_KENV
18521308Sache		return (kenv_dump(td,
18635486Sache		    uap->what == KENV_DUMP_LOADER ? (char **)md_envp :
18721308Sache		    (char **)kern_envp, uap->what, uap->value, uap->len));
18835486Sache#else
18935486Sache		return (ENOENT);
19021308Sache#endif
191136644Sache	case KENV_SET:
19235486Sache		error = priv_check(td, PRIV_KENV_SET);
19335486Sache		if (error)
19435486Sache			return (error);
195136644Sache		break;
196119610Sache
197119610Sache	case KENV_UNSET:
198119610Sache		error = priv_check(td, PRIV_KENV_UNSET);
199119610Sache		if (error)
200136644Sache			return (error);
201136644Sache		break;
202136644Sache	}
203136644Sache
204119610Sache	name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
205119610Sache
206119610Sache	error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
207119610Sache	if (error)
208136644Sache		goto done;
209136644Sache
210136644Sache	switch (uap->what) {
211136644Sache	case KENV_GET:
21258310Sache#ifdef MAC
21358310Sache		error = mac_kenv_check_get(td->td_ucred, name);
214119610Sache		if (error)
21558310Sache			goto done;
21635486Sache#endif
21721308Sache		value = kern_getenv(name);
218136644Sache		if (value == NULL) {
219136644Sache			error = ENOENT;
220136644Sache			goto done;
221136644Sache		}
22221308Sache		len = strlen(value) + 1;
22321308Sache		if (len > uap->len)
22421308Sache			len = uap->len;
22521308Sache		error = copyout(value, uap->value, len);
226136644Sache		freeenv(value);
22721308Sache		if (error)
228119610Sache			goto done;
22921308Sache		td->td_retval[0] = len;
230119610Sache		break;
23121308Sache	case KENV_SET:
23221308Sache		len = uap->len;
23321308Sache		if (len < 1) {
23421308Sache			error = EINVAL;
23521308Sache			goto done;
23621308Sache		}
23758310Sache		if (len > kenv_mvallen + 1)
23821308Sache			len = kenv_mvallen + 1;
23921308Sache		value = malloc(len, M_TEMP, M_WAITOK);
240119610Sache		error = copyinstr(uap->value, value, len, NULL);
241119610Sache		if (error) {
24221308Sache			free(value, M_TEMP);
24321308Sache			goto done;
244119610Sache		}
245119610Sache#ifdef MAC
246119610Sache		error = mac_kenv_check_set(td->td_ucred, name, value);
247136644Sache		if (error == 0)
248136644Sache#endif
249136644Sache			kern_setenv(name, value);
250136644Sache		free(value, M_TEMP);
251136644Sache		break;
252136644Sache	case KENV_UNSET:
253119610Sache#ifdef MAC
25421308Sache		error = mac_kenv_check_unset(td->td_ucred, name);
25521308Sache		if (error)
256119610Sache			goto done;
257119610Sache#endif
25821308Sache		error = kern_unsetenv(name);
259165670Sache		if (error)
260165670Sache			error = ENOENT;
261165670Sache		break;
262165670Sache	default:
263165670Sache		error = EINVAL;
26421308Sache		break;
265119610Sache	}
266136644Sachedone:
267136644Sache	free(name, M_TEMP);
268136644Sache	return (error);
269136644Sache}
270136644Sache
271136644Sache/*
272136644Sache * Populate the initial kernel environment.
273136644Sache *
274136644Sache * This is called very early in MD startup, either to provide a copy of the
275136644Sache * environment obtained from a boot loader, or to provide an empty buffer into
276136644Sache * which MD code can store an initial environment using kern_setenv() calls.
277136644Sache *
278136644Sache * kern_envp is set to the static_env generated by config(8).  This implements
279136644Sache * the env keyword described in config(5).
280136644Sache *
281136644Sache * If len is non-zero, the caller is providing an empty buffer.  The caller will
28221308Sache * subsequently use kern_setenv() to add up to len bytes of initial environment
28321308Sache * before the dynamic environment is available.
28421308Sache *
28521308Sache * If len is zero, the caller is providing a pre-loaded buffer containing
28621308Sache * environment strings.  Additional strings cannot be added until the dynamic
28721308Sache * environment is available.  The memory pointed to must remain stable at least
28821308Sache * until sysinit runs init_dynamic_kenv() and preferably until after SI_SUB_KMEM
28921308Sache * is finished so that subr_hints routines may continue to use it until the
29021308Sache * environments have been fully merged at the end of the pass.  If no initial
29121308Sache * environment is available from the boot loader, passing a NULL pointer allows
292136644Sache * the static_env to be installed if it is configured.  In this case, any call
29321308Sache * to kern_setenv() prior to the setup of the dynamic environment will result in
294119610Sache * a panic.
295119610Sache */
296119610Sachevoid
29721308Sacheinit_static_kenv(char *buf, size_t len)
29821308Sache{
29921308Sache
30021308Sache	KASSERT(!dynamic_kenv, ("kenv: dynamic_kenv already initialized"));
30121308Sache	/*
30275406Sache	 * Suitably sized means it must be able to hold at least one empty
30375406Sache	 * variable, otherwise things go belly up if a kern_getenv call is
30421308Sache	 * made without a prior call to kern_setenv as we have a malformed
30521308Sache	 * environment.
30675406Sache	 */
30747558Sache	KASSERT(len == 0 || len >= 2,
30821308Sache	    ("kenv: static env must be initialized or suitably sized"));
309136644Sache	KASSERT(len == 0 || (*buf == '\0' && *(buf + 1) == '\0'),
31075406Sache	    ("kenv: sized buffer must be initially empty"));
31121308Sache
31235486Sache	/*
31321308Sache	 * We may be called twice, with the second call needed to relocate
31426497Sache	 * md_envp after enabling paging.  md_envp is then garbage if it is
31521308Sache	 * not null and the relocation will move it.  Discard it so as to
31626497Sache	 * not crash using its old value in our first call to kern_getenv().
31775406Sache	 *
31821308Sache	 * The second call gives the same environment as the first except
31975406Sache	 * in silly configurations where the static env disables itself.
32021308Sache	 *
32175406Sache	 * Other env calls don't handle possibly-garbage pointers, so must
32275406Sache	 * not be made between enabling paging and calling here.
32375406Sache	 */
32475406Sache	md_envp = NULL;
32575406Sache	md_env_len = 0;
32675406Sache	md_env_pos = 0;
32721308Sache
32875406Sache	/*
32975406Sache	 * Give the static environment a chance to disable the loader(8)
33075406Sache	 * environment first.  This is done with loader_env.disabled=1.
33175406Sache	 *
33275406Sache	 * static_env and static_hints may both be disabled, but in slightly
33375406Sache	 * different ways.  For static_env, we just don't setup kern_envp and
33475406Sache	 * it's as if a static env wasn't even provided.  For static_hints,
33575406Sache	 * we effectively zero out the buffer to stop the rest of the kernel
33675406Sache	 * from being able to use it.
33775406Sache	 *
33858310Sache	 * We're intentionally setting this up so that static_hints.disabled may
33935486Sache	 * be specified in either the MD env or the static env. This keeps us
34035486Sache	 * consistent in our new world view.
34135486Sache	 *
34235486Sache	 * As a warning, the static environment may not be disabled in any way
34335486Sache	 * if the static environment has disabled the loader environment.
34435486Sache	 */
34535486Sache	kern_envp = static_env;
34675406Sache	if (!getenv_is_true("loader_env.disabled")) {
34775406Sache		md_envp = buf;
34875406Sache		md_env_len = len;
34975406Sache		md_env_pos = 0;
35075406Sache
35135486Sache		if (getenv_is_true("static_env.disabled")) {
35235486Sache			kern_envp[0] = '\0';
35335486Sache			kern_envp[1] = '\0';
35435486Sache		}
355119610Sache	}
356119610Sache	if (getenv_is_true("static_hints.disabled")) {
357119610Sache		static_hints[0] = '\0';
358119610Sache		static_hints[1] = '\0';
359119610Sache	}
360119610Sache}
361119610Sache
36235486Sache/* Maximum suffix number appended for duplicate environment variable names. */
36321308Sache#define MAXSUFFIX 9999
36421308Sache#define SUFFIXLEN strlen("_" __XSTRING(MAXSUFFIX))
36521308Sache
36675406Sachestatic void
36775406Sachegetfreesuffix(char *cp, size_t *n)
36875406Sache{
36975406Sache	size_t len = strlen(cp);
37021308Sache	char * ncp;
37121308Sache
372136644Sache	ncp = malloc(len + SUFFIXLEN + 1, M_KENV, M_WAITOK);
373136644Sache	memcpy(ncp, cp, len);
374136644Sache	for (*n = 1; *n <= MAXSUFFIX; (*n)++) {
375136644Sache		sprintf(&ncp[len], "_%zu", *n);
37621308Sache		if (!_getenv_dynamic_locked(ncp, NULL))
377136644Sache			break;
37821308Sache	}
379136644Sache	free(ncp, M_KENV);
38021308Sache	if (*n > MAXSUFFIX)
38121308Sache		panic("Too many duplicate kernel environment values: %s", cp);
38221308Sache}
38321308Sache
38421308Sachestatic void
38521308Sacheinit_dynamic_kenv_from(char *init_env, int *curpos)
38621308Sache{
387119610Sache	char *cp, *cpnext, *eqpos, *found;
388136644Sache	size_t len, n;
389136644Sache	int i;
390136644Sache
391136644Sache	if (init_env && *init_env != '\0') {
392136644Sache		found = NULL;
393136644Sache		i = *curpos;
394136644Sache		for (cp = init_env; cp != NULL; cp = cpnext) {
395136644Sache			cpnext = kernenv_next(cp);
39621308Sache			len = strlen(cp) + 1;
39721308Sache			if (i > KENV_SIZE) {
39821308Sache				printf(
399119610Sache				"WARNING: too many kenv strings, ignoring %s\n",
40021308Sache				    cp);
401119610Sache				goto sanitize;
40247558Sache			}
40347558Sache			if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
40447558Sache				printf(
405119610Sache				"WARNING: too long kenv string, ignoring %s\n",
40647558Sache				    cp);
40747558Sache				goto sanitize;
40821308Sache			}
40921308Sache			eqpos = strchr(cp, '=');
41021308Sache			if (eqpos == NULL) {
41121308Sache				printf(
41221308Sache				"WARNING: malformed static env value, ignoring %s\n",
41321308Sache				    cp);
41421308Sache				goto sanitize;
41521308Sache			}
41675406Sache			*eqpos = 0;
41721308Sache			/*
41821308Sache			 * Handle duplicates in the environment as we go; we
41921308Sache			 * add the duplicated assignments with _N suffixes.
42021308Sache			 * This ensures that (a) if a variable is set in the
42121308Sache			 * static environment and in the "loader" environment
42221308Sache			 * provided by MD code, the value from the loader will
42321308Sache			 * have the expected variable name and the value from
42475406Sache			 * the static environment will have the suffix; and (b)
42521308Sache			 * if the "loader" environment has the same variable
42621308Sache			 * set multiple times (as is possible with values being
42721308Sache			 * passed via the kernel "command line") the extra
42826497Sache			 * values are visible to code which knows where to look
42975406Sache			 * for them.
430136644Sache			 */
431119610Sache			found = _getenv_dynamic_locked(cp, NULL);
43221308Sache			if (found != NULL) {
433119610Sache				getfreesuffix(cp, &n);
434119610Sache				kenvp[i] = malloc(len + SUFFIXLEN,
43526497Sache				    M_KENV, M_WAITOK);
436119610Sache				sprintf(kenvp[i++], "%s_%zu=%s", cp, n,
43726497Sache				    &eqpos[1]);
43875406Sache			} else {
43921308Sache				kenvp[i] = malloc(len, M_KENV, M_WAITOK);
44030971Sache				*eqpos = '=';
44121308Sache				strcpy(kenvp[i++], cp);
44221308Sache			}
44321308Sachesanitize:
44421308Sache#ifdef PRESERVE_EARLY_KENV
44521308Sache			continue;
446136644Sache#else
447119610Sache			explicit_bzero(cp, len - 1);
448119610Sache#endif
449119610Sache		}
45021308Sache		*curpos = i;
45121308Sache	}
45221308Sache}
45321308Sache
45421308Sache/*
45521308Sache * Setup the dynamic kernel environment.
45621308Sache */
45721308Sachestatic void
45821308Sacheinit_dynamic_kenv(void *data __unused)
45921308Sache{
46021308Sache	int dynamic_envpos;
46121308Sache	int size;
46221308Sache
46321308Sache	TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
464136644Sache	size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
465136644Sache
466136644Sache	kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
467136644Sache	    UMA_ALIGN_PTR, 0);
468136644Sache
469136644Sache	kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
470136644Sache		M_WAITOK | M_ZERO);
471136644Sache
472136644Sache	dynamic_envpos = 0;
47321308Sache	init_dynamic_kenv_from(md_envp, &dynamic_envpos);
47421308Sache	init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
475136644Sache	kenvp[dynamic_envpos] = NULL;
476119610Sache
477119610Sache	mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
478119610Sache	dynamic_kenv = true;
479119610Sache}
480119610SacheSYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
481119610Sache
482119610Sachevoid
483119610Sachefreeenv(char *env)
484119610Sache{
485119610Sache
486119610Sache	if (dynamic_kenv && env != NULL) {
487119610Sache		explicit_bzero(env, strlen(env));
488119610Sache		uma_zfree(kenv_zone, env);
489119610Sache	}
490119610Sache}
491119610Sache
492119610Sache/*
493119610Sache * Internal functions for string lookup.
494119610Sache */
495119610Sachestatic char *
496119610Sache_getenv_dynamic_locked(const char *name, int *idx)
49721308Sache{
49821308Sache	char *cp;
49921308Sache	int len, i;
500136644Sache
501136644Sache	len = strlen(name);
502136644Sache	for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
503136644Sache		if ((strncmp(cp, name, len) == 0) &&
504136644Sache		    (cp[len] == '=')) {
505136644Sache			if (idx != NULL)
50621308Sache				*idx = i;
50721308Sache			return (cp + len + 1);
50821308Sache		}
50921308Sache	}
51021308Sache	return (NULL);
511136644Sache}
512119610Sache
513119610Sachestatic char *
514119610Sache_getenv_dynamic(const char *name, int *idx)
51575406Sache{
51675406Sache
51721308Sache	mtx_assert(&kenv_lock, MA_OWNED);
518119610Sache	return (_getenv_dynamic_locked(name, idx));
51921308Sache}
52021308Sache
52121308Sachestatic char *
52221308Sache_getenv_static_from(char *chkenv, const char *name)
52321308Sache{
52421308Sache	char *cp, *ep;
52575406Sache	int len;
52621308Sache
52721308Sache	for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
52821308Sache		for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
52921308Sache			;
53021308Sache		if (*ep != '=')
53121308Sache			continue;
53221308Sache		len = ep - cp;
53375406Sache		ep++;
53421308Sache		if (!strncmp(name, cp, len) && name[len] == 0)
53521308Sache			return (ep);
53621308Sache	}
53721308Sache	return (NULL);
53821308Sache}
53921308Sache
54021308Sachestatic char *
54121308Sache_getenv_static(const char *name)
54221308Sache{
54375406Sache	char *val;
54421308Sache
54521308Sache	val = _getenv_static_from(md_envp, name);
54621308Sache	if (val != NULL)
547		return (val);
548	val = _getenv_static_from(kern_envp, name);
549	if (val != NULL)
550		return (val);
551	return (NULL);
552}
553
554/*
555 * Look up an environment variable by name.
556 * Return a pointer to the string if found.
557 * The pointer has to be freed with freeenv()
558 * after use.
559 */
560char *
561kern_getenv(const char *name)
562{
563	char *cp, *ret;
564	int len;
565
566	if (dynamic_kenv) {
567		len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
568		ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
569		mtx_lock(&kenv_lock);
570		cp = _getenv_dynamic(name, NULL);
571		if (cp != NULL)
572			strlcpy(ret, cp, len);
573		mtx_unlock(&kenv_lock);
574		if (cp == NULL) {
575			uma_zfree(kenv_zone, ret);
576			ret = NULL;
577		}
578	} else
579		ret = _getenv_static(name);
580
581	return (ret);
582}
583
584/*
585 * Test if an environment variable is defined.
586 */
587int
588testenv(const char *name)
589{
590	char *cp;
591
592	cp = kenv_acquire(name);
593	kenv_release(cp);
594
595	if (cp != NULL)
596		return (1);
597	return (0);
598}
599
600/*
601 * Set an environment variable in the MD-static environment.  This cannot
602 * feasibly be done on config(8)-generated static environments as they don't
603 * generally include space for extra variables.
604 */
605static int
606setenv_static(const char *name, const char *value)
607{
608	int len;
609
610	if (md_env_pos >= md_env_len)
611		return (-1);
612
613	/* Check space for x=y and two nuls */
614	len = strlen(name) + strlen(value);
615	if (len + 3 < md_env_len - md_env_pos) {
616		len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
617		md_env_pos += len+1;
618		md_envp[md_env_pos] = '\0';
619		return (0);
620	} else
621		return (-1);
622
623}
624
625/*
626 * Set an environment variable by name.
627 */
628int
629kern_setenv(const char *name, const char *value)
630{
631	char *buf, *cp, *oldenv;
632	int namelen, vallen, i;
633
634	if (!dynamic_kenv && md_env_len > 0)
635		return (setenv_static(name, value));
636
637	KENV_CHECK;
638
639	namelen = strlen(name) + 1;
640	if (namelen > KENV_MNAMELEN + 1)
641		return (-1);
642	vallen = strlen(value) + 1;
643	if (vallen > kenv_mvallen + 1)
644		return (-1);
645	buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
646	sprintf(buf, "%s=%s", name, value);
647
648	mtx_lock(&kenv_lock);
649	cp = _getenv_dynamic(name, &i);
650	if (cp != NULL) {
651		oldenv = kenvp[i];
652		kenvp[i] = buf;
653		mtx_unlock(&kenv_lock);
654		free(oldenv, M_KENV);
655	} else {
656		/* We add the option if it wasn't found */
657		for (i = 0; (cp = kenvp[i]) != NULL; i++)
658			;
659
660		/* Bounds checking */
661		if (i < 0 || i >= KENV_SIZE) {
662			free(buf, M_KENV);
663			mtx_unlock(&kenv_lock);
664			return (-1);
665		}
666
667		kenvp[i] = buf;
668		kenvp[i + 1] = NULL;
669		mtx_unlock(&kenv_lock);
670	}
671	EVENTHANDLER_INVOKE(setenv, name);
672	return (0);
673}
674
675/*
676 * Unset an environment variable string.
677 */
678int
679kern_unsetenv(const char *name)
680{
681	char *cp, *oldenv;
682	int i, j;
683
684	KENV_CHECK;
685
686	mtx_lock(&kenv_lock);
687	cp = _getenv_dynamic(name, &i);
688	if (cp != NULL) {
689		oldenv = kenvp[i];
690		for (j = i + 1; kenvp[j] != NULL; j++)
691			kenvp[i++] = kenvp[j];
692		kenvp[i] = NULL;
693		mtx_unlock(&kenv_lock);
694		zfree(oldenv, M_KENV);
695		EVENTHANDLER_INVOKE(unsetenv, name);
696		return (0);
697	}
698	mtx_unlock(&kenv_lock);
699	return (-1);
700}
701
702/*
703 * Return the internal kenv buffer for the variable name, if it exists.
704 * If the dynamic kenv is initialized and the name is present, return
705 * with kenv_lock held.
706 */
707static char *
708kenv_acquire(const char *name)
709{
710	char *value;
711
712	if (dynamic_kenv) {
713		mtx_lock(&kenv_lock);
714		value = _getenv_dynamic(name, NULL);
715		if (value == NULL)
716			mtx_unlock(&kenv_lock);
717		return (value);
718	} else
719		return (_getenv_static(name));
720}
721
722/*
723 * Undo a previous kenv_acquire() operation
724 */
725static void
726kenv_release(const char *buf)
727{
728	if ((buf != NULL) && dynamic_kenv)
729		mtx_unlock(&kenv_lock);
730}
731
732/*
733 * Return a string value from an environment variable.
734 */
735int
736getenv_string(const char *name, char *data, int size)
737{
738	char *cp;
739
740	cp = kenv_acquire(name);
741
742	if (cp != NULL)
743		strlcpy(data, cp, size);
744
745	kenv_release(cp);
746
747	return (cp != NULL);
748}
749
750/*
751 * Return an array of integers at the given type size and signedness.
752 */
753int
754getenv_array(const char *name, void *pdata, int size, int *psize,
755    int type_size, bool allow_signed)
756{
757	uint8_t shift;
758	int64_t value;
759	int64_t old;
760	const char *buf;
761	char *end;
762	const char *ptr;
763	int n;
764	int rc;
765
766	rc = 0;			  /* assume failure */
767
768	buf = kenv_acquire(name);
769	if (buf == NULL)
770		goto error;
771
772	/* get maximum number of elements */
773	size /= type_size;
774
775	n = 0;
776
777	for (ptr = buf; *ptr != 0; ) {
778		value = strtoq(ptr, &end, 0);
779
780		/* check if signed numbers are allowed */
781		if (value < 0 && !allow_signed)
782			goto error;
783
784		/* check for invalid value */
785		if (ptr == end)
786			goto error;
787
788		/* check for valid suffix */
789		switch (*end) {
790		case 't':
791		case 'T':
792			shift = 40;
793			end++;
794			break;
795		case 'g':
796		case 'G':
797			shift = 30;
798			end++;
799			break;
800		case 'm':
801		case 'M':
802			shift = 20;
803			end++;
804			break;
805		case 'k':
806		case 'K':
807			shift = 10;
808			end++;
809			break;
810		case ' ':
811		case '\t':
812		case ',':
813		case 0:
814			shift = 0;
815			break;
816		default:
817			/* garbage after numeric value */
818			goto error;
819		}
820
821		/* skip till next value, if any */
822		while (*end == '\t' || *end == ',' || *end == ' ')
823			end++;
824
825		/* update pointer */
826		ptr = end;
827
828		/* apply shift */
829		old = value;
830		value <<= shift;
831
832		/* overflow check */
833		if ((value >> shift) != old)
834			goto error;
835
836		/* check for buffer overflow */
837		if (n >= size)
838			goto error;
839
840		/* store value according to type size */
841		switch (type_size) {
842		case 1:
843			if (allow_signed) {
844				if (value < SCHAR_MIN || value > SCHAR_MAX)
845					goto error;
846			} else {
847				if (value < 0 || value > UCHAR_MAX)
848					goto error;
849			}
850			((uint8_t *)pdata)[n] = (uint8_t)value;
851			break;
852		case 2:
853			if (allow_signed) {
854				if (value < SHRT_MIN || value > SHRT_MAX)
855					goto error;
856			} else {
857				if (value < 0 || value > USHRT_MAX)
858					goto error;
859			}
860			((uint16_t *)pdata)[n] = (uint16_t)value;
861			break;
862		case 4:
863			if (allow_signed) {
864				if (value < INT_MIN || value > INT_MAX)
865					goto error;
866			} else {
867				if (value > UINT_MAX)
868					goto error;
869			}
870			((uint32_t *)pdata)[n] = (uint32_t)value;
871			break;
872		case 8:
873			((uint64_t *)pdata)[n] = (uint64_t)value;
874			break;
875		default:
876			goto error;
877		}
878		n++;
879	}
880	*psize = n * type_size;
881
882	if (n != 0)
883		rc = 1;	/* success */
884error:
885	kenv_release(buf);
886	return (rc);
887}
888
889/*
890 * Return an integer value from an environment variable.
891 */
892int
893getenv_int(const char *name, int *data)
894{
895	quad_t tmp;
896	int rval;
897
898	rval = getenv_quad(name, &tmp);
899	if (rval)
900		*data = (int) tmp;
901	return (rval);
902}
903
904/*
905 * Return an unsigned integer value from an environment variable.
906 */
907int
908getenv_uint(const char *name, unsigned int *data)
909{
910	quad_t tmp;
911	int rval;
912
913	rval = getenv_quad(name, &tmp);
914	if (rval)
915		*data = (unsigned int) tmp;
916	return (rval);
917}
918
919/*
920 * Return an int64_t value from an environment variable.
921 */
922int
923getenv_int64(const char *name, int64_t *data)
924{
925	quad_t tmp;
926	int64_t rval;
927
928	rval = getenv_quad(name, &tmp);
929	if (rval)
930		*data = (int64_t) tmp;
931	return (rval);
932}
933
934/*
935 * Return an uint64_t value from an environment variable.
936 */
937int
938getenv_uint64(const char *name, uint64_t *data)
939{
940	quad_t tmp;
941	uint64_t rval;
942
943	rval = getenv_quad(name, &tmp);
944	if (rval)
945		*data = (uint64_t) tmp;
946	return (rval);
947}
948
949/*
950 * Return a long value from an environment variable.
951 */
952int
953getenv_long(const char *name, long *data)
954{
955	quad_t tmp;
956	int rval;
957
958	rval = getenv_quad(name, &tmp);
959	if (rval)
960		*data = (long) tmp;
961	return (rval);
962}
963
964/*
965 * Return an unsigned long value from an environment variable.
966 */
967int
968getenv_ulong(const char *name, unsigned long *data)
969{
970	quad_t tmp;
971	int rval;
972
973	rval = getenv_quad(name, &tmp);
974	if (rval)
975		*data = (unsigned long) tmp;
976	return (rval);
977}
978
979/*
980 * Return a quad_t value from an environment variable.
981 */
982int
983getenv_quad(const char *name, quad_t *data)
984{
985	const char	*value;
986	char		suffix, *vtp;
987	quad_t		iv;
988
989	value = kenv_acquire(name);
990	if (value == NULL) {
991		goto error;
992	}
993	iv = strtoq(value, &vtp, 0);
994	if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
995		goto error;
996	}
997	suffix = vtp[0];
998	kenv_release(value);
999	switch (suffix) {
1000	case 't': case 'T':
1001		iv *= 1024;
1002		/* FALLTHROUGH */
1003	case 'g': case 'G':
1004		iv *= 1024;
1005		/* FALLTHROUGH */
1006	case 'm': case 'M':
1007		iv *= 1024;
1008		/* FALLTHROUGH */
1009	case 'k': case 'K':
1010		iv *= 1024;
1011	case '\0':
1012		break;
1013	default:
1014		return (0);
1015	}
1016	*data = iv;
1017	return (1);
1018error:
1019	kenv_release(value);
1020	return (0);
1021}
1022
1023/*
1024 * Return a boolean value from an environment variable. This can be in
1025 * numerical or string form, i.e. "1" or "true".
1026 */
1027int
1028getenv_bool(const char *name, bool *data)
1029{
1030	char *val;
1031	int ret = 0;
1032
1033	if (name == NULL)
1034		return (0);
1035
1036	val = kern_getenv(name);
1037	if (val == NULL)
1038		return (0);
1039
1040	if ((strcmp(val, "1") == 0) || (strcasecmp(val, "true") == 0)) {
1041		*data = true;
1042		ret = 1;
1043	} else if ((strcmp(val, "0") == 0) || (strcasecmp(val, "false") == 0)) {
1044		*data = false;
1045		ret = 1;
1046	} else {
1047		/* Spit out a warning for malformed boolean variables. */
1048		printf("Environment variable %s has non-boolean value \"%s\"\n",
1049		    name, val);
1050	}
1051	freeenv(val);
1052
1053	return (ret);
1054}
1055
1056/*
1057 * Wrapper around getenv_bool to easily check for true.
1058 */
1059bool
1060getenv_is_true(const char *name)
1061{
1062	bool val;
1063
1064	if (getenv_bool(name, &val) != 0)
1065		return (val);
1066	return (false);
1067}
1068
1069/*
1070 * Wrapper around getenv_bool to easily check for false.
1071 */
1072bool
1073getenv_is_false(const char *name)
1074{
1075	bool val;
1076
1077	if (getenv_bool(name, &val) != 0)
1078		return (!val);
1079	return (false);
1080}
1081
1082/*
1083 * Find the next entry after the one which (cp) falls within, return a
1084 * pointer to its start or NULL if there are no more.
1085 */
1086static char *
1087kernenv_next(char *cp)
1088{
1089
1090	if (cp != NULL) {
1091		while (*cp != 0)
1092			cp++;
1093		cp++;
1094		if (*cp == 0)
1095			cp = NULL;
1096	}
1097	return (cp);
1098}
1099
1100void
1101tunable_int_init(void *data)
1102{
1103	struct tunable_int *d = (struct tunable_int *)data;
1104
1105	TUNABLE_INT_FETCH(d->path, d->var);
1106}
1107
1108void
1109tunable_long_init(void *data)
1110{
1111	struct tunable_long *d = (struct tunable_long *)data;
1112
1113	TUNABLE_LONG_FETCH(d->path, d->var);
1114}
1115
1116void
1117tunable_ulong_init(void *data)
1118{
1119	struct tunable_ulong *d = (struct tunable_ulong *)data;
1120
1121	TUNABLE_ULONG_FETCH(d->path, d->var);
1122}
1123
1124void
1125tunable_int64_init(void *data)
1126{
1127	struct tunable_int64 *d = (struct tunable_int64 *)data;
1128
1129	TUNABLE_INT64_FETCH(d->path, d->var);
1130}
1131
1132void
1133tunable_uint64_init(void *data)
1134{
1135	struct tunable_uint64 *d = (struct tunable_uint64 *)data;
1136
1137	TUNABLE_UINT64_FETCH(d->path, d->var);
1138}
1139
1140void
1141tunable_quad_init(void *data)
1142{
1143	struct tunable_quad *d = (struct tunable_quad *)data;
1144
1145	TUNABLE_QUAD_FETCH(d->path, d->var);
1146}
1147
1148void
1149tunable_bool_init(void *data)
1150{
1151	struct tunable_bool *d = (struct tunable_bool *)data;
1152
1153	TUNABLE_BOOL_FETCH(d->path, d->var);
1154}
1155
1156void
1157tunable_str_init(void *data)
1158{
1159	struct tunable_str *d = (struct tunable_str *)data;
1160
1161	TUNABLE_STR_FETCH(d->path, d->var, d->size);
1162}
1163