2 * Copyright (c) 2007-2009 Sean C. Farley <scf@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer,
10 * without modification, immediately at the beginning of the file.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
31 #include "namespace.h"
32 #include <sys/types.h>
39 #include "un-namespace.h"
42 static const char CorruptEnvFindMsg[] = "environment corrupt; unable to find ";
43 static const char CorruptEnvValueMsg[] =
44 "environment corrupt; missing value for ";
48 * Standard environ. environ variable is exposed to entire process.
50 * origEnviron: Upon cleanup on unloading of library or failure, this
51 * allows environ to return to as it was before.
52 * environSize: Number of variables environ can hold. Can only
54 * intEnviron: Internally-built environ. Exposed via environ during
55 * (re)builds of the environment.
57 extern char **environ;
58 static char **origEnviron;
59 static char **intEnviron = NULL;
60 static int environSize = 0;
63 * Array of environment variables built from environ. Each element records:
64 * name: Pointer to name=value string
65 * name length: Length of name not counting '=' character
66 * value: Pointer to value within same string as name
67 * value size: Size (not length) of space for value not counting the
69 * active state: true/false value to signify whether variable is active.
70 * Useful since multiple variables with the same name can
71 * co-exist. At most, one variable can be active at any
73 * putenv: Created from putenv() call. This memory must not be
76 static struct envVars {
86 * Environment array information.
88 * envActive: Number of active variables in array.
89 * envVarsSize: Size of array.
90 * envVarsTotal: Number of total variables in array (active or not).
92 static int envActive = 0;
93 static int envVarsSize = 0;
94 static int envVarsTotal = 0;
97 /* Deinitialization of new environment. */
98 static void __attribute__ ((destructor)) __clean_env_destructor(void);
102 * A simple version of warnx() to avoid the bloat of including stdio in static
106 __env_warnx(const char *msg, const char *name, size_t nameLen)
108 static const char nl[] = "\n";
109 static const char progSep[] = ": ";
111 _write(STDERR_FILENO, _getprogname(), strlen(_getprogname()));
112 _write(STDERR_FILENO, progSep, sizeof(progSep) - 1);
113 _write(STDERR_FILENO, msg, strlen(msg));
114 _write(STDERR_FILENO, name, nameLen);
115 _write(STDERR_FILENO, nl, sizeof(nl) - 1);
122 * Inline strlen() for performance. Also, perform check for an equals sign.
123 * Cheaper here than peforming a strchr() later.
126 __strleneq(const char *str)
130 for (s = str; *s != '\0'; ++s)
139 * Comparison of an environment name=value to a name.
142 strncmpeq(const char *nameValue, const char *name, size_t nameLen)
144 if (strncmp(nameValue, name, nameLen) == 0 && nameValue[nameLen] == '=')
152 * Using environment, returns pointer to value associated with name, if any,
153 * else NULL. If the onlyActive flag is set to true, only variables that are
154 * active are returned else all are.
157 __findenv(const char *name, size_t nameLen, int *envNdx, bool onlyActive)
162 * Find environment variable from end of array (more likely to be
163 * active). A variable created by putenv is always active, or it is not
164 * tracked in the array.
166 for (ndx = *envNdx; ndx >= 0; ndx--)
167 if (envVars[ndx].putenv) {
168 if (strncmpeq(envVars[ndx].name, name, nameLen)) {
170 return (envVars[ndx].name + nameLen +
173 } else if ((!onlyActive || envVars[ndx].active) &&
174 (envVars[ndx].nameLen == nameLen &&
175 strncmpeq(envVars[ndx].name, name, nameLen))) {
177 return (envVars[ndx].value);
185 * Using environ, returns pointer to value associated with name, if any, else
186 * NULL. Used on the original environ passed into the program.
189 __findenv_environ(const char *name, size_t nameLen)
193 /* Find variable within environ. */
194 for (envNdx = 0; environ[envNdx] != NULL; envNdx++)
195 if (strncmpeq(environ[envNdx], name, nameLen))
196 return (&(environ[envNdx][nameLen + sizeof("=") - 1]));
203 * Remove variable added by putenv() from variable tracking array.
206 __remove_putenv(int envNdx)
209 if (envVarsTotal > envNdx)
210 memmove(&(envVars[envNdx]), &(envVars[envNdx + 1]),
211 (envVarsTotal - envNdx) * sizeof (*envVars));
212 memset(&(envVars[envVarsTotal]), 0, sizeof (*envVars));
219 * Deallocate the environment built from environ as well as environ then set
220 * both to NULL. Eases debugging of memory leaks.
223 __clean_env(bool freeVars)
227 /* Deallocate environment and environ if created by *env(). */
228 if (envVars != NULL) {
229 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--)
230 /* Free variables or deactivate them. */
231 if (envVars[envNdx].putenv) {
233 __remove_putenv(envNdx);
236 free(envVars[envNdx].name);
238 envVars[envNdx].active = false;
246 /* Restore original environ if it has not updated by program. */
247 if (origEnviron != NULL) {
248 if (environ == intEnviron)
249 environ = origEnviron;
261 * Using the environment, rebuild the environ array for use by other C library
262 * calls that depend upon it.
265 __rebuild_environ(int newEnvironSize)
272 /* Resize environ. */
273 if (newEnvironSize > environSize) {
274 tmpEnvironSize = newEnvironSize * 2;
275 tmpEnviron = realloc(intEnviron, sizeof (*intEnviron) *
276 (tmpEnvironSize + 1));
277 if (tmpEnviron == NULL)
279 environSize = tmpEnvironSize;
280 intEnviron = tmpEnviron;
282 envActive = newEnvironSize;
284 /* Assign active variables to environ. */
285 for (envNdx = envVarsTotal - 1, environNdx = 0; envNdx >= 0; envNdx--)
286 if (envVars[envNdx].active)
287 intEnviron[environNdx++] = envVars[envNdx].name;
288 intEnviron[environNdx] = NULL;
290 /* Always set environ which may have been replaced by program. */
291 environ = intEnviron;
298 * Enlarge new environment.
304 struct envVars *tmpEnvVars;
307 if (envVarsTotal > envVarsSize) {
308 newEnvVarsSize = envVarsTotal * 2;
309 tmpEnvVars = realloc(envVars, sizeof (*envVars) *
311 if (tmpEnvVars == NULL) {
315 envVarsSize = newEnvVarsSize;
316 envVars = tmpEnvVars;
324 * Using environ, build an environment for use by standard C library calls.
335 /* Check for non-existant environment. */
336 if (environ == NULL || environ[0] == NULL)
339 /* Count environment variables. */
340 for (env = environ, envVarsTotal = 0; *env != NULL; env++)
342 envVarsSize = envVarsTotal * 2;
344 /* Create new environment. */
345 envVars = calloc(envVarsSize, sizeof(*envVars));
349 /* Copy environ values and keep track of them. */
350 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--) {
351 envVars[envNdx].putenv = false;
352 envVars[envNdx].name =
353 strdup(environ[envVarsTotal - envNdx - 1]);
354 if (envVars[envNdx].name == NULL)
356 envVars[envNdx].value = strchr(envVars[envNdx].name, '=');
357 if (envVars[envNdx].value != NULL) {
358 envVars[envNdx].value++;
359 envVars[envNdx].valueSize =
360 strlen(envVars[envNdx].value);
362 __env_warnx(CorruptEnvValueMsg, envVars[envNdx].name,
363 strlen(envVars[envNdx].name));
369 * Find most current version of variable to make active. This
370 * will prevent multiple active variables from being created
371 * during this initialization phase.
373 nameLen = envVars[envNdx].value - envVars[envNdx].name - 1;
374 envVars[envNdx].nameLen = nameLen;
375 activeNdx = envVarsTotal - 1;
376 if (__findenv(envVars[envNdx].name, nameLen, &activeNdx,
378 __env_warnx(CorruptEnvFindMsg, envVars[envNdx].name,
383 envVars[activeNdx].active = true;
386 /* Create a new environ. */
387 origEnviron = environ;
389 if (__rebuild_environ(envVarsTotal) == 0)
402 * Destructor function with default argument to __clean_env().
405 __clean_env_destructor(void)
414 * Returns the value of a variable or NULL if none are found.
417 getenv(const char *name)
422 /* Check for malformed name. */
423 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
429 * Variable search order:
430 * 1. Check for an empty environ. This allows an application to clear
432 * 2. Search the external environ array.
433 * 3. Search the internal environment.
435 * Since malloc() depends upon getenv(), getenv() must never cause the
436 * internal environment storage to be generated.
438 if (environ == NULL || environ[0] == NULL)
440 else if (envVars == NULL || environ != intEnviron)
441 return (__findenv_environ(name, nameLen));
443 envNdx = envVarsTotal - 1;
444 return (__findenv(name, nameLen, &envNdx, true));
450 * Set the value of a variable. Older settings are labeled as inactive. If an
451 * older setting has enough room to store the new value, it will be reused. No
452 * previous variables are ever freed here to avoid causing a segmentation fault
455 * The variables nameLen and valueLen are passed into here to allow the caller
456 * to calculate the length by means besides just strlen().
459 __setenv(const char *name, size_t nameLen, const char *value, int overwrite)
467 /* Find existing environment variable large enough to use. */
468 envNdx = envVarsTotal - 1;
469 newEnvActive = envActive;
470 valueLen = strlen(value);
472 if (__findenv(name, nameLen, &envNdx, false) != NULL) {
473 /* Deactivate entry if overwrite is allowed. */
474 if (envVars[envNdx].active) {
477 envVars[envNdx].active = false;
481 /* putenv() created variable cannot be reused. */
482 if (envVars[envNdx].putenv)
483 __remove_putenv(envNdx);
485 /* Entry is large enough to reuse. */
486 else if (envVars[envNdx].valueSize >= valueLen)
490 /* Create new variable if none was found of sufficient size. */
492 /* Enlarge environment. */
493 envNdx = envVarsTotal;
494 if (!__enlarge_env())
497 /* Create environment entry. */
498 envVars[envNdx].name = malloc(nameLen + sizeof ("=") +
500 if (envVars[envNdx].name == NULL) {
504 envVars[envNdx].nameLen = nameLen;
505 envVars[envNdx].valueSize = valueLen;
507 /* Save name of name/value pair. */
508 env = stpncpy(envVars[envNdx].name, name, nameLen);
512 env = envVars[envNdx].value;
514 /* Save value of name/value pair. */
516 envVars[envNdx].value = env;
517 envVars[envNdx].active = true;
520 /* No need to rebuild environ if an active variable was reused. */
521 if (reuse && newEnvActive == envActive)
524 return (__rebuild_environ(newEnvActive));
529 * If the program attempts to replace the array of environment variables
530 * (environ) environ or sets the first varible to NULL, then deactivate all
531 * variables and merge in the new list from environ.
534 __merge_environ(void)
540 * Internally-built environ has been replaced or cleared (detected by
541 * using the count of active variables against a NULL as the first value
542 * in environ). Clean up everything.
544 if (intEnviron != NULL && (environ != intEnviron || (envActive > 0 &&
545 environ[0] == NULL))) {
546 /* Deactivate all environment variables. */
553 * Insert new environ into existing, yet deactivated,
556 origEnviron = environ;
557 if (origEnviron != NULL)
558 for (env = origEnviron; *env != NULL; env++) {
559 if ((equals = strchr(*env, '=')) == NULL) {
560 __env_warnx(CorruptEnvValueMsg, *env,
565 if (__setenv(*env, equals - *env, equals + 1,
576 * The exposed setenv() that peforms a few tests before calling the function
577 * (__setenv()) that does the actual work of inserting a variable into the
581 setenv(const char *name, const char *value, int overwrite)
585 /* Check for malformed name. */
586 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
591 /* Initialize environment. */
592 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
595 return (__setenv(name, nameLen, value, overwrite));
600 * Insert a "name=value" string into the environment. Special settings must be
601 * made to keep setenv() from reusing this memory block and unsetenv() from
602 * allowing it to be tracked.
612 /* Check for malformed argument. */
613 if (string == NULL || (equals = strchr(string, '=')) == NULL ||
614 (nameLen = equals - string) == 0) {
619 /* Initialize environment. */
620 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
623 /* Deactivate previous environment variable. */
624 envNdx = envVarsTotal - 1;
625 newEnvActive = envActive;
626 if (__findenv(string, nameLen, &envNdx, true) != NULL) {
627 /* Reuse previous putenv slot. */
628 if (envVars[envNdx].putenv) {
629 envVars[envNdx].name = string;
630 return (__rebuild_environ(envActive));
633 envVars[envNdx].active = false;
637 /* Enlarge environment. */
638 envNdx = envVarsTotal;
639 if (!__enlarge_env())
642 /* Create environment entry. */
643 envVars[envNdx].name = string;
644 envVars[envNdx].nameLen = -1;
645 envVars[envNdx].value = NULL;
646 envVars[envNdx].valueSize = -1;
647 envVars[envNdx].putenv = true;
648 envVars[envNdx].active = true;
651 return (__rebuild_environ(newEnvActive));
656 * Unset variable with the same name by flagging it as inactive. No variable is
660 unsetenv(const char *name)
666 /* Check for malformed name. */
667 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
672 /* Initialize environment. */
673 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
676 /* Deactivate specified variable. */
677 /* Remove all occurrences. */
678 envNdx = envVarsTotal - 1;
679 newEnvActive = envActive;
680 while (__findenv(name, nameLen, &envNdx, true) != NULL) {
681 envVars[envNdx].active = false;
682 if (envVars[envNdx].putenv)
683 __remove_putenv(envNdx);
687 if (newEnvActive != envActive)
688 __rebuild_environ(newEnvActive);