Modify get_all_remote_parts to read headers

This commit is contained in:
Nick Krichevsky 2018-09-01 17:33:39 -04:00
parent ec2da2168b
commit 0d211539f3
2 changed files with 41 additions and 3 deletions

View file

@ -1,5 +1,6 @@
#include "http_types.h"
#include "socket_helper.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@ -84,25 +85,58 @@ static struct line_read_result read_line(const char *buffer, int buffer_size, st
return result;
}
int get_all_remote_parts(int socket_fd, struct http_message *message) {
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;
bool have_start_line = false;
bool read_data = false;
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);
read_cursor = result;
} else {
write_offset = current_result_size;
current_result_size += bytes_read;
result = realloc(result, current_result_size);
}
memcpy(result + write_offset, buffer, BUFFER_SIZE);
struct line_read_result line_result;
memset(&line_result, 0, sizeof(struct line_read_result));
while ((line_result = read_line(read_cursor, result + current_result_size - read_cursor, message),
line_result.line_type != RESULT_NO_LINE)) {
read_cursor += line_result.bytes_read;
free(line_result.line);
if (!have_start_line && line_result.line_type == RESULT_BLANK_LINE) {
// If we don't have a start line, we can skip any blank lines.
continue;
} else if (!have_start_line && line_result.line_type != RESULT_START_LINE) {
// If we don't start with a start line, we don't have a valid request.
free(buffer);
free(result);
return RESULT_MALFORMED;
} else if (line_result.line_type == RESULT_BLANK_LINE) {
// If we hit a blank line, we're done reading headers.
break;
} else if (line_result.line_type == RESULT_START_LINE) {
if (have_start_line) {
// If we have a start line already, we can't have another.
free(buffer);
free(result);
return RESULT_MALFORMED;
}
have_start_line = true;
}
}
// TODO: parse headers
}
free(buffer);
message->contents = result;
return result;
return RESULT_OK;
}

View file

@ -1,15 +1,19 @@
#ifndef SOCKET_HELPER_H
#define SOCKET_HELPER_H
#include "http_types.h"
#define BUFFER_SIZE 1024
enum line_type {RESULT_START_LINE, RESULT_HEADER, RESULT_BLANK_LINE, RESULT_NO_LINE};
enum socket_read_result {RESULT_OK, RESULT_MALFORMED, RESULT_READ_ERROR};
struct line_read_result {
enum line_type line_type;
// TODO: this just gets freed... do we need it?
char *line;
int bytes_read;
};
char *get_all_remote_parts(int socket_fd);
enum socket_read_result get_all_remote_parts(int socket_fd, struct http_message *message);
#endif