lander/lnm/src/http/lnm_http_loop_steps.c

45 lines
1.4 KiB
C

#include <string.h>
#include "lnm/http/consts.h"
#include "lnm/http/loop.h"
#include "lnm/loop.h"
lnm_http_step_err lnm_http_loop_step_body_to_buf(lnm_http_conn *conn) {
lnm_http_loop_ctx *ctx = conn->ctx;
if (ctx->req.body.buf == NULL) {
ctx->req.body.buf = malloc(ctx->req.body.expected_len * sizeof(char));
ctx->req.body.len = 0;
}
size_t to_read = LNM_MIN(conn->r.size - conn->r.read,
ctx->req.body.expected_len - ctx->req.body.len);
memcpy(&ctx->req.body.buf[ctx->req.body.len], &conn->r.buf[conn->r.read],
to_read);
ctx->req.body.len += to_read;
conn->r.read += to_read;
return ctx->req.body.len == ctx->req.body.expected_len
? lnm_http_step_err_done
: lnm_http_step_err_io_needed;
}
lnm_http_step_err lnm_http_loop_step_auth(lnm_http_conn *conn) {
lnm_http_loop_ctx *ctx = conn->ctx;
// If there's no API key, requests are always authorized
bool authorized = ctx->g->api_key == NULL;
const char *value;
size_t value_len;
if (!authorized && lnm_http_req_header_get_s(&value, &value_len, &ctx->req,
"X-Api-Key") == lnm_err_ok) {
authorized = (value_len == strlen(ctx->g->api_key)) &&
(memcmp(value, ctx->g->api_key, value_len) == 0);
}
ctx->res.status = authorized ? ctx->res.status : lnm_http_status_unauthorized;
return authorized ? lnm_http_step_err_done : lnm_http_step_err_res;
}