From 323fa65921ad207f11b98a2468ea8b7e984f3899 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Wed, 31 May 2023 13:29:13 +0200 Subject: [PATCH] feat: configure api key using env var --- include/http/types.h | 4 ++-- src/http/types.c | 4 +--- src/http_loop/http_loop_steps.c | 7 ++++--- src/main.c | 11 ++++++++++- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/include/http/types.h b/include/http/types.h index 27b3133..06e3da8 100644 --- a/include/http/types.h +++ b/include/http/types.h @@ -1,9 +1,9 @@ #ifndef LANDER_HTTP_TYPES #define LANDER_HTTP_TYPES -#include -#include #include +#include +#include // Array mapping the http_request_method enum to strings extern const char *http_method_names[]; diff --git a/src/http/types.c b/src/http/types.c index e2f3cfa..d7f2647 100644 --- a/src/http/types.c +++ b/src/http/types.c @@ -2,9 +2,7 @@ #include "http/types.h" -http_body *http_body_init() { - return calloc(sizeof(http_body), 1); -} +http_body *http_body_init() { return calloc(sizeof(http_body), 1); } void http_body_reset(http_body *body) { if (body->type == http_body_file) { diff --git a/src/http_loop/http_loop_steps.c b/src/http_loop/http_loop_steps.c index e5d3436..bd91109 100644 --- a/src/http_loop/http_loop_steps.c +++ b/src/http_loop/http_loop_steps.c @@ -76,8 +76,8 @@ bool http_loop_step_body_to_buf(event_loop_conn *conn) { size_t bytes_to_copy = MIN(conn->rbuf_size - conn->rbuf_read, ctx->req.body.expected_len - ctx->req.body.len); - memcpy(&ctx->req.body.buf[ctx->req.body.len], - &conn->rbuf[conn->rbuf_read], bytes_to_copy); + memcpy(&ctx->req.body.buf[ctx->req.body.len], &conn->rbuf[conn->rbuf_read], + bytes_to_copy); ctx->req.body.len += bytes_to_copy; conn->rbuf_read += bytes_to_copy; @@ -114,7 +114,8 @@ bool http_loop_step_auth(event_loop_conn *conn) { struct phr_header *header = &ctx->req.headers[i]; if ((strncmp("X-Api-Key", header->name, header->name_len) == 0) && - (strncmp(header->value, ctx->g->api_key, header->value_len) == 0)) { + (strncmp(header->value, ctx->g->api_key, header->value_len) == 0) && + strlen(ctx->g->api_key) == header->value_len) { return true; } } diff --git a/src/main.c b/src/main.c index b69931d..bc956b8 100644 --- a/src/main.c +++ b/src/main.c @@ -3,9 +3,18 @@ #include "lander.h" #include "log.h" +#define ENV(var, env_var) \ + const char *var = getenv(env_var); \ + if (var == NULL) { \ + critical(1, "Missing environment variable %s", env_var); \ + } \ + var = strdup(var); + int main() { setvbuf(stdout, NULL, _IONBF, 0); + ENV(api_key, "LANDER_API_KEY"); + info("Initializing trie"); Trie *trie; @@ -21,7 +30,7 @@ int main() { gctx->trie = trie; gctx->routes = lander_routes; gctx->route_count = sizeof(lander_routes) / sizeof(lander_routes[0]); - gctx->api_key = "test"; + gctx->api_key = api_key; event_loop *el = http_loop_init(gctx); http_loop_run(el, 18080);