From eba491b4b5bc9b061f78276d4a741294dc94b3a2 Mon Sep 17 00:00:00 2001 From: Armin Friedl Date: Sun, 30 Aug 2020 09:38:02 +0200 Subject: [PATCH] Find template in root, don't search tail dir twice --- dirl.c | 25 ++++++++++++++++++++++--- dirl.h | 6 ++++-- resp.c | 2 +- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/dirl.c b/dirl.c index 900ecd0..764d750 100644 --- a/dirl.c +++ b/dirl.c @@ -44,6 +44,11 @@ dirl_find_templ_dir(const char* start_path) char* path_buf = calloc(sizeof(char), strlen(start_path)); strcat(path_buf, start_path); + if(path_buf[strlen(path_buf)-1] == '/') { + // don't read last dir twice + path_buf[strlen(path_buf)-1] = '\0'; + } + while (strlen(path_buf) != 0) { DIR* cur = opendir(path_buf); struct dirent* de; @@ -58,8 +63,17 @@ dirl_find_templ_dir(const char* start_path) } } - char* parent = strrchr(path_buf, '/'); - (*parent) = '\0'; // strip tail from path_buf + if (strlen(path_buf) > 1) { + char* parent = strrchr(path_buf, '/'); + (*parent) = '\0'; // strip tail from path_buf + + if(strlen(path_buf) == 0) { // we stripped root, let it loop once more + path_buf[0] = '/'; + path_buf[1] = '\0'; + } + } else { + path_buf[0] = '\0'; // we checked root, now terminate loop + } } free(path_buf); @@ -70,6 +84,11 @@ dirl_find_templ_dir(const char* start_path) static void dirl_fill_templ(char** templ, char* base, char* name, char* def) { + if (!base || !name) { + *templ = def; + return; + } + char* path = calloc(sizeof(char), strlen(base) + strlen(name)); strcpy(path, base); strcat(path, name); @@ -106,7 +125,7 @@ dirl_header(int fd, const struct response* res, const struct dirl_templ* templ) /* Replace placeholder */ char* nhead = calloc(sizeof(char), strlen(templ->header)); memcpy(nhead, templ->header, strlen(templ->header)); - replace(&nhead, "{curdir}", res->path); + replace(&nhead, "{uri}", res->uri); /* Write header */ write(fd, nhead, strlen(nhead)); diff --git a/dirl.h b/dirl.h index b374c01..ebdc4f8 100644 --- a/dirl.h +++ b/dirl.h @@ -22,10 +22,11 @@ "\n" \ " \n" \ " \n" \ - " Index of {curdir}\n" \ + " Index of {uri}\n" \ " \n" \ " \n" \ - "

Index of {curdir}

\n" \ + "

Index of {uri}

\n" \ + "
" \ " ..\n" #define DIRL_ENTRY_DEFAULT \ @@ -33,6 +34,7 @@ " {entry}{suffix}\n" #define DIRL_FOOTER_DEFAULT \ + "
" \ " \n" \ "" diff --git a/resp.c b/resp.c index 2042405..ea9d388 100644 --- a/resp.c +++ b/resp.c @@ -41,7 +41,7 @@ resp_dir(int fd, const struct response *res) } /* read templates */ - struct dirl_templ templates = dirl_read_templ(res->path); + struct dirl_templ templates = dirl_read_templ(res->uri); /* listing header */ if ((ret = dirl_header(fd, res, &templates))) {