xref: /freebsd/sys/kern/kern_environment.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1998 Michael Smith
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * The unified bootloader passes us a pointer to a preserved copy of
31  * bootstrap/kernel environment variables.  We convert them to a
32  * dynamic array of strings later when the VM subsystem is up.
33  *
34  * We make these available through the kenv(2) syscall for userland
35  * and through kern_getenv()/freeenv() kern_setenv() kern_unsetenv() testenv() for
36  * the kernel.
37  */
38 
39 #include <sys/cdefs.h>
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kenv.h>
43 #include <sys/kernel.h>
44 #include <sys/libkern.h>
45 #include <sys/limits.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/mutex.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/queue.h>
52 #include <sys/sysent.h>
53 #include <sys/sysproto.h>
54 
55 #include <security/mac/mac_framework.h>
56 
57 static char *_getenv_dynamic_locked(const char *name, int *idx);
58 static char *_getenv_dynamic(const char *name, int *idx);
59 
60 static char *kenv_acquire(const char *name);
61 static void kenv_release(const char *buf);
62 
63 static MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
64 
65 #define KENV_SIZE	512	/* Maximum number of environment strings */
66 
67 static uma_zone_t kenv_zone;
68 static int	kenv_mvallen = KENV_MVALLEN;
69 
70 /* pointer to the config-generated static environment */
71 char		*kern_envp;
72 
73 /* pointer to the md-static environment */
74 char		*md_envp;
75 static int	md_env_len;
76 static int	md_env_pos;
77 
78 static char	*kernenv_next(char *);
79 
80 /* dynamic environment variables */
81 char		**kenvp;
82 struct mtx	kenv_lock;
83 
84 /*
85  * No need to protect this with a mutex since SYSINITS are single threaded.
86  */
87 bool	dynamic_kenv;
88 
89 #define KENV_CHECK	if (!dynamic_kenv) \
90 			    panic("%s: called before SI_SUB_KMEM", __func__)
91 
92 static int
93 kenv_dump(struct thread *td, char **envp, int what, char *value, int len)
94 {
95 	char *buffer, *senv;
96 	size_t done, needed, buflen;
97 	int error;
98 
99 	error = 0;
100 	buffer = NULL;
101 	done = needed = 0;
102 
103 	MPASS(what == KENV_DUMP || what == KENV_DUMP_LOADER ||
104 	    what == KENV_DUMP_STATIC);
105 
106 	/*
107 	 * For non-dynamic kernel environment, we pass in either md_envp or
108 	 * kern_envp and we must traverse with kernenv_next().  This shuffling
109 	 * of pointers simplifies the below loop by only differing in how envp
110 	 * is modified.
111 	 */
112 	if (what != KENV_DUMP) {
113 		senv = (char *)envp;
114 		envp = &senv;
115 	}
116 
117 	buflen = len;
118 	if (buflen > KENV_SIZE * (KENV_MNAMELEN + kenv_mvallen + 2))
119 		buflen = KENV_SIZE * (KENV_MNAMELEN +
120 		    kenv_mvallen + 2);
121 	if (len > 0 && value != NULL)
122 		buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
123 
124 	/* Only take the lock for the dynamic kenv. */
125 	if (what == KENV_DUMP)
126 		mtx_lock(&kenv_lock);
127 	while (*envp != NULL) {
128 		len = strlen(*envp) + 1;
129 		needed += len;
130 		len = min(len, buflen - done);
131 		/*
132 		 * If called with a NULL or insufficiently large
133 		 * buffer, just keep computing the required size.
134 		 */
135 		if (value != NULL && buffer != NULL && len > 0) {
136 			bcopy(*envp, buffer + done, len);
137 			done += len;
138 		}
139 
140 		/* Advance the pointer depending on the kenv format. */
141 		if (what == KENV_DUMP)
142 			envp++;
143 		else
144 			senv = kernenv_next(senv);
145 	}
146 	if (what == KENV_DUMP)
147 		mtx_unlock(&kenv_lock);
148 	if (buffer != NULL) {
149 		error = copyout(buffer, value, done);
150 		free(buffer, M_TEMP);
151 	}
152 	td->td_retval[0] = ((done == needed) ? 0 : needed);
153 	return (error);
154 }
155 
156 int
157 sys_kenv(struct thread *td, struct kenv_args *uap)
158 {
159 	char *name, *value;
160 	size_t len;
161 	int error;
162 
163 	KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = false"));
164 
165 	error = 0;
166 
167 	switch (uap->what) {
168 	case KENV_DUMP:
169 #ifdef MAC
170 		error = mac_kenv_check_dump(td->td_ucred);
171 		if (error)
172 			return (error);
173 #endif
174 		return (kenv_dump(td, kenvp, uap->what, uap->value, uap->len));
175 	case KENV_DUMP_LOADER:
176 	case KENV_DUMP_STATIC:
177 #ifdef MAC
178 		error = mac_kenv_check_dump(td->td_ucred);
179 		if (error)
180 			return (error);
181 #endif
182 #ifdef PRESERVE_EARLY_KENV
183 		return (kenv_dump(td,
184 		    uap->what == KENV_DUMP_LOADER ? (char **)md_envp :
185 		    (char **)kern_envp, uap->what, uap->value, uap->len));
186 #else
187 		return (ENOENT);
188 #endif
189 	case KENV_SET:
190 		error = priv_check(td, PRIV_KENV_SET);
191 		if (error)
192 			return (error);
193 		break;
194 
195 	case KENV_UNSET:
196 		error = priv_check(td, PRIV_KENV_UNSET);
197 		if (error)
198 			return (error);
199 		break;
200 	}
201 
202 	name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
203 
204 	error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
205 	if (error)
206 		goto done;
207 
208 	switch (uap->what) {
209 	case KENV_GET:
210 #ifdef MAC
211 		error = mac_kenv_check_get(td->td_ucred, name);
212 		if (error)
213 			goto done;
214 #endif
215 		value = kern_getenv(name);
216 		if (value == NULL) {
217 			error = ENOENT;
218 			goto done;
219 		}
220 		len = strlen(value) + 1;
221 		if (len > uap->len)
222 			len = uap->len;
223 		error = copyout(value, uap->value, len);
224 		freeenv(value);
225 		if (error)
226 			goto done;
227 		td->td_retval[0] = len;
228 		break;
229 	case KENV_SET:
230 		len = uap->len;
231 		if (len < 1) {
232 			error = EINVAL;
233 			goto done;
234 		}
235 		if (len > kenv_mvallen + 1)
236 			len = kenv_mvallen + 1;
237 		value = malloc(len, M_TEMP, M_WAITOK);
238 		error = copyinstr(uap->value, value, len, NULL);
239 		if (error) {
240 			free(value, M_TEMP);
241 			goto done;
242 		}
243 #ifdef MAC
244 		error = mac_kenv_check_set(td->td_ucred, name, value);
245 		if (error == 0)
246 #endif
247 			kern_setenv(name, value);
248 		free(value, M_TEMP);
249 		break;
250 	case KENV_UNSET:
251 #ifdef MAC
252 		error = mac_kenv_check_unset(td->td_ucred, name);
253 		if (error)
254 			goto done;
255 #endif
256 		error = kern_unsetenv(name);
257 		if (error)
258 			error = ENOENT;
259 		break;
260 	default:
261 		error = EINVAL;
262 		break;
263 	}
264 done:
265 	free(name, M_TEMP);
266 	return (error);
267 }
268 
269 /*
270  * Populate the initial kernel environment.
271  *
272  * This is called very early in MD startup, either to provide a copy of the
273  * environment obtained from a boot loader, or to provide an empty buffer into
274  * which MD code can store an initial environment using kern_setenv() calls.
275  *
276  * kern_envp is set to the static_env generated by config(8).  This implements
277  * the env keyword described in config(5).
278  *
279  * If len is non-zero, the caller is providing an empty buffer.  The caller will
280  * subsequently use kern_setenv() to add up to len bytes of initial environment
281  * before the dynamic environment is available.
282  *
283  * If len is zero, the caller is providing a pre-loaded buffer containing
284  * environment strings.  Additional strings cannot be added until the dynamic
285  * environment is available.  The memory pointed to must remain stable at least
286  * until sysinit runs init_dynamic_kenv() and preferably until after SI_SUB_KMEM
287  * is finished so that subr_hints routines may continue to use it until the
288  * environments have been fully merged at the end of the pass.  If no initial
289  * environment is available from the boot loader, passing a NULL pointer allows
290  * the static_env to be installed if it is configured.  In this case, any call
291  * to kern_setenv() prior to the setup of the dynamic environment will result in
292  * a panic.
293  */
294 void
295 init_static_kenv(char *buf, size_t len)
296 {
297 
298 	KASSERT(!dynamic_kenv, ("kenv: dynamic_kenv already initialized"));
299 	/*
300 	 * Suitably sized means it must be able to hold at least one empty
301 	 * variable, otherwise things go belly up if a kern_getenv call is
302 	 * made without a prior call to kern_setenv as we have a malformed
303 	 * environment.
304 	 */
305 	KASSERT(len == 0 || len >= 2,
306 	    ("kenv: static env must be initialized or suitably sized"));
307 	KASSERT(len == 0 || (*buf == '\0' && *(buf + 1) == '\0'),
308 	    ("kenv: sized buffer must be initially empty"));
309 
310 	/*
311 	 * We may be called twice, with the second call needed to relocate
312 	 * md_envp after enabling paging.  md_envp is then garbage if it is
313 	 * not null and the relocation will move it.  Discard it so as to
314 	 * not crash using its old value in our first call to kern_getenv().
315 	 *
316 	 * The second call gives the same environment as the first except
317 	 * in silly configurations where the static env disables itself.
318 	 *
319 	 * Other env calls don't handle possibly-garbage pointers, so must
320 	 * not be made between enabling paging and calling here.
321 	 */
322 	md_envp = NULL;
323 	md_env_len = 0;
324 	md_env_pos = 0;
325 
326 	/*
327 	 * Give the static environment a chance to disable the loader(8)
328 	 * environment first.  This is done with loader_env.disabled=1.
329 	 *
330 	 * static_env and static_hints may both be disabled, but in slightly
331 	 * different ways.  For static_env, we just don't setup kern_envp and
332 	 * it's as if a static env wasn't even provided.  For static_hints,
333 	 * we effectively zero out the buffer to stop the rest of the kernel
334 	 * from being able to use it.
335 	 *
336 	 * We're intentionally setting this up so that static_hints.disabled may
337 	 * be specified in either the MD env or the static env. This keeps us
338 	 * consistent in our new world view.
339 	 *
340 	 * As a warning, the static environment may not be disabled in any way
341 	 * if the static environment has disabled the loader environment.
342 	 */
343 	kern_envp = static_env;
344 	if (!getenv_is_true("loader_env.disabled")) {
345 		md_envp = buf;
346 		md_env_len = len;
347 		md_env_pos = 0;
348 
349 		if (getenv_is_true("static_env.disabled")) {
350 			kern_envp[0] = '\0';
351 			kern_envp[1] = '\0';
352 		}
353 	}
354 	if (getenv_is_true("static_hints.disabled")) {
355 		static_hints[0] = '\0';
356 		static_hints[1] = '\0';
357 	}
358 }
359 
360 /* Maximum suffix number appended for duplicate environment variable names. */
361 #define MAXSUFFIX 9999
362 #define SUFFIXLEN strlen("_" __XSTRING(MAXSUFFIX))
363 
364 static void
365 getfreesuffix(char *cp, size_t *n)
366 {
367 	size_t len = strlen(cp);
368 	char * ncp;
369 
370 	ncp = malloc(len + SUFFIXLEN + 1, M_KENV, M_WAITOK);
371 	memcpy(ncp, cp, len);
372 	for (*n = 1; *n <= MAXSUFFIX; (*n)++) {
373 		sprintf(&ncp[len], "_%zu", *n);
374 		if (!_getenv_dynamic_locked(ncp, NULL))
375 			break;
376 	}
377 	free(ncp, M_KENV);
378 	if (*n > MAXSUFFIX)
379 		panic("Too many duplicate kernel environment values: %s", cp);
380 }
381 
382 static void
383 init_dynamic_kenv_from(char *init_env, int *curpos)
384 {
385 	char *cp, *cpnext, *eqpos, *found;
386 	size_t len, n;
387 	int i;
388 
389 	if (init_env && *init_env != '\0') {
390 		found = NULL;
391 		i = *curpos;
392 		for (cp = init_env; cp != NULL; cp = cpnext) {
393 			cpnext = kernenv_next(cp);
394 			len = strlen(cp) + 1;
395 			if (i > KENV_SIZE) {
396 				printf(
397 				"WARNING: too many kenv strings, ignoring %s\n",
398 				    cp);
399 				goto sanitize;
400 			}
401 			if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
402 				printf(
403 				"WARNING: too long kenv string, ignoring %s\n",
404 				    cp);
405 				goto sanitize;
406 			}
407 			eqpos = strchr(cp, '=');
408 			if (eqpos == NULL) {
409 				printf(
410 				"WARNING: malformed static env value, ignoring %s\n",
411 				    cp);
412 				goto sanitize;
413 			}
414 			*eqpos = 0;
415 			/*
416 			 * Handle duplicates in the environment as we go; we
417 			 * add the duplicated assignments with _N suffixes.
418 			 * This ensures that (a) if a variable is set in the
419 			 * static environment and in the "loader" environment
420 			 * provided by MD code, the value from the loader will
421 			 * have the expected variable name and the value from
422 			 * the static environment will have the suffix; and (b)
423 			 * if the "loader" environment has the same variable
424 			 * set multiple times (as is possible with values being
425 			 * passed via the kernel "command line") the extra
426 			 * values are visible to code which knows where to look
427 			 * for them.
428 			 */
429 			found = _getenv_dynamic_locked(cp, NULL);
430 			if (found != NULL) {
431 				getfreesuffix(cp, &n);
432 				kenvp[i] = malloc(len + SUFFIXLEN,
433 				    M_KENV, M_WAITOK);
434 				sprintf(kenvp[i++], "%s_%zu=%s", cp, n,
435 				    &eqpos[1]);
436 			} else {
437 				kenvp[i] = malloc(len, M_KENV, M_WAITOK);
438 				*eqpos = '=';
439 				strcpy(kenvp[i++], cp);
440 			}
441 sanitize:
442 #ifdef PRESERVE_EARLY_KENV
443 			continue;
444 #else
445 			explicit_bzero(cp, len - 1);
446 #endif
447 		}
448 		*curpos = i;
449 	}
450 }
451 
452 /*
453  * Setup the dynamic kernel environment.
454  */
455 static void
456 init_dynamic_kenv(void *data __unused)
457 {
458 	int dynamic_envpos;
459 	int size;
460 
461 	TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
462 	size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
463 
464 	kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
465 	    UMA_ALIGN_PTR, 0);
466 
467 	kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
468 		M_WAITOK | M_ZERO);
469 
470 	dynamic_envpos = 0;
471 	init_dynamic_kenv_from(md_envp, &dynamic_envpos);
472 	init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
473 	kenvp[dynamic_envpos] = NULL;
474 
475 	mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
476 	dynamic_kenv = true;
477 }
478 SYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
479 
480 void
481 freeenv(char *env)
482 {
483 
484 	if (dynamic_kenv && env != NULL) {
485 		explicit_bzero(env, strlen(env));
486 		uma_zfree(kenv_zone, env);
487 	}
488 }
489 
490 /*
491  * Internal functions for string lookup.
492  */
493 static char *
494 _getenv_dynamic_locked(const char *name, int *idx)
495 {
496 	char *cp;
497 	int len, i;
498 
499 	len = strlen(name);
500 	for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
501 		if ((strncmp(cp, name, len) == 0) &&
502 		    (cp[len] == '=')) {
503 			if (idx != NULL)
504 				*idx = i;
505 			return (cp + len + 1);
506 		}
507 	}
508 	return (NULL);
509 }
510 
511 static char *
512 _getenv_dynamic(const char *name, int *idx)
513 {
514 
515 	mtx_assert(&kenv_lock, MA_OWNED);
516 	return (_getenv_dynamic_locked(name, idx));
517 }
518 
519 static char *
520 _getenv_static_from(char *chkenv, const char *name)
521 {
522 	char *cp, *ep;
523 	int len;
524 
525 	for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
526 		for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
527 			;
528 		if (*ep != '=')
529 			continue;
530 		len = ep - cp;
531 		ep++;
532 		if (!strncmp(name, cp, len) && name[len] == 0)
533 			return (ep);
534 	}
535 	return (NULL);
536 }
537 
538 static char *
539 _getenv_static(const char *name)
540 {
541 	char *val;
542 
543 	val = _getenv_static_from(md_envp, name);
544 	if (val != NULL)
545 		return (val);
546 	val = _getenv_static_from(kern_envp, name);
547 	if (val != NULL)
548 		return (val);
549 	return (NULL);
550 }
551 
552 /*
553  * Look up an environment variable by name.
554  * Return a pointer to the string if found.
555  * The pointer has to be freed with freeenv()
556  * after use.
557  */
558 char *
559 kern_getenv(const char *name)
560 {
561 	char *cp, *ret;
562 	int len;
563 
564 	if (dynamic_kenv) {
565 		len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
566 		ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
567 		mtx_lock(&kenv_lock);
568 		cp = _getenv_dynamic(name, NULL);
569 		if (cp != NULL)
570 			strlcpy(ret, cp, len);
571 		mtx_unlock(&kenv_lock);
572 		if (cp == NULL) {
573 			uma_zfree(kenv_zone, ret);
574 			ret = NULL;
575 		}
576 	} else
577 		ret = _getenv_static(name);
578 
579 	return (ret);
580 }
581 
582 /*
583  * Test if an environment variable is defined.
584  */
585 int
586 testenv(const char *name)
587 {
588 	char *cp;
589 
590 	cp = kenv_acquire(name);
591 	kenv_release(cp);
592 
593 	if (cp != NULL)
594 		return (1);
595 	return (0);
596 }
597 
598 /*
599  * Set an environment variable in the MD-static environment.  This cannot
600  * feasibly be done on config(8)-generated static environments as they don't
601  * generally include space for extra variables.
602  */
603 static int
604 setenv_static(const char *name, const char *value)
605 {
606 	int len;
607 
608 	if (md_env_pos >= md_env_len)
609 		return (-1);
610 
611 	/* Check space for x=y and two nuls */
612 	len = strlen(name) + strlen(value);
613 	if (len + 3 < md_env_len - md_env_pos) {
614 		len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
615 		md_env_pos += len+1;
616 		md_envp[md_env_pos] = '\0';
617 		return (0);
618 	} else
619 		return (-1);
620 
621 }
622 
623 /*
624  * Set an environment variable by name.
625  */
626 int
627 kern_setenv(const char *name, const char *value)
628 {
629 	char *buf, *cp, *oldenv;
630 	int namelen, vallen, i;
631 
632 	if (!dynamic_kenv && md_env_len > 0)
633 		return (setenv_static(name, value));
634 
635 	KENV_CHECK;
636 
637 	namelen = strlen(name) + 1;
638 	if (namelen > KENV_MNAMELEN + 1)
639 		return (-1);
640 	vallen = strlen(value) + 1;
641 	if (vallen > kenv_mvallen + 1)
642 		return (-1);
643 	buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
644 	sprintf(buf, "%s=%s", name, value);
645 
646 	mtx_lock(&kenv_lock);
647 	cp = _getenv_dynamic(name, &i);
648 	if (cp != NULL) {
649 		oldenv = kenvp[i];
650 		kenvp[i] = buf;
651 		mtx_unlock(&kenv_lock);
652 		free(oldenv, M_KENV);
653 	} else {
654 		/* We add the option if it wasn't found */
655 		for (i = 0; (cp = kenvp[i]) != NULL; i++)
656 			;
657 
658 		/* Bounds checking */
659 		if (i < 0 || i >= KENV_SIZE) {
660 			free(buf, M_KENV);
661 			mtx_unlock(&kenv_lock);
662 			return (-1);
663 		}
664 
665 		kenvp[i] = buf;
666 		kenvp[i + 1] = NULL;
667 		mtx_unlock(&kenv_lock);
668 	}
669 	return (0);
670 }
671 
672 /*
673  * Unset an environment variable string.
674  */
675 int
676 kern_unsetenv(const char *name)
677 {
678 	char *cp, *oldenv;
679 	int i, j;
680 
681 	KENV_CHECK;
682 
683 	mtx_lock(&kenv_lock);
684 	cp = _getenv_dynamic(name, &i);
685 	if (cp != NULL) {
686 		oldenv = kenvp[i];
687 		for (j = i + 1; kenvp[j] != NULL; j++)
688 			kenvp[i++] = kenvp[j];
689 		kenvp[i] = NULL;
690 		mtx_unlock(&kenv_lock);
691 		zfree(oldenv, M_KENV);
692 		return (0);
693 	}
694 	mtx_unlock(&kenv_lock);
695 	return (-1);
696 }
697 
698 /*
699  * Return the internal kenv buffer for the variable name, if it exists.
700  * If the dynamic kenv is initialized and the name is present, return
701  * with kenv_lock held.
702  */
703 static char *
704 kenv_acquire(const char *name)
705 {
706 	char *value;
707 
708 	if (dynamic_kenv) {
709 		mtx_lock(&kenv_lock);
710 		value = _getenv_dynamic(name, NULL);
711 		if (value == NULL)
712 			mtx_unlock(&kenv_lock);
713 		return (value);
714 	} else
715 		return (_getenv_static(name));
716 }
717 
718 /*
719  * Undo a previous kenv_acquire() operation
720  */
721 static void
722 kenv_release(const char *buf)
723 {
724 	if ((buf != NULL) && dynamic_kenv)
725 		mtx_unlock(&kenv_lock);
726 }
727 
728 /*
729  * Return a string value from an environment variable.
730  */
731 int
732 getenv_string(const char *name, char *data, int size)
733 {
734 	char *cp;
735 
736 	cp = kenv_acquire(name);
737 
738 	if (cp != NULL)
739 		strlcpy(data, cp, size);
740 
741 	kenv_release(cp);
742 
743 	return (cp != NULL);
744 }
745 
746 /*
747  * Return an array of integers at the given type size and signedness.
748  */
749 int
750 getenv_array(const char *name, void *pdata, int size, int *psize,
751     int type_size, bool allow_signed)
752 {
753 	uint8_t shift;
754 	int64_t value;
755 	int64_t old;
756 	const char *buf;
757 	char *end;
758 	const char *ptr;
759 	int n;
760 	int rc;
761 
762 	rc = 0;			  /* assume failure */
763 
764 	buf = kenv_acquire(name);
765 	if (buf == NULL)
766 		goto error;
767 
768 	/* get maximum number of elements */
769 	size /= type_size;
770 
771 	n = 0;
772 
773 	for (ptr = buf; *ptr != 0; ) {
774 		value = strtoq(ptr, &end, 0);
775 
776 		/* check if signed numbers are allowed */
777 		if (value < 0 && !allow_signed)
778 			goto error;
779 
780 		/* check for invalid value */
781 		if (ptr == end)
782 			goto error;
783 
784 		/* check for valid suffix */
785 		switch (*end) {
786 		case 't':
787 		case 'T':
788 			shift = 40;
789 			end++;
790 			break;
791 		case 'g':
792 		case 'G':
793 			shift = 30;
794 			end++;
795 			break;
796 		case 'm':
797 		case 'M':
798 			shift = 20;
799 			end++;
800 			break;
801 		case 'k':
802 		case 'K':
803 			shift = 10;
804 			end++;
805 			break;
806 		case ' ':
807 		case '\t':
808 		case ',':
809 		case 0:
810 			shift = 0;
811 			break;
812 		default:
813 			/* garbage after numeric value */
814 			goto error;
815 		}
816 
817 		/* skip till next value, if any */
818 		while (*end == '\t' || *end == ',' || *end == ' ')
819 			end++;
820 
821 		/* update pointer */
822 		ptr = end;
823 
824 		/* apply shift */
825 		old = value;
826 		value <<= shift;
827 
828 		/* overflow check */
829 		if ((value >> shift) != old)
830 			goto error;
831 
832 		/* check for buffer overflow */
833 		if (n >= size)
834 			goto error;
835 
836 		/* store value according to type size */
837 		switch (type_size) {
838 		case 1:
839 			if (allow_signed) {
840 				if (value < SCHAR_MIN || value > SCHAR_MAX)
841 					goto error;
842 			} else {
843 				if (value < 0 || value > UCHAR_MAX)
844 					goto error;
845 			}
846 			((uint8_t *)pdata)[n] = (uint8_t)value;
847 			break;
848 		case 2:
849 			if (allow_signed) {
850 				if (value < SHRT_MIN || value > SHRT_MAX)
851 					goto error;
852 			} else {
853 				if (value < 0 || value > USHRT_MAX)
854 					goto error;
855 			}
856 			((uint16_t *)pdata)[n] = (uint16_t)value;
857 			break;
858 		case 4:
859 			if (allow_signed) {
860 				if (value < INT_MIN || value > INT_MAX)
861 					goto error;
862 			} else {
863 				if (value > UINT_MAX)
864 					goto error;
865 			}
866 			((uint32_t *)pdata)[n] = (uint32_t)value;
867 			break;
868 		case 8:
869 			((uint64_t *)pdata)[n] = (uint64_t)value;
870 			break;
871 		default:
872 			goto error;
873 		}
874 		n++;
875 	}
876 	*psize = n * type_size;
877 
878 	if (n != 0)
879 		rc = 1;	/* success */
880 error:
881 	kenv_release(buf);
882 	return (rc);
883 }
884 
885 /*
886  * Return an integer value from an environment variable.
887  */
888 int
889 getenv_int(const char *name, int *data)
890 {
891 	quad_t tmp;
892 	int rval;
893 
894 	rval = getenv_quad(name, &tmp);
895 	if (rval)
896 		*data = (int) tmp;
897 	return (rval);
898 }
899 
900 /*
901  * Return an unsigned integer value from an environment variable.
902  */
903 int
904 getenv_uint(const char *name, unsigned int *data)
905 {
906 	quad_t tmp;
907 	int rval;
908 
909 	rval = getenv_quad(name, &tmp);
910 	if (rval)
911 		*data = (unsigned int) tmp;
912 	return (rval);
913 }
914 
915 /*
916  * Return an int64_t value from an environment variable.
917  */
918 int
919 getenv_int64(const char *name, int64_t *data)
920 {
921 	quad_t tmp;
922 	int64_t rval;
923 
924 	rval = getenv_quad(name, &tmp);
925 	if (rval)
926 		*data = (int64_t) tmp;
927 	return (rval);
928 }
929 
930 /*
931  * Return an uint64_t value from an environment variable.
932  */
933 int
934 getenv_uint64(const char *name, uint64_t *data)
935 {
936 	quad_t tmp;
937 	uint64_t rval;
938 
939 	rval = getenv_quad(name, &tmp);
940 	if (rval)
941 		*data = (uint64_t) tmp;
942 	return (rval);
943 }
944 
945 /*
946  * Return a long value from an environment variable.
947  */
948 int
949 getenv_long(const char *name, long *data)
950 {
951 	quad_t tmp;
952 	int rval;
953 
954 	rval = getenv_quad(name, &tmp);
955 	if (rval)
956 		*data = (long) tmp;
957 	return (rval);
958 }
959 
960 /*
961  * Return an unsigned long value from an environment variable.
962  */
963 int
964 getenv_ulong(const char *name, unsigned long *data)
965 {
966 	quad_t tmp;
967 	int rval;
968 
969 	rval = getenv_quad(name, &tmp);
970 	if (rval)
971 		*data = (unsigned long) tmp;
972 	return (rval);
973 }
974 
975 /*
976  * Return a quad_t value from an environment variable.
977  */
978 int
979 getenv_quad(const char *name, quad_t *data)
980 {
981 	const char	*value;
982 	char		suffix, *vtp;
983 	quad_t		iv;
984 
985 	value = kenv_acquire(name);
986 	if (value == NULL) {
987 		goto error;
988 	}
989 	iv = strtoq(value, &vtp, 0);
990 	if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
991 		goto error;
992 	}
993 	suffix = vtp[0];
994 	kenv_release(value);
995 	switch (suffix) {
996 	case 't': case 'T':
997 		iv *= 1024;
998 		/* FALLTHROUGH */
999 	case 'g': case 'G':
1000 		iv *= 1024;
1001 		/* FALLTHROUGH */
1002 	case 'm': case 'M':
1003 		iv *= 1024;
1004 		/* FALLTHROUGH */
1005 	case 'k': case 'K':
1006 		iv *= 1024;
1007 	case '\0':
1008 		break;
1009 	default:
1010 		return (0);
1011 	}
1012 	*data = iv;
1013 	return (1);
1014 error:
1015 	kenv_release(value);
1016 	return (0);
1017 }
1018 
1019 /*
1020  * Return a boolean value from an environment variable. This can be in
1021  * numerical or string form, i.e. "1" or "true".
1022  */
1023 int
1024 getenv_bool(const char *name, bool *data)
1025 {
1026 	char *val;
1027 	int ret = 0;
1028 
1029 	if (name == NULL)
1030 		return (0);
1031 
1032 	val = kern_getenv(name);
1033 	if (val == NULL)
1034 		return (0);
1035 
1036 	if ((strcmp(val, "1") == 0) || (strcasecmp(val, "true") == 0)) {
1037 		*data = true;
1038 		ret = 1;
1039 	} else if ((strcmp(val, "0") == 0) || (strcasecmp(val, "false") == 0)) {
1040 		*data = false;
1041 		ret = 1;
1042 	} else {
1043 		/* Spit out a warning for malformed boolean variables. */
1044 		printf("Environment variable %s has non-boolean value \"%s\"\n",
1045 		    name, val);
1046 	}
1047 	freeenv(val);
1048 
1049 	return (ret);
1050 }
1051 
1052 /*
1053  * Wrapper around getenv_bool to easily check for true.
1054  */
1055 bool
1056 getenv_is_true(const char *name)
1057 {
1058 	bool val;
1059 
1060 	if (getenv_bool(name, &val) != 0)
1061 		return (val);
1062 	return (false);
1063 }
1064 
1065 /*
1066  * Wrapper around getenv_bool to easily check for false.
1067  */
1068 bool
1069 getenv_is_false(const char *name)
1070 {
1071 	bool val;
1072 
1073 	if (getenv_bool(name, &val) != 0)
1074 		return (!val);
1075 	return (false);
1076 }
1077 
1078 /*
1079  * Find the next entry after the one which (cp) falls within, return a
1080  * pointer to its start or NULL if there are no more.
1081  */
1082 static char *
1083 kernenv_next(char *cp)
1084 {
1085 
1086 	if (cp != NULL) {
1087 		while (*cp != 0)
1088 			cp++;
1089 		cp++;
1090 		if (*cp == 0)
1091 			cp = NULL;
1092 	}
1093 	return (cp);
1094 }
1095 
1096 void
1097 tunable_int_init(void *data)
1098 {
1099 	struct tunable_int *d = (struct tunable_int *)data;
1100 
1101 	TUNABLE_INT_FETCH(d->path, d->var);
1102 }
1103 
1104 void
1105 tunable_long_init(void *data)
1106 {
1107 	struct tunable_long *d = (struct tunable_long *)data;
1108 
1109 	TUNABLE_LONG_FETCH(d->path, d->var);
1110 }
1111 
1112 void
1113 tunable_ulong_init(void *data)
1114 {
1115 	struct tunable_ulong *d = (struct tunable_ulong *)data;
1116 
1117 	TUNABLE_ULONG_FETCH(d->path, d->var);
1118 }
1119 
1120 void
1121 tunable_int64_init(void *data)
1122 {
1123 	struct tunable_int64 *d = (struct tunable_int64 *)data;
1124 
1125 	TUNABLE_INT64_FETCH(d->path, d->var);
1126 }
1127 
1128 void
1129 tunable_uint64_init(void *data)
1130 {
1131 	struct tunable_uint64 *d = (struct tunable_uint64 *)data;
1132 
1133 	TUNABLE_UINT64_FETCH(d->path, d->var);
1134 }
1135 
1136 void
1137 tunable_quad_init(void *data)
1138 {
1139 	struct tunable_quad *d = (struct tunable_quad *)data;
1140 
1141 	TUNABLE_QUAD_FETCH(d->path, d->var);
1142 }
1143 
1144 void
1145 tunable_bool_init(void *data)
1146 {
1147 	struct tunable_bool *d = (struct tunable_bool *)data;
1148 
1149 	TUNABLE_BOOL_FETCH(d->path, d->var);
1150 }
1151 
1152 void
1153 tunable_str_init(void *data)
1154 {
1155 	struct tunable_str *d = (struct tunable_str *)data;
1156 
1157 	TUNABLE_STR_FETCH(d->path, d->var, d->size);
1158 }
1159