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