diff --git a/src/include/tcp.h b/src/include/tcp.h index 12cc39a..f83f4bc 100644 --- a/src/include/tcp.h +++ b/src/include/tcp.h @@ -16,7 +16,7 @@ typedef struct { void setup_socket(server_conn_t* conn); -void recv_message(char** buffer, int socket); +int recv_message(char** buffer, int socket); /// Threaded function to handle http requests /// takes client socket as an argument diff --git a/src/tcp.c b/src/tcp.c index 205dc68..84ef4fa 100644 --- a/src/tcp.c +++ b/src/tcp.c @@ -42,7 +42,7 @@ void setup_socket(server_conn_t* conn) } } -void recv_message(char** buffer, int socket) +int recv_message(char** buffer, int socket) { ulong current_size, bytes_recv; int status; @@ -70,15 +70,22 @@ void recv_message(char** buffer, int socket) // lets recv BUFFER_INC_LEN amount of bytes status = recv(socket, *buffer + bytes_recv, BUFFER_INC_LEN, MSG_DONTWAIT); if (status < 0) { - if (errno != EAGAIN && errno != EWOULDBLOCK) // these signify that that were just no data to read, dw about this + // these signify that that were just no data to read, dw about this + if (errno != EAGAIN && errno != EWOULDBLOCK) { perror("recv"); - break; // don't want to crash on a recv failure, lets just break + } + return -1; + } bytes_recv += status; - } while (status == BUFFER_INC_LEN); // break when we stop receiving, status < BUFFER_INC_LEN means no more data after this last call + // break when we stop receiving, status < BUFFER_INC_LEN + // means no more data after this last call + } while (status == BUFFER_INC_LEN); (*buffer)[bytes_recv] = '\0'; + + return 0; } void* connection_handler(void* arg) @@ -86,15 +93,19 @@ void* connection_handler(void* arg) int client_socket = *(int*) arg; http_request request; char* buffer = NULL; + int err; - recv_message(&buffer, client_socket); + err = recv_message(&buffer, client_socket); + if (err == -1) { // if we had a recv error lets throw away the result + free(buffer); + close(client_socket); + return NULL; + } puts(buffer); parse_http_request(&buffer, &request); - printf("%s %s %1.1f\n", http_method_to_str(request.method), request.request_uri, request.version); - /** * Handle HTTP request here :) */