diff --git a/include/http/types.h b/include/http/types.h index cccf0a0..fbbe160 100644 --- a/include/http/types.h +++ b/include/http/types.h @@ -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 { diff --git a/src/http/http_consts.c b/src/http/http_consts.c index 8aa6f4b..a072309 100644 --- a/src/http/http_consts.c +++ b/src/http/http_consts.c @@ -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] = { diff --git a/src/http_loop/http_loop_res.c b/src/http_loop/http_loop_res.c index 5516cb7..8e96b56 100644 --- a/src/http_loop/http_loop_res.c +++ b/src/http_loop/http_loop_res.c @@ -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",