From 2f425cb9e9d28c8e7f017a4fbe1203c7431e745b Mon Sep 17 00:00:00 2001 From: Dennis Camera Date: Mon, 22 Aug 2022 00:27:47 +0200 Subject: Implement command execution --- src/util/fs.c | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'src/util/fs.c') diff --git a/src/util/fs.c b/src/util/fs.c index 72c87f3..762c9a5 100644 --- a/src/util/fs.c +++ b/src/util/fs.c @@ -7,6 +7,8 @@ #include #include #include +#include +#include bool is_dir(const char *restrict pathname) { #ifdef STAT_MACROS_BROKEN @@ -122,3 +124,67 @@ static int __rmtree_fn( int rmtree(const char *dir) { return nftw(dir, __rmtree_fn, 16, FTW_DEPTH | FTW_PHYS); } + +void which( + const char *restrict name, char *restrict resolved_path, + const char *restrict search_path) { + char *path = NULL; + + /* check if name is a path */ + if (realpath(name, resolved_path)) { + if (access(resolved_path, X_OK)) { + return; + } + } + + resolved_path[0] = '\0'; + + if (NULL == search_path) { + /* use PATH from environment */ + search_path = getenv("PATH"); + } + if (NULL != search_path) { + path = strdup(search_path); + } +#ifdef _CS_PATH + if (NULL == search_path) { + /* fall back to POSIX path */ + size_t pathlen = confstr(_CS_PATH, NULL, 0); + path = malloc(pathlen); + if (NULL != path) { + (void)confstr(_CS_PATH, path, pathlen); + } + } +#endif + + if (NULL == path) { + /* cannot determine PATH */ + return; + } + + char *saveptr = NULL; + char *path_tok = strtok_r(path, stringize(PATHSEP), &saveptr); + do { + if (PATH_MAX < pathjoin_r(resolved_path, PATH_MAX+1, path_tok, name)) { + /* TODO: handle error */ + continue; + } + + if (access(resolved_path, X_OK)) { + /* no match */ + resolved_path[0] = '\0'; + continue; + } + + /* match */ + break; + } while ((path_tok = strtok_r(NULL, stringize(PATHSEP), &saveptr))); + + if (!is_empty_string(resolved_path)) { + sk_debug("resolved command %s: %s", name, resolved_path); + } else { + sk_warn("could not resolve command: %s", name); + } + + free(path); +} -- cgit v1.2.3