xref: /freebsd/sys/kern/kern_environment.c (revision 56e53cb8ef000c3ef72337a4095987a932cdedef)
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/types.h>
43 #include <sys/param.h>
44 #include <sys/proc.h>
45 #include <sys/queue.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/mutex.h>
49 #include <sys/priv.h>
50 #include <sys/kernel.h>
51 #include <sys/systm.h>
52 #include <sys/sysent.h>
53 #include <sys/sysproto.h>
54 #include <sys/libkern.h>
55 #include <sys/kenv.h>
56 
57 #include <security/mac/mac_framework.h>
58 
59 static MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
60 
61 #define KENV_SIZE	512	/* Maximum number of environment strings */
62 
63 /* pointer to the static environment */
64 char		*kern_envp;
65 static int	env_len;
66 static int	env_pos;
67 static char	*kernenv_next(char *);
68 
69 /* dynamic environment variables */
70 char		**kenvp;
71 struct mtx	kenv_lock;
72 
73 /*
74  * No need to protect this with a mutex since SYSINITS are single threaded.
75  */
76 int	dynamic_kenv = 0;
77 
78 #define KENV_CHECK	if (!dynamic_kenv) \
79 			    panic("%s: called before SI_SUB_KMEM", __func__)
80 
81 int
82 sys_kenv(td, uap)
83 	struct thread *td;
84 	struct kenv_args /* {
85 		int what;
86 		const char *name;
87 		char *value;
88 		int len;
89 	} */ *uap;
90 {
91 	char *name, *value, *buffer = NULL;
92 	size_t len, done, needed, buflen;
93 	int error, i;
94 
95 	KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = 0"));
96 
97 	error = 0;
98 	if (uap->what == KENV_DUMP) {
99 #ifdef MAC
100 		error = mac_kenv_check_dump(td->td_ucred);
101 		if (error)
102 			return (error);
103 #endif
104 		done = needed = 0;
105 		buflen = uap->len;
106 		if (buflen > KENV_SIZE * (KENV_MNAMELEN + KENV_MVALLEN + 2))
107 			buflen = KENV_SIZE * (KENV_MNAMELEN +
108 			    KENV_MVALLEN + 2);
109 		if (uap->len > 0 && uap->value != NULL)
110 			buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
111 		mtx_lock(&kenv_lock);
112 		for (i = 0; kenvp[i] != NULL; i++) {
113 			len = strlen(kenvp[i]) + 1;
114 			needed += len;
115 			len = min(len, buflen - done);
116 			/*
117 			 * If called with a NULL or insufficiently large
118 			 * buffer, just keep computing the required size.
119 			 */
120 			if (uap->value != NULL && buffer != NULL && len > 0) {
121 				bcopy(kenvp[i], buffer + done, len);
122 				done += len;
123 			}
124 		}
125 		mtx_unlock(&kenv_lock);
126 		if (buffer != NULL) {
127 			error = copyout(buffer, uap->value, done);
128 			free(buffer, M_TEMP);
129 		}
130 		td->td_retval[0] = ((done == needed) ? 0 : needed);
131 		return (error);
132 	}
133 
134 	switch (uap->what) {
135 	case KENV_SET:
136 		error = priv_check(td, PRIV_KENV_SET);
137 		if (error)
138 			return (error);
139 		break;
140 
141 	case KENV_UNSET:
142 		error = priv_check(td, PRIV_KENV_UNSET);
143 		if (error)
144 			return (error);
145 		break;
146 	}
147 
148 	name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
149 
150 	error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
151 	if (error)
152 		goto done;
153 
154 	switch (uap->what) {
155 	case KENV_GET:
156 #ifdef MAC
157 		error = mac_kenv_check_get(td->td_ucred, name);
158 		if (error)
159 			goto done;
160 #endif
161 		value = kern_getenv(name);
162 		if (value == NULL) {
163 			error = ENOENT;
164 			goto done;
165 		}
166 		len = strlen(value) + 1;
167 		if (len > uap->len)
168 			len = uap->len;
169 		error = copyout(value, uap->value, len);
170 		freeenv(value);
171 		if (error)
172 			goto done;
173 		td->td_retval[0] = len;
174 		break;
175 	case KENV_SET:
176 		len = uap->len;
177 		if (len < 1) {
178 			error = EINVAL;
179 			goto done;
180 		}
181 		if (len > KENV_MVALLEN + 1)
182 			len = KENV_MVALLEN + 1;
183 		value = malloc(len, M_TEMP, M_WAITOK);
184 		error = copyinstr(uap->value, value, len, NULL);
185 		if (error) {
186 			free(value, M_TEMP);
187 			goto done;
188 		}
189 #ifdef MAC
190 		error = mac_kenv_check_set(td->td_ucred, name, value);
191 		if (error == 0)
192 #endif
193 			kern_setenv(name, value);
194 		free(value, M_TEMP);
195 		break;
196 	case KENV_UNSET:
197 #ifdef MAC
198 		error = mac_kenv_check_unset(td->td_ucred, name);
199 		if (error)
200 			goto done;
201 #endif
202 		error = kern_unsetenv(name);
203 		if (error)
204 			error = ENOENT;
205 		break;
206 	default:
207 		error = EINVAL;
208 		break;
209 	}
210 done:
211 	free(name, M_TEMP);
212 	return (error);
213 }
214 
215 /*
216  * Populate the initial kernel environment.
217  *
218  * This is called very early in MD startup, either to provide a copy of the
219  * environment obtained from a boot loader, or to provide an empty buffer into
220  * which MD code can store an initial environment using kern_setenv() calls.
221  *
222  * When a copy of an initial environment is passed in, we start by scanning that
223  * env for overrides to the compiled-in envmode and hintmode variables.
224  *
225  * If the global envmode is 1, the environment is initialized from the global
226  * static_env[], regardless of the arguments passed.  This implements the env
227  * keyword described in config(5).  In this case env_pos is set to env_len,
228  * causing kern_setenv() to return -1 (if len > 0) or panic (if len == 0) until
229  * the dynamic environment is available.  The envmode and static_env variables
230  * are defined in env.c which is generated by config(8).
231  *
232  * If len is non-zero, the caller is providing an empty buffer.  The caller will
233  * subsequently use kern_setenv() to add up to len bytes of initial environment
234  * before the dynamic environment is available.
235  *
236  * If len is zero, the caller is providing a pre-loaded buffer containing
237  * environment strings.  Additional strings cannot be added until the dynamic
238  * environment is available.  The memory pointed to must remain stable at least
239  * until sysinit runs init_dynamic_kenv().  If no initial environment is
240  * available from the boot loader, passing a NULL pointer allows the static_env
241  * to be installed if it is configured.
242  */
243 void
244 init_static_kenv(char *buf, size_t len)
245 {
246 	char *cp;
247 
248 	for (cp = buf; cp != NULL && cp[0] != '\0'; cp += strlen(cp) + 1) {
249 		if (strcmp(cp, "static_env.disabled=1") == 0)
250 			envmode = 0;
251 		if (strcmp(cp, "static_hints.disabled=1") == 0)
252 			hintmode = 0;
253 	}
254 
255 	if (envmode == 1) {
256 		kern_envp = static_env;
257 		env_len = len;
258 		env_pos = len;
259 	} else {
260 		kern_envp = buf;
261 		env_len = len;
262 		env_pos = 0;
263 	}
264 }
265 
266 /*
267  * Setup the dynamic kernel environment.
268  */
269 static void
270 init_dynamic_kenv(void *data __unused)
271 {
272 	char *cp, *cpnext;
273 	size_t len;
274 	int i;
275 
276 	kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
277 		M_WAITOK | M_ZERO);
278 	i = 0;
279 	if (kern_envp && *kern_envp != '\0') {
280 		for (cp = kern_envp; cp != NULL; cp = cpnext) {
281 			cpnext = kernenv_next(cp);
282 			len = strlen(cp) + 1;
283 			if (len > KENV_MNAMELEN + 1 + KENV_MVALLEN + 1) {
284 				printf(
285 				"WARNING: too long kenv string, ignoring %s\n",
286 				    cp);
287 				continue;
288 			}
289 			if (i < KENV_SIZE) {
290 				kenvp[i] = malloc(len, M_KENV, M_WAITOK);
291 				strcpy(kenvp[i++], cp);
292 				memset(cp, 0, strlen(cp));
293 			} else
294 				printf(
295 				"WARNING: too many kenv strings, ignoring %s\n",
296 				    cp);
297 		}
298 	}
299 	kenvp[i] = NULL;
300 
301 	mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
302 	dynamic_kenv = 1;
303 }
304 SYSINIT(kenv, SI_SUB_KMEM, SI_ORDER_ANY, init_dynamic_kenv, NULL);
305 
306 void
307 freeenv(char *env)
308 {
309 
310 	if (dynamic_kenv && env != NULL) {
311 		memset(env, 0, strlen(env));
312 		free(env, M_KENV);
313 	}
314 }
315 
316 /*
317  * Internal functions for string lookup.
318  */
319 static char *
320 _getenv_dynamic(const char *name, int *idx)
321 {
322 	char *cp;
323 	int len, i;
324 
325 	mtx_assert(&kenv_lock, MA_OWNED);
326 	len = strlen(name);
327 	for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
328 		if ((strncmp(cp, name, len) == 0) &&
329 		    (cp[len] == '=')) {
330 			if (idx != NULL)
331 				*idx = i;
332 			return (cp + len + 1);
333 		}
334 	}
335 	return (NULL);
336 }
337 
338 static char *
339 _getenv_static(const char *name)
340 {
341 	char *cp, *ep;
342 	int len;
343 
344 	for (cp = kern_envp; cp != NULL; cp = kernenv_next(cp)) {
345 		for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
346 			;
347 		if (*ep != '=')
348 			continue;
349 		len = ep - cp;
350 		ep++;
351 		if (!strncmp(name, cp, len) && name[len] == 0)
352 			return (ep);
353 	}
354 	return (NULL);
355 }
356 
357 /*
358  * Look up an environment variable by name.
359  * Return a pointer to the string if found.
360  * The pointer has to be freed with freeenv()
361  * after use.
362  */
363 char *
364 kern_getenv(const char *name)
365 {
366 	char buf[KENV_MNAMELEN + 1 + KENV_MVALLEN + 1];
367 	char *ret;
368 
369 	if (dynamic_kenv) {
370 		if (getenv_string(name, buf, sizeof(buf))) {
371 			ret = strdup(buf, M_KENV);
372 		} else {
373 			ret = NULL;
374 			WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
375 			    "getenv");
376 		}
377 	} else
378 		ret = _getenv_static(name);
379 	return (ret);
380 }
381 
382 /*
383  * Test if an environment variable is defined.
384  */
385 int
386 testenv(const char *name)
387 {
388 	char *cp;
389 
390 	if (dynamic_kenv) {
391 		mtx_lock(&kenv_lock);
392 		cp = _getenv_dynamic(name, NULL);
393 		mtx_unlock(&kenv_lock);
394 	} else
395 		cp = _getenv_static(name);
396 	if (cp != NULL)
397 		return (1);
398 	return (0);
399 }
400 
401 static int
402 setenv_static(const char *name, const char *value)
403 {
404 	int len;
405 
406 	if (env_pos >= env_len)
407 		return (-1);
408 
409 	/* Check space for x=y and two nuls */
410 	len = strlen(name) + strlen(value);
411 	if (len + 3 < env_len - env_pos) {
412 		len = sprintf(&kern_envp[env_pos], "%s=%s", name, value);
413 		env_pos += len+1;
414 		kern_envp[env_pos] = '\0';
415 		return (0);
416 	} else
417 		return (-1);
418 
419 }
420 
421 /*
422  * Set an environment variable by name.
423  */
424 int
425 kern_setenv(const char *name, const char *value)
426 {
427 	char *buf, *cp, *oldenv;
428 	int namelen, vallen, i;
429 
430 	if (dynamic_kenv == 0 && env_len > 0)
431 		return (setenv_static(name, value));
432 
433 	KENV_CHECK;
434 
435 	namelen = strlen(name) + 1;
436 	if (namelen > KENV_MNAMELEN + 1)
437 		return (-1);
438 	vallen = strlen(value) + 1;
439 	if (vallen > KENV_MVALLEN + 1)
440 		return (-1);
441 	buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
442 	sprintf(buf, "%s=%s", name, value);
443 
444 	mtx_lock(&kenv_lock);
445 	cp = _getenv_dynamic(name, &i);
446 	if (cp != NULL) {
447 		oldenv = kenvp[i];
448 		kenvp[i] = buf;
449 		mtx_unlock(&kenv_lock);
450 		free(oldenv, M_KENV);
451 	} else {
452 		/* We add the option if it wasn't found */
453 		for (i = 0; (cp = kenvp[i]) != NULL; i++)
454 			;
455 
456 		/* Bounds checking */
457 		if (i < 0 || i >= KENV_SIZE) {
458 			free(buf, M_KENV);
459 			mtx_unlock(&kenv_lock);
460 			return (-1);
461 		}
462 
463 		kenvp[i] = buf;
464 		kenvp[i + 1] = NULL;
465 		mtx_unlock(&kenv_lock);
466 	}
467 	return (0);
468 }
469 
470 /*
471  * Unset an environment variable string.
472  */
473 int
474 kern_unsetenv(const char *name)
475 {
476 	char *cp, *oldenv;
477 	int i, j;
478 
479 	KENV_CHECK;
480 
481 	mtx_lock(&kenv_lock);
482 	cp = _getenv_dynamic(name, &i);
483 	if (cp != NULL) {
484 		oldenv = kenvp[i];
485 		for (j = i + 1; kenvp[j] != NULL; j++)
486 			kenvp[i++] = kenvp[j];
487 		kenvp[i] = NULL;
488 		mtx_unlock(&kenv_lock);
489 		memset(oldenv, 0, strlen(oldenv));
490 		free(oldenv, M_KENV);
491 		return (0);
492 	}
493 	mtx_unlock(&kenv_lock);
494 	return (-1);
495 }
496 
497 /*
498  * Return a string value from an environment variable.
499  */
500 int
501 getenv_string(const char *name, char *data, int size)
502 {
503 	char *cp;
504 
505 	if (dynamic_kenv) {
506 		mtx_lock(&kenv_lock);
507 		cp = _getenv_dynamic(name, NULL);
508 		if (cp != NULL)
509 			strlcpy(data, cp, size);
510 		mtx_unlock(&kenv_lock);
511 	} else {
512 		cp = _getenv_static(name);
513 		if (cp != NULL)
514 			strlcpy(data, cp, size);
515 	}
516 	return (cp != NULL);
517 }
518 
519 /*
520  * Return an integer value from an environment variable.
521  */
522 int
523 getenv_int(const char *name, int *data)
524 {
525 	quad_t tmp;
526 	int rval;
527 
528 	rval = getenv_quad(name, &tmp);
529 	if (rval)
530 		*data = (int) tmp;
531 	return (rval);
532 }
533 
534 /*
535  * Return an unsigned integer value from an environment variable.
536  */
537 int
538 getenv_uint(const char *name, unsigned int *data)
539 {
540 	quad_t tmp;
541 	int rval;
542 
543 	rval = getenv_quad(name, &tmp);
544 	if (rval)
545 		*data = (unsigned int) tmp;
546 	return (rval);
547 }
548 
549 /*
550  * Return an int64_t value from an environment variable.
551  */
552 int
553 getenv_int64(const char *name, int64_t *data)
554 {
555 	quad_t tmp;
556 	int64_t rval;
557 
558 	rval = getenv_quad(name, &tmp);
559 	if (rval)
560 		*data = (int64_t) tmp;
561 	return (rval);
562 }
563 
564 /*
565  * Return an uint64_t value from an environment variable.
566  */
567 int
568 getenv_uint64(const char *name, uint64_t *data)
569 {
570 	quad_t tmp;
571 	uint64_t rval;
572 
573 	rval = getenv_quad(name, &tmp);
574 	if (rval)
575 		*data = (uint64_t) tmp;
576 	return (rval);
577 }
578 
579 /*
580  * Return a long value from an environment variable.
581  */
582 int
583 getenv_long(const char *name, long *data)
584 {
585 	quad_t tmp;
586 	int rval;
587 
588 	rval = getenv_quad(name, &tmp);
589 	if (rval)
590 		*data = (long) tmp;
591 	return (rval);
592 }
593 
594 /*
595  * Return an unsigned long value from an environment variable.
596  */
597 int
598 getenv_ulong(const char *name, unsigned long *data)
599 {
600 	quad_t tmp;
601 	int rval;
602 
603 	rval = getenv_quad(name, &tmp);
604 	if (rval)
605 		*data = (unsigned long) tmp;
606 	return (rval);
607 }
608 
609 /*
610  * Return a quad_t value from an environment variable.
611  */
612 int
613 getenv_quad(const char *name, quad_t *data)
614 {
615 	char	value[KENV_MNAMELEN + 1 + KENV_MVALLEN + 1];
616 	char	*vtp;
617 	quad_t	iv;
618 
619 	if (!getenv_string(name, value, sizeof(value)))
620 		return (0);
621 	iv = strtoq(value, &vtp, 0);
622 	if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0'))
623 		return (0);
624 	switch (vtp[0]) {
625 	case 't': case 'T':
626 		iv *= 1024;
627 	case 'g': case 'G':
628 		iv *= 1024;
629 	case 'm': case 'M':
630 		iv *= 1024;
631 	case 'k': case 'K':
632 		iv *= 1024;
633 	case '\0':
634 		break;
635 	default:
636 		return (0);
637 	}
638 	*data = iv;
639 	return (1);
640 }
641 
642 /*
643  * Find the next entry after the one which (cp) falls within, return a
644  * pointer to its start or NULL if there are no more.
645  */
646 static char *
647 kernenv_next(char *cp)
648 {
649 
650 	if (cp != NULL) {
651 		while (*cp != 0)
652 			cp++;
653 		cp++;
654 		if (*cp == 0)
655 			cp = NULL;
656 	}
657 	return (cp);
658 }
659 
660 void
661 tunable_int_init(void *data)
662 {
663 	struct tunable_int *d = (struct tunable_int *)data;
664 
665 	TUNABLE_INT_FETCH(d->path, d->var);
666 }
667 
668 void
669 tunable_long_init(void *data)
670 {
671 	struct tunable_long *d = (struct tunable_long *)data;
672 
673 	TUNABLE_LONG_FETCH(d->path, d->var);
674 }
675 
676 void
677 tunable_ulong_init(void *data)
678 {
679 	struct tunable_ulong *d = (struct tunable_ulong *)data;
680 
681 	TUNABLE_ULONG_FETCH(d->path, d->var);
682 }
683 
684 void
685 tunable_int64_init(void *data)
686 {
687 	struct tunable_int64 *d = (struct tunable_int64 *)data;
688 
689 	TUNABLE_INT64_FETCH(d->path, d->var);
690 }
691 
692 void
693 tunable_uint64_init(void *data)
694 {
695 	struct tunable_uint64 *d = (struct tunable_uint64 *)data;
696 
697 	TUNABLE_UINT64_FETCH(d->path, d->var);
698 }
699 
700 void
701 tunable_quad_init(void *data)
702 {
703 	struct tunable_quad *d = (struct tunable_quad *)data;
704 
705 	TUNABLE_QUAD_FETCH(d->path, d->var);
706 }
707 
708 void
709 tunable_str_init(void *data)
710 {
711 	struct tunable_str *d = (struct tunable_str *)data;
712 
713 	TUNABLE_STR_FETCH(d->path, d->var, d->size);
714 }
715