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