From 30fe078447d35c8fa9004d226fc7bb36a2244102 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Sat, 1 Sep 2018 23:27:42 -0400 Subject: [PATCH] Add ability to read content-lengthd requests --- common/socket_helper.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/common/socket_helper.c b/common/socket_helper.c index b1c4a89..763ae8d 100644 --- a/common/socket_helper.c +++ b/common/socket_helper.c @@ -120,16 +120,32 @@ static struct socket_read_info get_read_info(const struct http_header *headers) return info; } +static char *read_body_by_content_length(int socket_fd, int content_length) { + char *result = malloc((content_length + 1) * sizeof(char)); + char *buffer = malloc(content_length * sizeof(char)); + int total_bytes_read = 0; + int bytes_read = 0; + int write_offset = 0; + while ((total_bytes_read += bytes_read = read(socket_fd, buffer, content_length)) < content_length && bytes_read > 0) { + memcpy(result + write_offset, buffer, content_length) + write_offset += bytes_read; + } + free(buffer); + result[total_bytes_read] = '\0'; + + return result; +} + enum socket_read_result get_all_remote_parts(int socket_fd, struct http_message *message) { ssize_t current_result_size = 0; char *result = NULL; char *buffer = malloc(BUFFER_SIZE * sizeof(char)); char *read_cursor; ssize_t bytes_read; + int write_offset = 0; bool have_start_line = false; - bool read_data = false; + // Loop through all available info until we hit the end of the headers. while ((bytes_read = read(socket_fd, buffer, BUFFER_SIZE)) > 0) { - int write_offset = 0; //Allocate a new result buffer if we need to, otherwise grow the existing one. if (result == NULL) { result = malloc(bytes_read); @@ -168,8 +184,19 @@ enum socket_read_result get_all_remote_parts(int socket_fd, struct http_message have_start_line = true; } } - // TODO: parse headers } + struct socket_read_info read_info = get_read_info(message->headers); + char *body_result; + if (read_info.strategy == STRATEGY_CHUNKED) { + // TODO: Implement + } else if (read_info.strategy == STRATEGY_CONTENT_LENGTH) { + body_result = read_body_by_content_length(socket_fd, read_info.length); + } else { + // TODO: Implement + } + strcpy(result + write_offset, body_result); + free(body_result); + free(buffer); message->contents = result;