env-util: replace unsetenv_erase() by new getenv_steal_erase() helper

The new helper combines a bunch of steps every invocation of
unsetenv_erase() did so far: getenv() + strdup() + unsetenv_erase().
Let's unify this into one helper that is harder to use incorrectly. It's
in inspired by TAKE_PTR() in a way: get the env var out and invalidate
where it was before.
This commit is contained in:
Lennart Poettering
2022-02-20 12:38:06 +09:00
committed by Yu Watanabe
parent 5cf84d2545
commit e99ca14741
9 changed files with 91 additions and 85 deletions
+23 -6
View File
@@ -868,19 +868,36 @@ int getenv_path_list(const char *name, char ***ret_paths) {
return 1;
}
int unsetenv_erase(const char *name) {
char *p;
int getenv_steal_erase(const char *name, char **ret) {
_cleanup_(erase_and_freep) char *a = NULL;
char *e;
assert(name);
p = getenv(name);
if (!p)
return 0;
/* Reads an environment variable, makes a copy of it, erases its memory in the environment block and removes
* it from there. Usecase: reading passwords from the env block (which is a bad idea, but useful for
* testing, and given that people are likely going to misuse this, be thorough) */
string_erase(p);
e = getenv(name);
if (!e) {
if (ret)
*ret = NULL;
return 0;
}
if (ret) {
a = strdup(e);
if (!a)
return -ENOMEM;
}
string_erase(e);
if (unsetenv(name) < 0)
return -errno;
if (ret)
*ret = TAKE_PTR(a);
return 1;
}
+2
View File
@@ -70,3 +70,5 @@ int setenv_systemd_exec_pid(bool update_only);
int getenv_path_list(const char *name, char ***ret_paths);
int unsetenv_erase(const char *name);
int getenv_steal_erase(const char *name, char **ret);