diff options
author | tomsmeding <tom.smeding@gmail.com> | 2019-11-23 23:41:10 +0100 |
---|---|---|
committer | tomsmeding <tom.smeding@gmail.com> | 2019-11-23 23:41:10 +0100 |
commit | c04fbe3df564c66b0f4261a4013ea349ab41418c (patch) | |
tree | 2ad4ae7d5897bccd905b7173e1eba2fa2cbfd644 /plugins/static | |
parent | 0d2c5f9602db67810c1c9551ca59ac840339b56b (diff) |
static: Make thread-safe
Diffstat (limited to 'plugins/static')
-rw-r--r-- | plugins/static/static.c | 40 |
1 files changed, 18 insertions, 22 deletions
diff --git a/plugins/static/static.c b/plugins/static/static.c index 2fb6e0f..0b39afe 100644 --- a/plugins/static/static.c +++ b/plugins/static/static.c @@ -2,15 +2,16 @@ #include <stdlib.h> #include <stdbool.h> #include <string.h> -#include <assert.h> #include <errno.h> #include <unistd.h> #include <sys/stat.h> +#include "memory.h" #include "plugin.h" #include "util.h" #include "buffer.h" +// Will only be set once in the registration function, which is before any threading is done static char *static_file_dir = NULL; @@ -29,20 +30,9 @@ static bool path_allowed(const char *path) { return true; } -// Returns pointer to internal buffer, don't free -static const char* make_relative_path(const char *path) { - static char *rel = NULL; - static size_t rel_cap = 0; - - size_t necessary = strlen(static_file_dir) + 1 + strlen(path) + 1; - if (necessary >= rel_cap) { - rel_cap = necessary; - rel = realloc(rel, rel_cap); - assert(rel); - } - +static char* make_relative_path(const char *path) { + char *rel = malloc(strlen(static_file_dir) + 1 + strlen(path) + 1, char); sprintf(rel, "%s/%s", static_file_dir, path); - return rel; } @@ -98,33 +88,39 @@ static void send_500(int sock) { } static Handler_ret_t connection_handler(int sock, Headers *headers) { + char *path = NULL; + struct buffer buffer; + buffer.buf = NULL; + if (!path_allowed(headers->url)) { send_404(sock); - return HR_HANDLED; + goto cleanup_return; } - const char *path = make_relative_path(headers->url); + path = make_relative_path(headers->url); ssize_t size = query_file_size(path); if (size < 0) { if (errno == ENOENT || errno == EISDIR) { send_404(sock); - return HR_HANDLED; + goto cleanup_return; } else { send_500(sock); - return HR_HANDLED; + goto cleanup_return; } } - struct buffer buffer = build_response_headers("200 OK", "text/plain; charset=UTF-8", size); + buffer = build_response_headers("200 OK", "text/plain; charset=UTF-8", size); if (!buffer_append_file(&buffer, path)) { - buffer_free(buffer); send_500(sock); - return HR_HANDLED; + goto cleanup_return; } sendall(sock, buffer.buf, buffer.len); - buffer_free(buffer); + +cleanup_return: + if (buffer.buf) buffer_free(buffer); + if (path) free(path); return HR_HANDLED; } |