summaryrefslogtreecommitdiff
path: root/src/util/fs.c
diff options
context:
space:
mode:
authorDennis Camera <skonfig@dtnr.ch>2022-08-22 00:27:47 +0200
committerDennis Camera <skonfig@dtnr.ch>2022-08-22 00:27:47 +0200
commit2f425cb9e9d28c8e7f017a4fbe1203c7431e745b (patch)
tree9ac97abaebdbe3363ee71c6a9f3210799d4494ab /src/util/fs.c
parent580b957769a5ee4ab7522e474f3996c03426a286 (diff)
downloadskonfig-c-2f425cb9e9d28c8e7f017a4fbe1203c7431e745b.tar.gz
skonfig-c-2f425cb9e9d28c8e7f017a4fbe1203c7431e745b.zip
Implement command execution
Diffstat (limited to 'src/util/fs.c')
-rw-r--r--src/util/fs.c66
1 files changed, 66 insertions, 0 deletions
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 <sys/stat.h>
#include <fcntl.h>
#include <ftw.h>
+#include <string.h>
+#include <unistd.h>
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);
+}