diff options
Diffstat (limited to 'browse.c')
-rw-r--r-- | browse.c | 76 |
1 files changed, 69 insertions, 7 deletions
@@ -43,6 +43,7 @@ #include "config.h" #include "http.h" #include "url.h" +#include "util.h" /* * list of files for current directory @@ -153,13 +154,56 @@ build_file_list(struct kreq * r, char *request_dir) return 0; } +const char *const template_keys[] = {"name", "url"}; + +/* + * data required in the template function + */ +struct template_data { + struct kreq *r; + struct file *f; +}; + +static int +template_callback(size_t index, void *arg) +{ + struct kreq *r; + struct template_data *data; + + if (arg == NULL) { + kutil_warn(NULL, NULL, "Invalid data for browse template"); + return 0; + } + data = arg; + r = data->r; + switch (index) { + case 0: + /* name */ + K_OK(khttp_puts(r, data->f->name), r); + break; + case 1: + /* url */ + K_OK(khttp_puts(r, data->f->url), r); + break; + default: + kutil_warnx(r, NULL, "Invalid key index for browse template: %zd", index); + return 0; + } + + return 1; +} + void browse(struct kreq * r) { - size_t url_len; + size_t url_len, template_buf_len; char current_dir[PATH_MAX]; + char template_path[PATH_MAX]; + char *template_buf; struct file *file; struct khtmlreq html; + struct ktemplate template; + struct template_data data; /* check that the requested URL can be safely processed */ if (!check_request_path(r->path)) @@ -175,6 +219,18 @@ browse(struct kreq * r) if (build_file_list(r, current_dir) < 0) http_exit(r, KHTTP_500, "browse: Unable to build file list"); + /* read template */ + template_path[0] = '\0'; + strlcat(template_path, TEMPLATE_DIR, PATH_MAX); + url_len = strlcat(template_path, "/browse_file.html", PATH_MAX); + if (url_len == 0 || url_len >= PATH_MAX) + http_exit(r, KHTTP_404, "browse: Unable to read template"); + + template_buf = NULL; + if (read_file(template_path, &template_buf, &template_buf_len) < 0 + || template_buf == NULL) + http_exit(r, KHTTP_500, "browse: Unable to read template"); + /* we have all the data we need, we can start to write output page */ http_open(r, KHTTP_200, r->mime); @@ -190,17 +246,23 @@ browse(struct kreq * r) K_OK(khtml_puts(&html, "/"), r); K_OK(khtml_closeelem(&html, 1), r); + /* print file list */ + template.key = template_keys; + template.keysz = 2; + template.cb = template_callback; + template.arg = &data; + data.r = r; + K_OK(khtml_elem(&html, KELEM_UL), r); SLIST_FOREACH(file, &list, files) { - K_OK(khtml_elem(&html, KELEM_LI), r); - K_OK(khtml_attr(&html, KELEM_A, KATTR_HREF, file->url, KATTR__MAX), - r); - K_OK(khtml_puts(&html, file->name), r); - K_OK(khtml_closeelem(&html, 2), r); + data.f = file; + K_OK(khttp_template_buf(r, &template, template_buf, + template_buf_len), r); } K_OK(khtml_close(&html), r); - /* free list */ + /* free list template and list */ + free(template_buf); file = NULL; while (!SLIST_EMPTY(&list)) { file = SLIST_FIRST(&list); |