xref: /freebsd-13-stable/sys/kern/kern_environment.c (revision 3bc80996974a61a4223eae4c1ccd47b6ee32a48a)
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/proc.h>
42 #include <sys/queue.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mutex.h>
46 #include <sys/priv.h>
47 #include <sys/kenv.h>
48 #include <sys/kernel.h>
49 #include <sys/systm.h>
50 #include <sys/sysproto.h>
51 #include <sys/libkern.h>
52 #include <sys/kenv.h>
53 #include <sys/limits.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
kenv_dump(struct thread * td,char ** envp,int what,char * value,int len)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
sys_kenv(struct thread * td,struct kenv_args * uap)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
init_static_kenv(char * buf,size_t len)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 static void
init_dynamic_kenv_from(char * init_env,int * curpos)361 init_dynamic_kenv_from(char *init_env, int *curpos)
362 {
363 	char *cp, *cpnext, *eqpos, *found;
364 	size_t len;
365 	int i;
366 
367 	if (init_env && *init_env != '\0') {
368 		found = NULL;
369 		i = *curpos;
370 		for (cp = init_env; cp != NULL; cp = cpnext) {
371 			cpnext = kernenv_next(cp);
372 			len = strlen(cp) + 1;
373 			if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
374 				printf(
375 				"WARNING: too long kenv string, ignoring %s\n",
376 				    cp);
377 				goto sanitize;
378 			}
379 			eqpos = strchr(cp, '=');
380 			if (eqpos == NULL) {
381 				printf(
382 				"WARNING: malformed static env value, ignoring %s\n",
383 				    cp);
384 				goto sanitize;
385 			}
386 			*eqpos = 0;
387 			/*
388 			 * De-dupe the environment as we go.  We don't add the
389 			 * duplicated assignments because config(8) will flip
390 			 * the order of the static environment around to make
391 			 * kernel processing match the order of specification
392 			 * in the kernel config.
393 			 */
394 			found = _getenv_dynamic_locked(cp, NULL);
395 			*eqpos = '=';
396 			if (found != NULL)
397 				goto sanitize;
398 			if (i > KENV_SIZE) {
399 				printf(
400 				"WARNING: too many kenv strings, ignoring %s\n",
401 				    cp);
402 				goto sanitize;
403 			}
404 
405 			kenvp[i] = malloc(len, M_KENV, M_WAITOK);
406 			strcpy(kenvp[i++], cp);
407 sanitize:
408 #ifdef PRESERVE_EARLY_KENV
409 			continue;
410 #else
411 			explicit_bzero(cp, len - 1);
412 #endif
413 		}
414 		*curpos = i;
415 	}
416 }
417 
418 /*
419  * Setup the dynamic kernel environment.
420  */
421 static void
init_dynamic_kenv(void * data __unused)422 init_dynamic_kenv(void *data __unused)
423 {
424 	int dynamic_envpos;
425 	int size;
426 
427 	TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
428 	size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
429 
430 	kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
431 	    UMA_ALIGN_PTR, 0);
432 
433 	kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
434 		M_WAITOK | M_ZERO);
435 
436 	dynamic_envpos = 0;
437 	init_dynamic_kenv_from(md_envp, &dynamic_envpos);
438 	init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
439 	kenvp[dynamic_envpos] = NULL;
440 
441 	mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
442 	dynamic_kenv = true;
443 }
444 SYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
445 
446 void
freeenv(char * env)447 freeenv(char *env)
448 {
449 
450 	if (dynamic_kenv && env != NULL) {
451 		explicit_bzero(env, strlen(env));
452 		uma_zfree(kenv_zone, env);
453 	}
454 }
455 
456 /*
457  * Internal functions for string lookup.
458  */
459 static char *
_getenv_dynamic_locked(const char * name,int * idx)460 _getenv_dynamic_locked(const char *name, int *idx)
461 {
462 	char *cp;
463 	int len, i;
464 
465 	len = strlen(name);
466 	for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
467 		if ((strncmp(cp, name, len) == 0) &&
468 		    (cp[len] == '=')) {
469 			if (idx != NULL)
470 				*idx = i;
471 			return (cp + len + 1);
472 		}
473 	}
474 	return (NULL);
475 }
476 
477 static char *
_getenv_dynamic(const char * name,int * idx)478 _getenv_dynamic(const char *name, int *idx)
479 {
480 
481 	mtx_assert(&kenv_lock, MA_OWNED);
482 	return (_getenv_dynamic_locked(name, idx));
483 }
484 
485 static char *
_getenv_static_from(char * chkenv,const char * name)486 _getenv_static_from(char *chkenv, const char *name)
487 {
488 	char *cp, *ep;
489 	int len;
490 
491 	for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
492 		for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
493 			;
494 		if (*ep != '=')
495 			continue;
496 		len = ep - cp;
497 		ep++;
498 		if (!strncmp(name, cp, len) && name[len] == 0)
499 			return (ep);
500 	}
501 	return (NULL);
502 }
503 
504 static char *
_getenv_static(const char * name)505 _getenv_static(const char *name)
506 {
507 	char *val;
508 
509 	val = _getenv_static_from(md_envp, name);
510 	if (val != NULL)
511 		return (val);
512 	val = _getenv_static_from(kern_envp, name);
513 	if (val != NULL)
514 		return (val);
515 	return (NULL);
516 }
517 
518 /*
519  * Look up an environment variable by name.
520  * Return a pointer to the string if found.
521  * The pointer has to be freed with freeenv()
522  * after use.
523  */
524 char *
kern_getenv(const char * name)525 kern_getenv(const char *name)
526 {
527 	char *cp, *ret;
528 	int len;
529 
530 	if (dynamic_kenv) {
531 		len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
532 		ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
533 		mtx_lock(&kenv_lock);
534 		cp = _getenv_dynamic(name, NULL);
535 		if (cp != NULL)
536 			strlcpy(ret, cp, len);
537 		mtx_unlock(&kenv_lock);
538 		if (cp == NULL) {
539 			uma_zfree(kenv_zone, ret);
540 			ret = NULL;
541 		}
542 	} else
543 		ret = _getenv_static(name);
544 
545 	return (ret);
546 }
547 
548 /*
549  * Test if an environment variable is defined.
550  */
551 int
testenv(const char * name)552 testenv(const char *name)
553 {
554 	char *cp;
555 
556 	cp = kenv_acquire(name);
557 	kenv_release(cp);
558 
559 	if (cp != NULL)
560 		return (1);
561 	return (0);
562 }
563 
564 /*
565  * Set an environment variable in the MD-static environment.  This cannot
566  * feasibly be done on config(8)-generated static environments as they don't
567  * generally include space for extra variables.
568  */
569 static int
setenv_static(const char * name,const char * value)570 setenv_static(const char *name, const char *value)
571 {
572 	int len;
573 
574 	if (md_env_pos >= md_env_len)
575 		return (-1);
576 
577 	/* Check space for x=y and two nuls */
578 	len = strlen(name) + strlen(value);
579 	if (len + 3 < md_env_len - md_env_pos) {
580 		len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
581 		md_env_pos += len+1;
582 		md_envp[md_env_pos] = '\0';
583 		return (0);
584 	} else
585 		return (-1);
586 
587 }
588 
589 /*
590  * Set an environment variable by name.
591  */
592 int
kern_setenv(const char * name,const char * value)593 kern_setenv(const char *name, const char *value)
594 {
595 	char *buf, *cp, *oldenv;
596 	int namelen, vallen, i;
597 
598 	if (!dynamic_kenv && md_env_len > 0)
599 		return (setenv_static(name, value));
600 
601 	KENV_CHECK;
602 
603 	namelen = strlen(name) + 1;
604 	if (namelen > KENV_MNAMELEN + 1)
605 		return (-1);
606 	vallen = strlen(value) + 1;
607 	if (vallen > kenv_mvallen + 1)
608 		return (-1);
609 	buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
610 	sprintf(buf, "%s=%s", name, value);
611 
612 	mtx_lock(&kenv_lock);
613 	cp = _getenv_dynamic(name, &i);
614 	if (cp != NULL) {
615 		oldenv = kenvp[i];
616 		kenvp[i] = buf;
617 		mtx_unlock(&kenv_lock);
618 		free(oldenv, M_KENV);
619 	} else {
620 		/* We add the option if it wasn't found */
621 		for (i = 0; (cp = kenvp[i]) != NULL; i++)
622 			;
623 
624 		/* Bounds checking */
625 		if (i < 0 || i >= KENV_SIZE) {
626 			free(buf, M_KENV);
627 			mtx_unlock(&kenv_lock);
628 			return (-1);
629 		}
630 
631 		kenvp[i] = buf;
632 		kenvp[i + 1] = NULL;
633 		mtx_unlock(&kenv_lock);
634 	}
635 	return (0);
636 }
637 
638 /*
639  * Unset an environment variable string.
640  */
641 int
kern_unsetenv(const char * name)642 kern_unsetenv(const char *name)
643 {
644 	char *cp, *oldenv;
645 	int i, j;
646 
647 	KENV_CHECK;
648 
649 	mtx_lock(&kenv_lock);
650 	cp = _getenv_dynamic(name, &i);
651 	if (cp != NULL) {
652 		oldenv = kenvp[i];
653 		for (j = i + 1; kenvp[j] != NULL; j++)
654 			kenvp[i++] = kenvp[j];
655 		kenvp[i] = NULL;
656 		mtx_unlock(&kenv_lock);
657 		zfree(oldenv, M_KENV);
658 		return (0);
659 	}
660 	mtx_unlock(&kenv_lock);
661 	return (-1);
662 }
663 
664 /*
665  * Return the internal kenv buffer for the variable name, if it exists.
666  * If the dynamic kenv is initialized and the name is present, return
667  * with kenv_lock held.
668  */
669 static char *
kenv_acquire(const char * name)670 kenv_acquire(const char *name)
671 {
672 	char *value;
673 
674 	if (dynamic_kenv) {
675 		mtx_lock(&kenv_lock);
676 		value = _getenv_dynamic(name, NULL);
677 		if (value == NULL)
678 			mtx_unlock(&kenv_lock);
679 		return (value);
680 	} else
681 		return (_getenv_static(name));
682 }
683 
684 /*
685  * Undo a previous kenv_acquire() operation
686  */
687 static void
kenv_release(const char * buf)688 kenv_release(const char *buf)
689 {
690 	if ((buf != NULL) && dynamic_kenv)
691 		mtx_unlock(&kenv_lock);
692 }
693 
694 /*
695  * Return a string value from an environment variable.
696  */
697 int
getenv_string(const char * name,char * data,int size)698 getenv_string(const char *name, char *data, int size)
699 {
700 	char *cp;
701 
702 	cp = kenv_acquire(name);
703 
704 	if (cp != NULL)
705 		strlcpy(data, cp, size);
706 
707 	kenv_release(cp);
708 
709 	return (cp != NULL);
710 }
711 
712 /*
713  * Return an array of integers at the given type size and signedness.
714  */
715 int
getenv_array(const char * name,void * pdata,int size,int * psize,int type_size,bool allow_signed)716 getenv_array(const char *name, void *pdata, int size, int *psize,
717     int type_size, bool allow_signed)
718 {
719 	uint8_t shift;
720 	int64_t value;
721 	int64_t old;
722 	const char *buf;
723 	char *end;
724 	const char *ptr;
725 	int n;
726 	int rc;
727 
728 	rc = 0;			  /* assume failure */
729 
730 	buf = kenv_acquire(name);
731 	if (buf == NULL)
732 		goto error;
733 
734 	/* get maximum number of elements */
735 	size /= type_size;
736 
737 	n = 0;
738 
739 	for (ptr = buf; *ptr != 0; ) {
740 		value = strtoq(ptr, &end, 0);
741 
742 		/* check if signed numbers are allowed */
743 		if (value < 0 && !allow_signed)
744 			goto error;
745 
746 		/* check for invalid value */
747 		if (ptr == end)
748 			goto error;
749 
750 		/* check for valid suffix */
751 		switch (*end) {
752 		case 't':
753 		case 'T':
754 			shift = 40;
755 			end++;
756 			break;
757 		case 'g':
758 		case 'G':
759 			shift = 30;
760 			end++;
761 			break;
762 		case 'm':
763 		case 'M':
764 			shift = 20;
765 			end++;
766 			break;
767 		case 'k':
768 		case 'K':
769 			shift = 10;
770 			end++;
771 			break;
772 		case ' ':
773 		case '\t':
774 		case ',':
775 		case 0:
776 			shift = 0;
777 			break;
778 		default:
779 			/* garbage after numeric value */
780 			goto error;
781 		}
782 
783 		/* skip till next value, if any */
784 		while (*end == '\t' || *end == ',' || *end == ' ')
785 			end++;
786 
787 		/* update pointer */
788 		ptr = end;
789 
790 		/* apply shift */
791 		old = value;
792 		value <<= shift;
793 
794 		/* overflow check */
795 		if ((value >> shift) != old)
796 			goto error;
797 
798 		/* check for buffer overflow */
799 		if (n >= size)
800 			goto error;
801 
802 		/* store value according to type size */
803 		switch (type_size) {
804 		case 1:
805 			if (allow_signed) {
806 				if (value < SCHAR_MIN || value > SCHAR_MAX)
807 					goto error;
808 			} else {
809 				if (value < 0 || value > UCHAR_MAX)
810 					goto error;
811 			}
812 			((uint8_t *)pdata)[n] = (uint8_t)value;
813 			break;
814 		case 2:
815 			if (allow_signed) {
816 				if (value < SHRT_MIN || value > SHRT_MAX)
817 					goto error;
818 			} else {
819 				if (value < 0 || value > USHRT_MAX)
820 					goto error;
821 			}
822 			((uint16_t *)pdata)[n] = (uint16_t)value;
823 			break;
824 		case 4:
825 			if (allow_signed) {
826 				if (value < INT_MIN || value > INT_MAX)
827 					goto error;
828 			} else {
829 				if (value > UINT_MAX)
830 					goto error;
831 			}
832 			((uint32_t *)pdata)[n] = (uint32_t)value;
833 			break;
834 		case 8:
835 			((uint64_t *)pdata)[n] = (uint64_t)value;
836 			break;
837 		default:
838 			goto error;
839 		}
840 		n++;
841 	}
842 	*psize = n * type_size;
843 
844 	if (n != 0)
845 		rc = 1;	/* success */
846 error:
847 	kenv_release(buf);
848 	return (rc);
849 }
850 
851 /*
852  * Return an integer value from an environment variable.
853  */
854 int
getenv_int(const char * name,int * data)855 getenv_int(const char *name, int *data)
856 {
857 	quad_t tmp;
858 	int rval;
859 
860 	rval = getenv_quad(name, &tmp);
861 	if (rval)
862 		*data = (int) tmp;
863 	return (rval);
864 }
865 
866 /*
867  * Return an unsigned integer value from an environment variable.
868  */
869 int
getenv_uint(const char * name,unsigned int * data)870 getenv_uint(const char *name, unsigned int *data)
871 {
872 	quad_t tmp;
873 	int rval;
874 
875 	rval = getenv_quad(name, &tmp);
876 	if (rval)
877 		*data = (unsigned int) tmp;
878 	return (rval);
879 }
880 
881 /*
882  * Return an int64_t value from an environment variable.
883  */
884 int
getenv_int64(const char * name,int64_t * data)885 getenv_int64(const char *name, int64_t *data)
886 {
887 	quad_t tmp;
888 	int64_t rval;
889 
890 	rval = getenv_quad(name, &tmp);
891 	if (rval)
892 		*data = (int64_t) tmp;
893 	return (rval);
894 }
895 
896 /*
897  * Return an uint64_t value from an environment variable.
898  */
899 int
getenv_uint64(const char * name,uint64_t * data)900 getenv_uint64(const char *name, uint64_t *data)
901 {
902 	quad_t tmp;
903 	uint64_t rval;
904 
905 	rval = getenv_quad(name, &tmp);
906 	if (rval)
907 		*data = (uint64_t) tmp;
908 	return (rval);
909 }
910 
911 /*
912  * Return a long value from an environment variable.
913  */
914 int
getenv_long(const char * name,long * data)915 getenv_long(const char *name, long *data)
916 {
917 	quad_t tmp;
918 	int rval;
919 
920 	rval = getenv_quad(name, &tmp);
921 	if (rval)
922 		*data = (long) tmp;
923 	return (rval);
924 }
925 
926 /*
927  * Return an unsigned long value from an environment variable.
928  */
929 int
getenv_ulong(const char * name,unsigned long * data)930 getenv_ulong(const char *name, unsigned long *data)
931 {
932 	quad_t tmp;
933 	int rval;
934 
935 	rval = getenv_quad(name, &tmp);
936 	if (rval)
937 		*data = (unsigned long) tmp;
938 	return (rval);
939 }
940 
941 /*
942  * Return a quad_t value from an environment variable.
943  */
944 int
getenv_quad(const char * name,quad_t * data)945 getenv_quad(const char *name, quad_t *data)
946 {
947 	const char	*value;
948 	char		suffix, *vtp;
949 	quad_t		iv;
950 
951 	value = kenv_acquire(name);
952 	if (value == NULL) {
953 		goto error;
954 	}
955 	iv = strtoq(value, &vtp, 0);
956 	if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
957 		goto error;
958 	}
959 	suffix = vtp[0];
960 	kenv_release(value);
961 	switch (suffix) {
962 	case 't': case 'T':
963 		iv *= 1024;
964 		/* FALLTHROUGH */
965 	case 'g': case 'G':
966 		iv *= 1024;
967 		/* FALLTHROUGH */
968 	case 'm': case 'M':
969 		iv *= 1024;
970 		/* FALLTHROUGH */
971 	case 'k': case 'K':
972 		iv *= 1024;
973 	case '\0':
974 		break;
975 	default:
976 		return (0);
977 	}
978 	*data = iv;
979 	return (1);
980 error:
981 	kenv_release(value);
982 	return (0);
983 }
984 
985 /*
986  * Return a boolean value from an environment variable. This can be in
987  * numerical or string form, i.e. "1" or "true".
988  */
989 int
getenv_bool(const char * name,bool * data)990 getenv_bool(const char *name, bool *data)
991 {
992 	char *val;
993 	int ret = 0;
994 
995 	if (name == NULL)
996 		return (0);
997 
998 	val = kern_getenv(name);
999 	if (val == NULL)
1000 		return (0);
1001 
1002 	if ((strcmp(val, "1") == 0) || (strcasecmp(val, "true") == 0)) {
1003 		*data = true;
1004 		ret = 1;
1005 	} else if ((strcmp(val, "0") == 0) || (strcasecmp(val, "false") == 0)) {
1006 		*data = false;
1007 		ret = 1;
1008 	} else {
1009 		/* Spit out a warning for malformed boolean variables. */
1010 		printf("Environment variable %s has non-boolean value \"%s\"\n",
1011 		    name, val);
1012 	}
1013 	freeenv(val);
1014 
1015 	return (ret);
1016 }
1017 
1018 /*
1019  * Wrapper around getenv_bool to easily check for true.
1020  */
1021 bool
getenv_is_true(const char * name)1022 getenv_is_true(const char *name)
1023 {
1024 	bool val;
1025 
1026 	if (getenv_bool(name, &val) != 0)
1027 		return (val);
1028 	return (false);
1029 }
1030 
1031 /*
1032  * Wrapper around getenv_bool to easily check for false.
1033  */
1034 bool
getenv_is_false(const char * name)1035 getenv_is_false(const char *name)
1036 {
1037 	bool val;
1038 
1039 	if (getenv_bool(name, &val) != 0)
1040 		return (!val);
1041 	return (false);
1042 }
1043 
1044 /*
1045  * Find the next entry after the one which (cp) falls within, return a
1046  * pointer to its start or NULL if there are no more.
1047  */
1048 static char *
kernenv_next(char * cp)1049 kernenv_next(char *cp)
1050 {
1051 
1052 	if (cp != NULL) {
1053 		while (*cp != 0)
1054 			cp++;
1055 		cp++;
1056 		if (*cp == 0)
1057 			cp = NULL;
1058 	}
1059 	return (cp);
1060 }
1061 
1062 void
tunable_int_init(void * data)1063 tunable_int_init(void *data)
1064 {
1065 	struct tunable_int *d = (struct tunable_int *)data;
1066 
1067 	TUNABLE_INT_FETCH(d->path, d->var);
1068 }
1069 
1070 void
tunable_long_init(void * data)1071 tunable_long_init(void *data)
1072 {
1073 	struct tunable_long *d = (struct tunable_long *)data;
1074 
1075 	TUNABLE_LONG_FETCH(d->path, d->var);
1076 }
1077 
1078 void
tunable_ulong_init(void * data)1079 tunable_ulong_init(void *data)
1080 {
1081 	struct tunable_ulong *d = (struct tunable_ulong *)data;
1082 
1083 	TUNABLE_ULONG_FETCH(d->path, d->var);
1084 }
1085 
1086 void
tunable_int64_init(void * data)1087 tunable_int64_init(void *data)
1088 {
1089 	struct tunable_int64 *d = (struct tunable_int64 *)data;
1090 
1091 	TUNABLE_INT64_FETCH(d->path, d->var);
1092 }
1093 
1094 void
tunable_uint64_init(void * data)1095 tunable_uint64_init(void *data)
1096 {
1097 	struct tunable_uint64 *d = (struct tunable_uint64 *)data;
1098 
1099 	TUNABLE_UINT64_FETCH(d->path, d->var);
1100 }
1101 
1102 void
tunable_quad_init(void * data)1103 tunable_quad_init(void *data)
1104 {
1105 	struct tunable_quad *d = (struct tunable_quad *)data;
1106 
1107 	TUNABLE_QUAD_FETCH(d->path, d->var);
1108 }
1109 
1110 void
tunable_bool_init(void * data)1111 tunable_bool_init(void *data)
1112 {
1113 	struct tunable_bool *d = (struct tunable_bool *)data;
1114 
1115 	TUNABLE_BOOL_FETCH(d->path, d->var);
1116 }
1117 
1118 void
tunable_str_init(void * data)1119 tunable_str_init(void *data)
1120 {
1121 	struct tunable_str *d = (struct tunable_str *)data;
1122 
1123 	TUNABLE_STR_FETCH(d->path, d->var, d->size);
1124 }
1125