1 | /* |
---|
2 | * Replacement for a missing setenv. |
---|
3 | * |
---|
4 | * Provides the same functionality as the standard library routine setenv for |
---|
5 | * those platforms that don't have it. |
---|
6 | * |
---|
7 | * Written by Russ Allbery <rra@stanford.edu> |
---|
8 | * This work is hereby placed in the public domain by its author. |
---|
9 | */ |
---|
10 | |
---|
11 | #include <config.h> |
---|
12 | #include <portable/system.h> |
---|
13 | |
---|
14 | /* |
---|
15 | * If we're running the test suite, rename setenv to avoid conflicts with |
---|
16 | * the system version. |
---|
17 | */ |
---|
18 | #if TESTING |
---|
19 | # define setenv test_setenv |
---|
20 | int test_setenv(const char *, const char *, int); |
---|
21 | #endif |
---|
22 | |
---|
23 | int |
---|
24 | setenv(const char *name, const char *value, int overwrite) |
---|
25 | { |
---|
26 | char *envstring; |
---|
27 | size_t size; |
---|
28 | |
---|
29 | if (!overwrite && getenv(name) != NULL) |
---|
30 | return 0; |
---|
31 | |
---|
32 | /* |
---|
33 | * Allocate memory for the environment string. We intentionally don't use |
---|
34 | * concat here, or the xmalloc family of allocation routines, since the |
---|
35 | * intention is to provide a replacement for the standard library function |
---|
36 | * which sets errno and returns in the event of a memory allocation |
---|
37 | * failure. |
---|
38 | */ |
---|
39 | size = strlen(name) + 1 + strlen(value) + 1; |
---|
40 | envstring = malloc(size); |
---|
41 | if (envstring == NULL) |
---|
42 | return -1; |
---|
43 | |
---|
44 | /* |
---|
45 | * Build the environment string and add it to the environment using |
---|
46 | * putenv. Systems without putenv lose, but XPG4 requires it. |
---|
47 | */ |
---|
48 | strlcpy(envstring, name, size); |
---|
49 | strlcat(envstring, "=", size); |
---|
50 | strlcat(envstring, value, size); |
---|
51 | return putenv(envstring); |
---|
52 | |
---|
53 | /* |
---|
54 | * Note that the memory allocated is not freed. This is intentional; many |
---|
55 | * implementations of putenv assume that the string passed to putenv will |
---|
56 | * never be freed and don't make a copy of it. Repeated use of this |
---|
57 | * function will therefore leak memory, since most implementations of |
---|
58 | * putenv also don't free strings removed from the environment (due to |
---|
59 | * being overwritten). |
---|
60 | */ |
---|
61 | } |
---|