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