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