2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2007-2009 Sean C. Farley <scf@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer,
12 * without modification, immediately at the beginning of the file.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 #include "namespace.h"
31 #include <sys/types.h>
38 #include "un-namespace.h"
39 #include "libc_private.h"
41 static const char CorruptEnvFindMsg[] = "environment corrupt; unable to find ";
42 static const char CorruptEnvValueMsg[] =
43 "environment corrupt; missing value for ";
47 * Standard environ. environ variable is exposed to entire process.
49 * origEnviron: Upon cleanup on unloading of library or failure, this
50 * allows environ to return to as it was before.
51 * environSize: Number of variables environ can hold. Can only
53 * intEnviron: Internally-built environ. Exposed via environ during
54 * (re)builds of the environment.
56 static char **origEnviron;
57 static char **intEnviron = NULL;
58 static int environSize = 0;
61 * Array of environment variables built from environ. Each element records:
62 * name: Pointer to name=value string
63 * name length: Length of name not counting '=' character
64 * value: Pointer to value within same string as name
65 * value size: Size (not length) of space for value not counting the
67 * active state: true/false value to signify whether variable is active.
68 * Useful since multiple variables with the same name can
69 * co-exist. At most, one variable can be active at any
71 * putenv: Created from putenv() call. This memory must not be
74 static struct envVars {
84 * Environment array information.
86 * envActive: Number of active variables in array.
87 * envVarsSize: Size of array.
88 * envVarsTotal: Number of total variables in array (active or not).
90 static int envActive = 0;
91 static int envVarsSize = 0;
92 static int envVarsTotal = 0;
95 /* Deinitialization of new environment. */
96 static void __attribute__ ((destructor)) __clean_env_destructor(void);
100 * A simple version of warnx() to avoid the bloat of including stdio in static
104 __env_warnx(const char *msg, const char *name, size_t nameLen)
106 static const char nl[] = "\n";
107 static const char progSep[] = ": ";
109 _write(STDERR_FILENO, _getprogname(), strlen(_getprogname()));
110 _write(STDERR_FILENO, progSep, sizeof(progSep) - 1);
111 _write(STDERR_FILENO, msg, strlen(msg));
112 _write(STDERR_FILENO, name, nameLen);
113 _write(STDERR_FILENO, nl, sizeof(nl) - 1);
120 * Inline strlen() for performance. Also, perform check for an equals sign.
121 * Cheaper here than performing a strchr() later.
124 __strleneq(const char *str)
128 for (s = str; *s != '\0'; ++s)
137 * Comparison of an environment name=value to a name.
140 strncmpeq(const char *nameValue, const char *name, size_t nameLen)
142 if (strncmp(nameValue, name, nameLen) == 0 && nameValue[nameLen] == '=')
150 * Using environment, returns pointer to value associated with name, if any,
151 * else NULL. If the onlyActive flag is set to true, only variables that are
152 * active are returned else all are.
155 __findenv(const char *name, size_t nameLen, int *envNdx, bool onlyActive)
160 * Find environment variable from end of array (more likely to be
161 * active). A variable created by putenv is always active, or it is not
162 * tracked in the array.
164 for (ndx = *envNdx; ndx >= 0; ndx--)
165 if (envVars[ndx].putenv) {
166 if (strncmpeq(envVars[ndx].name, name, nameLen)) {
168 return (envVars[ndx].name + nameLen +
171 } else if ((!onlyActive || envVars[ndx].active) &&
172 (envVars[ndx].nameLen == nameLen &&
173 strncmpeq(envVars[ndx].name, name, nameLen))) {
175 return (envVars[ndx].value);
183 * Using environ, returns pointer to value associated with name, if any, else
184 * NULL. Used on the original environ passed into the program.
187 __findenv_environ(const char *name, size_t nameLen)
191 /* Find variable within environ. */
192 for (envNdx = 0; environ[envNdx] != NULL; envNdx++)
193 if (strncmpeq(environ[envNdx], name, nameLen))
194 return (&(environ[envNdx][nameLen + sizeof("=") - 1]));
201 * Remove variable added by putenv() from variable tracking array.
204 __remove_putenv(int envNdx)
207 if (envVarsTotal > envNdx)
208 memmove(&(envVars[envNdx]), &(envVars[envNdx + 1]),
209 (envVarsTotal - envNdx) * sizeof (*envVars));
210 memset(&(envVars[envVarsTotal]), 0, sizeof (*envVars));
217 * Deallocate the environment built from environ as well as environ then set
218 * both to NULL. Eases debugging of memory leaks.
221 __clean_env(bool freeVars)
225 /* Deallocate environment and environ if created by *env(). */
226 if (envVars != NULL) {
227 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--)
228 /* Free variables or deactivate them. */
229 if (envVars[envNdx].putenv) {
231 __remove_putenv(envNdx);
234 free(envVars[envNdx].name);
236 envVars[envNdx].active = false;
244 /* Restore original environ if it has not updated by program. */
245 if (origEnviron != NULL) {
246 if (environ == intEnviron)
247 environ = origEnviron;
259 * Using the environment, rebuild the environ array for use by other C library
260 * calls that depend upon it.
263 __rebuild_environ(int newEnvironSize)
270 /* Resize environ. */
271 if (newEnvironSize > environSize) {
272 tmpEnvironSize = newEnvironSize * 2;
273 tmpEnviron = reallocarray(intEnviron, tmpEnvironSize + 1,
274 sizeof(*intEnviron));
275 if (tmpEnviron == NULL)
277 environSize = tmpEnvironSize;
278 intEnviron = tmpEnviron;
280 envActive = newEnvironSize;
282 /* Assign active variables to environ. */
283 for (envNdx = envVarsTotal - 1, environNdx = 0; envNdx >= 0; envNdx--)
284 if (envVars[envNdx].active)
285 intEnviron[environNdx++] = envVars[envNdx].name;
286 intEnviron[environNdx] = NULL;
288 /* Always set environ which may have been replaced by program. */
289 environ = intEnviron;
296 * Enlarge new environment.
302 struct envVars *tmpEnvVars;
305 if (envVarsTotal > envVarsSize) {
306 newEnvVarsSize = envVarsTotal * 2;
307 tmpEnvVars = reallocarray(envVars, newEnvVarsSize,
309 if (tmpEnvVars == NULL) {
313 envVarsSize = newEnvVarsSize;
314 envVars = tmpEnvVars;
322 * Using environ, build an environment for use by standard C library calls.
333 /* Check for non-existant environment. */
334 if (environ == NULL || environ[0] == NULL)
337 /* Count environment variables. */
338 for (env = environ, envVarsTotal = 0; *env != NULL; env++)
340 envVarsSize = envVarsTotal * 2;
342 /* Create new environment. */
343 envVars = calloc(envVarsSize, sizeof(*envVars));
347 /* Copy environ values and keep track of them. */
348 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--) {
349 envVars[envNdx].putenv = false;
350 envVars[envNdx].name =
351 strdup(environ[envVarsTotal - envNdx - 1]);
352 if (envVars[envNdx].name == NULL)
354 envVars[envNdx].value = strchr(envVars[envNdx].name, '=');
355 if (envVars[envNdx].value != NULL) {
356 envVars[envNdx].value++;
357 envVars[envNdx].valueSize =
358 strlen(envVars[envNdx].value);
360 __env_warnx(CorruptEnvValueMsg, envVars[envNdx].name,
361 strlen(envVars[envNdx].name));
367 * Find most current version of variable to make active. This
368 * will prevent multiple active variables from being created
369 * during this initialization phase.
371 nameLen = envVars[envNdx].value - envVars[envNdx].name - 1;
372 envVars[envNdx].nameLen = nameLen;
373 activeNdx = envVarsTotal - 1;
374 if (__findenv(envVars[envNdx].name, nameLen, &activeNdx,
376 __env_warnx(CorruptEnvFindMsg, envVars[envNdx].name,
381 envVars[activeNdx].active = true;
384 /* Create a new environ. */
385 origEnviron = environ;
387 if (__rebuild_environ(envVarsTotal) == 0)
400 * Destructor function with default argument to __clean_env().
403 __clean_env_destructor(void)
412 * Returns the value of a variable or NULL if none are found.
415 getenv(const char *name)
420 /* Check for malformed name. */
421 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
427 * Variable search order:
428 * 1. Check for an empty environ. This allows an application to clear
430 * 2. Search the external environ array.
431 * 3. Search the internal environment.
433 * Since malloc() depends upon getenv(), getenv() must never cause the
434 * internal environment storage to be generated.
436 if (environ == NULL || environ[0] == NULL)
438 else if (envVars == NULL || environ != intEnviron)
439 return (__findenv_environ(name, nameLen));
441 envNdx = envVarsTotal - 1;
442 return (__findenv(name, nameLen, &envNdx, true));
448 * Runs getenv() unless the current process is tainted by uid or gid changes, in
449 * which case it will return NULL.
452 secure_getenv(const char *name)
456 return (getenv(name));
460 * Set the value of a variable. Older settings are labeled as inactive. If an
461 * older setting has enough room to store the new value, it will be reused. No
462 * previous variables are ever freed here to avoid causing a segmentation fault
465 * The variables nameLen and valueLen are passed into here to allow the caller
466 * to calculate the length by means besides just strlen().
469 __setenv(const char *name, size_t nameLen, const char *value, int overwrite)
477 /* Find existing environment variable large enough to use. */
478 envNdx = envVarsTotal - 1;
479 newEnvActive = envActive;
480 valueLen = strlen(value);
482 if (__findenv(name, nameLen, &envNdx, false) != NULL) {
483 /* Deactivate entry if overwrite is allowed. */
484 if (envVars[envNdx].active) {
487 envVars[envNdx].active = false;
491 /* putenv() created variable cannot be reused. */
492 if (envVars[envNdx].putenv)
493 __remove_putenv(envNdx);
495 /* Entry is large enough to reuse. */
496 else if (envVars[envNdx].valueSize >= valueLen)
500 /* Create new variable if none was found of sufficient size. */
502 /* Enlarge environment. */
503 envNdx = envVarsTotal;
504 if (!__enlarge_env())
507 /* Create environment entry. */
508 envVars[envNdx].name = malloc(nameLen + sizeof ("=") +
510 if (envVars[envNdx].name == NULL) {
514 envVars[envNdx].nameLen = nameLen;
515 envVars[envNdx].valueSize = valueLen;
517 /* Save name of name/value pair. */
518 env = stpncpy(envVars[envNdx].name, name, nameLen);
522 env = envVars[envNdx].value;
524 /* Save value of name/value pair. */
526 envVars[envNdx].value = env;
527 envVars[envNdx].active = true;
530 /* No need to rebuild environ if an active variable was reused. */
531 if (reuse && newEnvActive == envActive)
534 return (__rebuild_environ(newEnvActive));
539 * If the program attempts to replace the array of environment variables
540 * (environ) environ or sets the first varible to NULL, then deactivate all
541 * variables and merge in the new list from environ.
544 __merge_environ(void)
550 * Internally-built environ has been replaced or cleared (detected by
551 * using the count of active variables against a NULL as the first value
552 * in environ). Clean up everything.
554 if (intEnviron != NULL && (environ != intEnviron || (envActive > 0 &&
555 environ[0] == NULL))) {
556 /* Deactivate all environment variables. */
563 * Insert new environ into existing, yet deactivated,
566 origEnviron = environ;
567 if (origEnviron != NULL)
568 for (env = origEnviron; *env != NULL; env++) {
569 if ((equals = strchr(*env, '=')) == NULL) {
570 __env_warnx(CorruptEnvValueMsg, *env,
575 if (__setenv(*env, equals - *env, equals + 1,
586 * The exposed setenv() that performs a few tests before calling the function
587 * (__setenv()) that does the actual work of inserting a variable into the
591 setenv(const char *name, const char *value, int overwrite)
595 /* Check for malformed name. */
596 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
601 /* Initialize environment. */
602 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
605 return (__setenv(name, nameLen, value, overwrite));
610 * Insert a "name=value" string into the environment. Special settings must be
611 * made to keep setenv() from reusing this memory block and unsetenv() from
612 * allowing it to be tracked.
622 /* Check for malformed argument. */
623 if (string == NULL || (equals = strchr(string, '=')) == NULL ||
624 (nameLen = equals - string) == 0) {
629 /* Initialize environment. */
630 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
633 /* Deactivate previous environment variable. */
634 envNdx = envVarsTotal - 1;
635 newEnvActive = envActive;
636 if (__findenv(string, nameLen, &envNdx, true) != NULL) {
637 /* Reuse previous putenv slot. */
638 if (envVars[envNdx].putenv) {
639 envVars[envNdx].name = string;
640 return (__rebuild_environ(envActive));
643 envVars[envNdx].active = false;
647 /* Enlarge environment. */
648 envNdx = envVarsTotal;
649 if (!__enlarge_env())
652 /* Create environment entry. */
653 envVars[envNdx].name = string;
654 envVars[envNdx].nameLen = -1;
655 envVars[envNdx].value = NULL;
656 envVars[envNdx].valueSize = -1;
657 envVars[envNdx].putenv = true;
658 envVars[envNdx].active = true;
661 return (__rebuild_environ(newEnvActive));
666 * Unset variable with the same name by flagging it as inactive. No variable is
670 unsetenv(const char *name)
676 /* Check for malformed name. */
677 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
682 /* Initialize environment. */
683 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
686 /* Deactivate specified variable. */
687 /* Remove all occurrences. */
688 envNdx = envVarsTotal - 1;
689 newEnvActive = envActive;
690 while (__findenv(name, nameLen, &envNdx, true) != NULL) {
691 envVars[envNdx].active = false;
692 if (envVars[envNdx].putenv)
693 __remove_putenv(envNdx);
697 if (newEnvActive != envActive)
698 __rebuild_environ(newEnvActive);
704 * Unset all variable by flagging them as inactive. No variable is
712 /* Initialize environment. */
713 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
716 /* Remove from the end to not shuffle memory too much. */
717 for (ndx = envVarsTotal - 1; ndx >= 0; ndx--) {
718 envVars[ndx].active = false;
719 if (envVars[ndx].putenv)
720 __remove_putenv(ndx);
723 __rebuild_environ(0);