refactor(http): pass Server & Content-Length as proper headers
ci/woodpecker/push/build Pipeline was successful Details

lnm
Jef Roosens 2023-11-20 22:41:49 +01:00
parent 380605ea08
commit 1587b923c1
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
3 changed files with 30 additions and 10 deletions

View File

@ -125,7 +125,9 @@ typedef enum http_header {
http_header_connection = 0,
http_header_location,
http_header_content_type,
http_header_content_disposition
http_header_content_disposition,
http_header_server,
http_header_content_length
} http_header;
typedef enum http_body_type {

View File

@ -97,7 +97,9 @@ const char *http_header_names[] = {
"Connection",
"Location",
"Content-Type",
"Content-Disposition"
"Content-Disposition",
"Server",
"Content-Length"
};
const char *http_mime_type_names[][2] = {

View File

@ -1,10 +1,19 @@
#include "http_loop.h"
#include "log.h"
// cppcheck-suppress syntaxError
static const char *http_response_format = "HTTP/1.1 %i %s\n"
"Server: lander/" LANDER_VERSION "\n"
"Content-Length: %lu\n";
static const char *server = "lander/" LANDER_VERSION;
static int num_digits(size_t n) {
int digits = 1;
while (n > 9) {
digits++;
n /= 10;
}
return digits;
}
/*
* This function precalculates the size of the total buffer required using
@ -17,12 +26,20 @@ void http_loop_init_header(http_response *res) {
res->status = http_ok;
}
http_res_add_header(res, http_header_server, server, false);
char *content_length_header = malloc(num_digits(res->body.expected_len) + 1);
sprintf(content_length_header, "%zu", res->body.expected_len);
http_res_add_header(res, http_header_content_length, content_length_header,
true);
const char *response_type_name =
http_status_names[res->status / 100 - 1][res->status % 100];
// First we calculate the size of the start of the header
int buf_size = snprintf(NULL, 0, http_response_format, res->status,
response_type_name, res->body.expected_len);
int buf_size =
snprintf(NULL, 0, "HTTP/1.1 %i %s\n", res->status, response_type_name);
// We add each header's required size
for (size_t i = 0; i < res->headers.len; i++) {
@ -34,8 +51,7 @@ void http_loop_init_header(http_response *res) {
// The + 1 is required to store the final null byte, but we will replace it
// with the required final newline
char *buf = malloc(buf_size + 1);
buf_size = sprintf(buf, http_response_format, res->status, response_type_name,
res->body.expected_len);
buf_size = sprintf(buf, "HTTP/1.1 %i %s\n", res->status, response_type_name);
for (size_t i = 0; i < res->headers.len; i++) {
buf_size += sprintf(&buf[buf_size], "%s: %s\n",