util-lib: rework /tmp and /var/tmp handling code

Beef up the existing var_tmp() call, rename it to var_tmp_dir() and add a
matching tmp_dir() call (the former looks for the place for /var/tmp, the
latter for /tmp).

Both calls check $TMPDIR, $TEMP, $TMP, following the algorithm Python3 uses.
All dirs are validated before use. secure_getenv() is used in order to limite
exposure in suid binaries.

This also ports a couple of users over to these new APIs.

The var_tmp() return parameter is changed from an allocated buffer the caller
will own to a const string either pointing into environ[], or into a static
const buffer. Given that environ[] is mostly considered constant (and this is
exposed in the very well-known getenv() call), this should be OK behaviour and
allows us to avoid memory allocations in most cases.

Note that $TMPDIR and friends override both /var/tmp and /tmp usage if set.
This commit is contained in:
Lennart Poettering
2016-08-04 16:27:07 +02:00
parent eb18df724b
commit 992e8f224b
7 changed files with 125 additions and 60 deletions
+20 -32
View File
@@ -83,47 +83,35 @@ static void test_get_files_in_directory(void) {
}
static void test_var_tmp(void) {
char *tmp_dir = NULL;
char *tmpdir_backup = NULL;
const char *default_var_tmp = NULL;
const char *var_name;
bool do_overwrite = true;
_cleanup_free_ char *tmpdir_backup = NULL;
const char *tmp_dir = NULL, *t;
default_var_tmp = "/var/tmp";
var_name = "TMPDIR";
if (getenv(var_name) != NULL) {
tmpdir_backup = strdup(getenv(var_name));
assert_se(tmpdir_backup != NULL);
t = getenv("TMPDIR");
if (t) {
tmpdir_backup = strdup(t);
assert_se(tmpdir_backup);
}
unsetenv(var_name);
assert(unsetenv("TMPDIR") >= 0);
var_tmp(&tmp_dir);
assert_se(!strcmp(tmp_dir, default_var_tmp));
assert_se(var_tmp_dir(&tmp_dir) >= 0);
assert_se(streq(tmp_dir, "/var/tmp"));
free(tmp_dir);
assert_se(setenv("TMPDIR", "/tmp", true) >= 0);
assert_se(streq(getenv("TMPDIR"), "/tmp"));
setenv(var_name, "/tmp", do_overwrite);
assert_se(!strcmp(getenv(var_name), "/tmp"));
assert_se(var_tmp_dir(&tmp_dir) >= 0);
assert_se(streq(tmp_dir, "/tmp"));
var_tmp(&tmp_dir);
assert_se(!strcmp(tmp_dir, "/tmp"));
assert_se(setenv("TMPDIR", "/88_does_not_exist_88", true) >= 0);
assert_se(streq(getenv("TMPDIR"), "/88_does_not_exist_88"));
free(tmp_dir);
assert_se(var_tmp_dir(&tmp_dir) >= 0);
assert_se(streq(tmp_dir, "/var/tmp"));
setenv(var_name, "/88_does_not_exist_88", do_overwrite);
assert_se(!strcmp(getenv(var_name), "/88_does_not_exist_88"));
var_tmp(&tmp_dir);
assert_se(!strcmp(tmp_dir, default_var_tmp));
free(tmp_dir);
if (tmpdir_backup != NULL) {
setenv(var_name, tmpdir_backup, do_overwrite);
assert_se(!strcmp(getenv(var_name), tmpdir_backup));
free(tmpdir_backup);
if (tmpdir_backup) {
assert_se(setenv("TMPDIR", tmpdir_backup, true) >= 0);
assert_se(streq(getenv("TMPDIR"), tmpdir_backup));
}
}