From f4b68126751be934a24cedc251894e5a225f55c6 Mon Sep 17 00:00:00 2001 From: Cory McWilliams Date: Wed, 20 Dec 2023 23:13:03 +0000 Subject: [PATCH] Auto-add a content-length header. git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@4681 ed5197a5-7fde-0310-b194-c3ffbd925b24 --- src/http.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/http.c b/src/http.c index cd9cf211..feaa93b7 100644 --- a/src/http.c +++ b/src/http.c @@ -296,15 +296,28 @@ void tf_http_respond(tf_http_request_t* request, int status, const char** header { const char* status_text = _http_status_text(status); /* HTTP/1.x 200 OK\r\n */ + bool sent_content_length = false; int headers_length = 8 + 1 + 3 + 1 + strlen(status_text) + 2; for (int i = 0; i < headers_count; i += 2) { /* Key: Value\r\n */ headers_length += strlen(headers[i]) + 2 + strlen(headers[i + 1]) + 2; + if (strcasecmp(headers[i], "content-length") == 0) + { + sent_content_length = true; + } } /* \r\n */ headers_length += 2; + char content_length_buffer[32] = { 0 }; + int content_length_buffer_length = 0; + if (!sent_content_length) + { + content_length_buffer_length = snprintf(content_length_buffer, sizeof(content_length_buffer), "Content-Length: %zd\r\n", content_length); + headers_length += content_length_buffer_length; + } + uv_write_t* write = tf_malloc(sizeof(uv_write_t) + headers_length + content_length + 1); *write = (uv_write_t) { .data = request->connection }; char* buffer = (char*)(write + 1); @@ -313,6 +326,11 @@ void tf_http_respond(tf_http_request_t* request, int status, const char** header { offset += snprintf(buffer + offset, headers_length + 1 - offset, "%s: %s\r\n", headers[i], headers[i + 1]); } + if (!sent_content_length) + { + memcpy(buffer + offset, content_length_buffer, content_length_buffer_length); + offset += content_length_buffer_length; + } offset += snprintf(buffer + offset, headers_length + 1 - offset, "\r\n"); assert(offset == headers_length); if (content_length)