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 "namespace.h"
30 #include <sys/types.h>
37 #include "un-namespace.h"
38 #include "libc_private.h"
40 static const char CorruptEnvFindMsg[] = "environment corrupt; unable to find ";
41 static const char CorruptEnvValueMsg[] =
42 "environment corrupt; missing value for ";
46 * Standard environ. environ variable is exposed to entire process.
48 * origEnviron: Upon cleanup on unloading of library or failure, this
49 * allows environ to return to as it was before.
50 * environSize: Number of variables environ can hold. Can only
52 * intEnviron: Internally-built environ. Exposed via environ during
53 * (re)builds of the environment.
55 static char **origEnviron;
56 static char **intEnviron = NULL;
57 static int environSize = 0;
60 * Array of environment variables built from environ. Each element records:
61 * name: Pointer to name=value string
62 * name length: Length of name not counting '=' character
63 * value: Pointer to value within same string as name
64 * value size: Size (not length) of space for value not counting the
66 * active state: true/false value to signify whether variable is active.
67 * Useful since multiple variables with the same name can
68 * co-exist. At most, one variable can be active at any
70 * putenv: Created from putenv() call. This memory must not be
73 static struct envVars {
83 * Environment array information.
85 * envActive: Number of active variables in array.
86 * envVarsSize: Size of array.
87 * envVarsTotal: Number of total variables in array (active or not).
89 static int envActive = 0;
90 static int envVarsSize = 0;
91 static int envVarsTotal = 0;
94 /* Deinitialization of new environment. */
95 static void __attribute__ ((destructor)) __clean_env_destructor(void);
99 * A simple version of warnx() to avoid the bloat of including stdio in static
103 __env_warnx(const char *msg, const char *name, size_t nameLen)
105 static const char nl[] = "\n";
106 static const char progSep[] = ": ";
108 _write(STDERR_FILENO, _getprogname(), strlen(_getprogname()));
109 _write(STDERR_FILENO, progSep, sizeof(progSep) - 1);
110 _write(STDERR_FILENO, msg, strlen(msg));
111 _write(STDERR_FILENO, name, nameLen);
112 _write(STDERR_FILENO, nl, sizeof(nl) - 1);
119 * Inline strlen() for performance. Also, perform check for an equals sign.
120 * Cheaper here than performing a strchr() later.
123 __strleneq(const char *str)
127 for (s = str; *s != '\0'; ++s)
136 * Comparison of an environment name=value to a name.
139 strncmpeq(const char *nameValue, const char *name, size_t nameLen)
141 if (strncmp(nameValue, name, nameLen) == 0 && nameValue[nameLen] == '=')
149 * Using environment, returns pointer to value associated with name, if any,
150 * else NULL. If the onlyActive flag is set to true, only variables that are
151 * active are returned else all are.
154 __findenv(const char *name, size_t nameLen, int *envNdx, bool onlyActive)
159 * Find environment variable from end of array (more likely to be
160 * active). A variable created by putenv is always active, or it is not
161 * tracked in the array.
163 for (ndx = *envNdx; ndx >= 0; ndx--)
164 if (envVars[ndx].putenv) {
165 if (strncmpeq(envVars[ndx].name, name, nameLen)) {
167 return (envVars[ndx].name + nameLen +
170 } else if ((!onlyActive || envVars[ndx].active) &&
171 (envVars[ndx].nameLen == nameLen &&
172 strncmpeq(envVars[ndx].name, name, nameLen))) {
174 return (envVars[ndx].value);
182 * Using environ, returns pointer to value associated with name, if any, else
183 * NULL. Used on the original environ passed into the program.
186 __findenv_environ(const char *name, size_t nameLen)
190 /* Find variable within environ. */
191 for (envNdx = 0; environ[envNdx] != NULL; envNdx++)
192 if (strncmpeq(environ[envNdx], name, nameLen))
193 return (&(environ[envNdx][nameLen + sizeof("=") - 1]));
200 * Remove variable added by putenv() from variable tracking array.
203 __remove_putenv(int envNdx)
206 if (envVarsTotal > envNdx)
207 memmove(&(envVars[envNdx]), &(envVars[envNdx + 1]),
208 (envVarsTotal - envNdx) * sizeof (*envVars));
209 memset(&(envVars[envVarsTotal]), 0, sizeof (*envVars));
216 * Deallocate the environment built from environ as well as environ then set
217 * both to NULL. Eases debugging of memory leaks.
220 __clean_env(bool freeVars)
224 /* Deallocate environment and environ if created by *env(). */
225 if (envVars != NULL) {
226 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--)
227 /* Free variables or deactivate them. */
228 if (envVars[envNdx].putenv) {
230 __remove_putenv(envNdx);
233 free(envVars[envNdx].name);
235 envVars[envNdx].active = false;
243 /* Restore original environ if it has not updated by program. */
244 if (origEnviron != NULL) {
245 if (environ == intEnviron)
246 environ = origEnviron;
258 * Using the environment, rebuild the environ array for use by other C library
259 * calls that depend upon it.
262 __rebuild_environ(int newEnvironSize)
269 /* Resize environ. */
270 if (newEnvironSize > environSize) {
271 tmpEnvironSize = newEnvironSize * 2;
272 tmpEnviron = reallocarray(intEnviron, tmpEnvironSize + 1,
273 sizeof(*intEnviron));
274 if (tmpEnviron == NULL)
276 environSize = tmpEnvironSize;
277 intEnviron = tmpEnviron;
279 envActive = newEnvironSize;
281 /* Assign active variables to environ. */
282 for (envNdx = envVarsTotal - 1, environNdx = 0; envNdx >= 0; envNdx--)
283 if (envVars[envNdx].active)
284 intEnviron[environNdx++] = envVars[envNdx].name;
285 intEnviron[environNdx] = NULL;
287 /* Always set environ which may have been replaced by program. */
288 environ = intEnviron;
295 * Enlarge new environment.
301 struct envVars *tmpEnvVars;
304 if (envVarsTotal > envVarsSize) {
305 newEnvVarsSize = envVarsTotal * 2;
306 tmpEnvVars = reallocarray(envVars, newEnvVarsSize,
308 if (tmpEnvVars == NULL) {
312 envVarsSize = newEnvVarsSize;
313 envVars = tmpEnvVars;
321 * Using environ, build an environment for use by standard C library calls.
332 /* Check for non-existant environment. */
333 if (environ == NULL || environ[0] == NULL)
336 /* Count environment variables. */
337 for (env = environ, envVarsTotal = 0; *env != NULL; env++)
339 envVarsSize = envVarsTotal * 2;
341 /* Create new environment. */
342 envVars = calloc(envVarsSize, sizeof(*envVars));
346 /* Copy environ values and keep track of them. */
347 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--) {
348 envVars[envNdx].putenv = false;
349 envVars[envNdx].name =
350 strdup(environ[envVarsTotal - envNdx - 1]);
351 if (envVars[envNdx].name == NULL)
353 envVars[envNdx].value = strchr(envVars[envNdx].name, '=');
354 if (envVars[envNdx].value != NULL) {
355 envVars[envNdx].value++;
356 envVars[envNdx].valueSize =
357 strlen(envVars[envNdx].value);
359 __env_warnx(CorruptEnvValueMsg, envVars[envNdx].name,
360 strlen(envVars[envNdx].name));
366 * Find most current version of variable to make active. This
367 * will prevent multiple active variables from being created
368 * during this initialization phase.
370 nameLen = envVars[envNdx].value - envVars[envNdx].name - 1;
371 envVars[envNdx].nameLen = nameLen;
372 activeNdx = envVarsTotal - 1;
373 if (__findenv(envVars[envNdx].name, nameLen, &activeNdx,
375 __env_warnx(CorruptEnvFindMsg, envVars[envNdx].name,
380 envVars[activeNdx].active = true;
383 /* Create a new environ. */
384 origEnviron = environ;
386 if (__rebuild_environ(envVarsTotal) == 0)
399 * Destructor function with default argument to __clean_env().
402 __clean_env_destructor(void)
411 * Returns the value of a variable or NULL if none are found.
414 getenv(const char *name)
419 /* Check for malformed name. */
420 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
426 * Variable search order:
427 * 1. Check for an empty environ. This allows an application to clear
429 * 2. Search the external environ array.
430 * 3. Search the internal environment.
432 * Since malloc() depends upon getenv(), getenv() must never cause the
433 * internal environment storage to be generated.
435 if (environ == NULL || environ[0] == NULL)
437 else if (envVars == NULL || environ != intEnviron)
438 return (__findenv_environ(name, nameLen));
440 envNdx = envVarsTotal - 1;
441 return (__findenv(name, nameLen, &envNdx, true));
447 * Runs getenv() unless the current process is tainted by uid or gid changes, in
448 * which case it will return NULL.
451 secure_getenv(const char *name)
455 return (getenv(name));
459 * Set the value of a variable. Older settings are labeled as inactive. If an
460 * older setting has enough room to store the new value, it will be reused. No
461 * previous variables are ever freed here to avoid causing a segmentation fault
464 * The variables nameLen and valueLen are passed into here to allow the caller
465 * to calculate the length by means besides just strlen().
468 __setenv(const char *name, size_t nameLen, const char *value, int overwrite)
476 /* Find existing environment variable large enough to use. */
477 envNdx = envVarsTotal - 1;
478 newEnvActive = envActive;
479 valueLen = strlen(value);
481 if (__findenv(name, nameLen, &envNdx, false) != NULL) {
482 /* Deactivate entry if overwrite is allowed. */
483 if (envVars[envNdx].active) {
486 envVars[envNdx].active = false;
490 /* putenv() created variable cannot be reused. */
491 if (envVars[envNdx].putenv)
492 __remove_putenv(envNdx);
494 /* Entry is large enough to reuse. */
495 else if (envVars[envNdx].valueSize >= valueLen)
499 /* Create new variable if none was found of sufficient size. */
501 /* Enlarge environment. */
502 envNdx = envVarsTotal;
503 if (!__enlarge_env())
506 /* Create environment entry. */
507 envVars[envNdx].name = malloc(nameLen + sizeof ("=") +
509 if (envVars[envNdx].name == NULL) {
513 envVars[envNdx].nameLen = nameLen;
514 envVars[envNdx].valueSize = valueLen;
516 /* Save name of name/value pair. */
517 env = stpncpy(envVars[envNdx].name, name, nameLen);
521 env = envVars[envNdx].value;
523 /* Save value of name/value pair. */
525 envVars[envNdx].value = env;
526 envVars[envNdx].active = true;
529 /* No need to rebuild environ if an active variable was reused. */
530 if (reuse && newEnvActive == envActive)
533 return (__rebuild_environ(newEnvActive));
538 * If the program attempts to replace the array of environment variables
539 * (environ) environ or sets the first varible to NULL, then deactivate all
540 * variables and merge in the new list from environ.
543 __merge_environ(void)
549 * Internally-built environ has been replaced or cleared (detected by
550 * using the count of active variables against a NULL as the first value
551 * in environ). Clean up everything.
553 if (intEnviron != NULL && (environ != intEnviron || (envActive > 0 &&
554 environ[0] == NULL))) {
555 /* Deactivate all environment variables. */
562 * Insert new environ into existing, yet deactivated,
565 origEnviron = environ;
566 if (origEnviron != NULL)
567 for (env = origEnviron; *env != NULL; env++) {
568 if ((equals = strchr(*env, '=')) == NULL) {
569 __env_warnx(CorruptEnvValueMsg, *env,
574 if (__setenv(*env, equals - *env, equals + 1,
585 * The exposed setenv() that performs a few tests before calling the function
586 * (__setenv()) that does the actual work of inserting a variable into the
590 setenv(const char *name, const char *value, int overwrite)
594 /* Check for malformed name. */
595 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
600 /* Initialize environment. */
601 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
604 return (__setenv(name, nameLen, value, overwrite));
609 * Insert a "name=value" string into the environment. Special settings must be
610 * made to keep setenv() from reusing this memory block and unsetenv() from
611 * allowing it to be tracked.
621 /* Check for malformed argument. */
622 if (string == NULL || (equals = strchr(string, '=')) == NULL ||
623 (nameLen = equals - string) == 0) {
628 /* Initialize environment. */
629 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
632 /* Deactivate previous environment variable. */
633 envNdx = envVarsTotal - 1;
634 newEnvActive = envActive;
635 if (__findenv(string, nameLen, &envNdx, true) != NULL) {
636 /* Reuse previous putenv slot. */
637 if (envVars[envNdx].putenv) {
638 envVars[envNdx].name = string;
639 return (__rebuild_environ(envActive));
642 envVars[envNdx].active = false;
646 /* Enlarge environment. */
647 envNdx = envVarsTotal;
648 if (!__enlarge_env())
651 /* Create environment entry. */
652 envVars[envNdx].name = string;
653 envVars[envNdx].nameLen = -1;
654 envVars[envNdx].value = NULL;
655 envVars[envNdx].valueSize = -1;
656 envVars[envNdx].putenv = true;
657 envVars[envNdx].active = true;
660 return (__rebuild_environ(newEnvActive));
665 * Unset variable with the same name by flagging it as inactive. No variable is
669 unsetenv(const char *name)
675 /* Check for malformed name. */
676 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
681 /* Initialize environment. */
682 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
685 /* Deactivate specified variable. */
686 /* Remove all occurrences. */
687 envNdx = envVarsTotal - 1;
688 newEnvActive = envActive;
689 while (__findenv(name, nameLen, &envNdx, true) != NULL) {
690 envVars[envNdx].active = false;
691 if (envVars[envNdx].putenv)
692 __remove_putenv(envNdx);
696 if (newEnvActive != envActive)
697 __rebuild_environ(newEnvActive);
703 * Unset all variable by flagging them as inactive. No variable is
711 /* Initialize environment. */
712 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
715 /* Remove from the end to not shuffle memory too much. */
716 for (ndx = envVarsTotal - 1; ndx >= 0; ndx--) {
717 envVars[ndx].active = false;
718 if (envVars[ndx].putenv)
719 __remove_putenv(ndx);
722 __rebuild_environ(0);