Use copied strings instead of consts for http_message

attempt-2
Nick Krichevsky 2018-08-29 18:46:49 -04:00
parent eadb440bcb
commit e93c07a0a2
2 changed files with 18 additions and 7 deletions

View File

@ -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;
}

View File

@ -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