From 72e5fe5b8f09d88affb473f0fd6d0f787dbc37c9 Mon Sep 17 00:00:00 2001 From: Cory McWilliams Date: Sat, 30 Dec 2023 20:35:03 +0000 Subject: [PATCH] Allow receiving fragmented websocket messages. I thought this was what was breaking me on Android, but it's not. git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@4711 ed5197a5-7fde-0310-b194-c3ffbd925b24 --- src/http.c | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/http.c b/src/http.c index f3c828df..c409baa2 100644 --- a/src/http.c +++ b/src/http.c @@ -54,6 +54,8 @@ typedef struct _tf_http_connection_t bool is_websocket; int websocket_message_index; void* body; + void* fragment; + size_t fragment_length; size_t body_length; size_t content_length; bool connection_close; @@ -175,6 +177,11 @@ static void _http_connection_destroy(tf_http_connection_t* connection, const cha tf_free(connection->body); connection->body = NULL; } + if (connection->fragment) + { + tf_free(connection->fragment); + connection->fragment = NULL; + } tf_free(connection); } } @@ -187,6 +194,7 @@ static void _http_builtin_404_handler(tf_http_request_t* request) static void _http_reset_connection(tf_http_connection_t* connection) { + connection->fragment_length = 0; connection->body_length = 0; connection->content_length = 0; connection->headers_buffer_length = 0; @@ -267,16 +275,22 @@ static void _http_add_body_bytes(tf_http_connection_t* connection, const void* d (uint32_t)p[mask_start + 2] << 16 | (uint32_t)p[mask_start + 3] << 24; _http_websocket_mask_in_place(p + mask_start + 4, mask, length); + + const uint8_t* message = p + mask_start + 4; + if (!fin || connection->fragment_length) + { + connection->fragment = tf_realloc(connection->fragment, connection->fragment_length + length); + memcpy((uint8_t*)connection->fragment + connection->fragment_length, message, length); + connection->fragment_length += length; + } + if (fin) { if (connection->request->on_message) { - connection->request->on_message(connection->request, op_code, p + mask_start + 4, length); - } - else - { - tf_printf("MESSAGE %d [%.*s]\n", op_code, (int)length, p + mask_start + 4); + connection->request->on_message(connection->request, op_code, connection->fragment_length ? connection->fragment : message, connection->fragment_length ? connection->fragment_length : length); } + connection->fragment_length = 0; } connection->websocket_message_index++; size_t total_length = mask_start + 4 + length;