1 /* $Id: environ.c,v 1.3 2009-08-09 17:57:39 tcunha Exp $ */
4 * Copyright (c) 2009 Nicholas Marriott <nicm@users.sourceforge.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
27 * Environment - manipulate a set of environment variables.
30 RB_GENERATE(environ
, environ_entry
, entry
, environ_cmp
);
33 environ_cmp(struct environ_entry
*envent1
, struct environ_entry
*envent2
)
35 return (strcmp(envent1
->name
, envent2
->name
));
39 environ_init(struct environ
*env
)
45 environ_free(struct environ
*env
)
47 struct environ_entry
*envent
;
49 while (!RB_EMPTY(env
)) {
50 envent
= RB_ROOT(env
);
51 RB_REMOVE(environ
, env
, envent
);
53 if (envent
->value
!= NULL
)
60 environ_copy(struct environ
*srcenv
, struct environ
*dstenv
)
62 struct environ_entry
*envent
;
64 RB_FOREACH(envent
, environ
, srcenv
)
65 environ_set(dstenv
, envent
->name
, envent
->value
);
68 struct environ_entry
*
69 environ_find(struct environ
*env
, const char *name
)
71 struct environ_entry envent
;
73 envent
.name
= (char *) name
;
74 return (RB_FIND(environ
, env
, &envent
));
78 environ_set(struct environ
*env
, const char *name
, const char *value
)
80 struct environ_entry
*envent
;
82 if ((envent
= environ_find(env
, name
)) != NULL
) {
83 if (envent
->value
!= NULL
)
86 envent
->value
= xstrdup(value
);
90 envent
= xmalloc(sizeof *envent
);
91 envent
->name
= xstrdup(name
);
93 envent
->value
= xstrdup(value
);
96 RB_INSERT(environ
, env
, envent
);
101 environ_put(struct environ
*env
, const char *var
)
105 value
= strchr(var
, '=');
111 name
[strcspn(name
, "=")] = '\0';
113 environ_set(env
, name
, value
);
118 environ_unset(struct environ
*env
, const char *name
)
120 struct environ_entry
*envent
;
122 if ((envent
= environ_find(env
, name
)) == NULL
)
124 RB_REMOVE(environ
, env
, envent
);
126 if (envent
->value
!= NULL
)
127 xfree(envent
->value
);
132 environ_update(const char *vars
, struct environ
*srcenv
, struct environ
*dstenv
)
134 struct environ_entry
*envent
;
135 char *copyvars
, *var
, *next
;
137 copyvars
= next
= xstrdup(vars
);
138 while ((var
= strsep(&next
, " ")) != NULL
) {
139 if ((envent
= environ_find(srcenv
, var
)) == NULL
)
140 environ_set(dstenv
, var
, NULL
);
142 environ_set(dstenv
, envent
->name
, envent
->value
);