refactor: Break env API functions out of the main daemon source

Signed-off-by: Kai Krakow <kai@kaishome.de>
This commit is contained in:
Kai Krakow
2018-10-08 20:57:25 +02:00
parent 748808be7e
commit 92967b135b
4 changed files with 104 additions and 56 deletions

View File

@@ -43,7 +43,6 @@ POSSIBILITY OF SUCH DAMAGE.
#include <fcntl.h>
#include <linux/sched.h>
#include <pthread.h>
#include <pwd.h>
#include <sched.h>
#include <signal.h>
#include <stdatomic.h>
@@ -719,61 +718,6 @@ GameModeContext *game_mode_context_instance()
return &instance;
}
/**
* Lookup the process environment for a specific variable or return NULL.
* Requires an open directory FD from /proc/PID.
*/
static char *game_mode_lookup_proc_env(const procfd_t proc_fd, const char *var)
{
char *environ = NULL;
int fd = openat(proc_fd, "environ", O_RDONLY | O_CLOEXEC);
if (fd != -1) {
FILE *stream = fdopen(fd, "r");
if (stream) {
/* Read every \0 terminated line from the environment */
char *line = NULL;
size_t len = 0;
size_t pos = strlen(var) + 1;
while (!environ && (getdelim(&line, &len, 0, stream) != -1)) {
/* Find a match including the "=" suffix */
if ((len > pos) && (strncmp(line, var, strlen(var)) == 0) && (line[pos - 1] == '='))
environ = strndup(line + pos, len - pos);
}
free(line);
fclose(stream);
} else
close(fd);
}
/* If found variable is empty, skip it */
if (environ && !strlen(environ)) {
free(environ);
environ = NULL;
}
return environ;
}
/**
* Lookup the home directory of the user in a safe way.
*/
static char *game_mode_lookup_user_home(void)
{
/* Try loading env HOME first */
const char *home = secure_getenv("HOME");
if (!home) {
/* If HOME is not defined (or out of context), fall back to passwd */
struct passwd *pw = getpwuid(getuid());
if (!pw)
return NULL;
home = pw->pw_dir;
}
/* Try to allocate into our heap */
return home ? strdup(home) : NULL;
}
/**
* Attempt to resolve the exe for wine-preloader.
* This function is used if game_mode_context_find_exe() identified the