Find template in root, don't search tail dir twice

This commit is contained in:
Armin Friedl 2020-08-30 09:38:02 +02:00
parent bd51ff593d
commit eba491b4b5
3 changed files with 27 additions and 6 deletions

25
dirl.c
View file

@ -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));

6
dirl.h
View file

@ -22,10 +22,11 @@
"<html>\n" \
" <head>\n" \
" <link rel=\"stylesheet\" href=\"/" DIRL_STYLE "\">\n" \
" <title>Index of {curdir}</title>\n" \
" <title>Index of {uri}</title>\n" \
" </head>\n" \
" <body>\n" \
" <h1>Index of {curdir}</h1>\n" \
" <h1>Index of {uri}</h1>\n" \
" <hr />" \
" <a href=\"..\">..</a>\n"
#define DIRL_ENTRY_DEFAULT \
@ -33,6 +34,7 @@
" <a href=\"{entry}\">{entry}{suffix}</a>\n"
#define DIRL_FOOTER_DEFAULT \
" <hr />" \
" </body>\n" \
"</html>"

2
resp.c
View file

@ -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))) {