From e93c07a0a20af1664bc89c16b514c6f9b9c5bbf8 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Wed, 29 Aug 2018 18:46:49 -0400 Subject: [PATCH] Use copied strings instead of consts for http_message --- client/http_socket.c | 19 +++++++++++++++---- common/http_message.h | 6 +++--- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/client/http_socket.c b/client/http_socket.c index e088d4e..d070e3a 100644 --- a/client/http_socket.c +++ b/client/http_socket.c @@ -34,16 +34,27 @@ static size_t get_buffer_size(const char **components, int num_components) { * @param path The path on the host requested * @param port The port of the host requested * - * @return A http_message - note that the contents field has been mallocced and must be manually freed. + * @return A http_message - note that all host, path, and contents must all be freed using free_basic_request */ struct http_message build_basic_request(const char *method, const char *host, const char *path, int port) { + struct http_message message; + + int host_length = strlen(host) + 1; + message.address = malloc(host_length * sizeof(char)); + strcpy(message.address, host); + + message.port = port; + + int path_length = strlen(path) + 1; + message.path = malloc(path_length * sizeof(char)); + strcpy(message.path, host); + const char *request_line_components[] = {method, " ", path, " ", HTTP_VERSION, "\r\n"}; const char *host_header[] = {"Host: ", host, "\r\n"}; // Add the size of the buffers, plus space for the trailing carriage return and the null term. int message_buffer_size = get_buffer_size(request_line_components, 6) + get_buffer_size(host_header, 3) + 2 + 1; - char *message_buffer = malloc(message_buffer_size * sizeof(char)); - sprintf(message_buffer, "%s %s %s\r\nHost: %s\r\n\r\n", method, path, HTTP_VERSION, host); - struct http_message message = {host, port, path, message_buffer}; + message.contents = malloc(message_buffer_size * sizeof(char)); + sprintf(message.contents, "%s %s %s\r\nHost: %s\r\n\r\n", method, path, HTTP_VERSION, host); return message; } diff --git a/common/http_message.h b/common/http_message.h index 7aef327..48d103b 100644 --- a/common/http_message.h +++ b/common/http_message.h @@ -1,9 +1,9 @@ #ifndef HTTP_MESSAGE_H #define HTTP_MESSAGE_H struct http_message { - const char *address; + char *address; int port; - const char *path; - const char *contents; + char *path; + char *contents; }; #endif