move msghdr and cmsghdr out of bits/socket.h
[musl.git] / src / env / setenv.c
blobc5226b6d3c52fee58e34c86e1183804420e3af91
1 #include <stdlib.h>
2 #include <string.h>
3 #include <errno.h>
5 void __env_rm_add(char *old, char *new)
7 static char **env_alloced;
8 static size_t env_alloced_n;
9 for (size_t i=0; i < env_alloced_n; i++)
10 if (env_alloced[i] == old) {
11 env_alloced[i] = new;
12 free(old);
13 return;
14 } else if (!env_alloced[i] && new) {
15 env_alloced[i] = new;
16 new = 0;
18 if (!new) return;
19 char **t = realloc(env_alloced, sizeof *t * (env_alloced_n+1));
20 if (!t) return;
21 (env_alloced = t)[env_alloced_n++] = new;
24 int setenv(const char *var, const char *value, int overwrite)
26 char *s;
27 size_t l1, l2;
29 if (!var || !(l1 = __strchrnul(var, '=') - var) || var[l1]) {
30 errno = EINVAL;
31 return -1;
33 if (!overwrite && getenv(var)) return 0;
35 l2 = strlen(value);
36 s = malloc(l1+l2+2);
37 if (!s) return -1;
38 memcpy(s, var, l1);
39 s[l1] = '=';
40 memcpy(s+l1+1, value, l2+1);
41 return __putenv(s, l1, s);