From 41c1284bd4bc791a65a2e07faeaec82f5dd4066c Mon Sep 17 00:00:00 2001 From: Max Christian Pohle Date: Wed, 10 Nov 2021 20:38:34 +0100 Subject: http answer implemented --- main.c | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 63 insertions(+), 10 deletions(-) diff --git a/main.c b/main.c index 18e33f5..b8be592 100644 --- a/main.c +++ b/main.c @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include @@ -10,16 +12,63 @@ #include -void * next_customer(int new_socket) +void * next_customer(void * new_socket) { - char *hello = "Hello from server"; - char buffer[1024] = {0}; - int valread = read(new_socket, buffer, 1024); - printf("%s %d\n", buffer, valread); + if (new_socket == 0) return NULL; - send(new_socket, hello, strlen(hello), 0); - printf("Hello message sent\n"); + // read the input data... + char * input_buffer = {0}; + size_t input_buffer_position = 0; + FILE * f_input = open_memstream(&input_buffer, &input_buffer_position); + + + for( + int size=1024, + read_buffer[1024] = {0}; + size>0; + size=recv((size_t) new_socket, read_buffer, 1024, MSG_WAITALL)) { + fwrite(read_buffer, size, 1, f_input); + usleep(10); // TODO: implement with some sort of epoll + } + + fflush(f_input); + printf("input_buffer has %ld bytes and contains:\n", input_buffer_position); + + char * c = strstr(input_buffer, "Content-Type"); + printf("WE ARE HERE: %s\n", c); + write(STDOUT_FILENO, input_buffer, input_buffer_position); + + + + // answer the call... + + char * buffer = {0}; + size_t buffer_position = 0; + FILE * f = open_memstream(&buffer, &buffer_position); + fputs("HTTP/1.0 200 OK\n", f); + fputs("content-type: text/html\n\n", f); + fputs("", f); + fputs("", f); + fputs("test", f); + fputs("", f); + fputs("", f); + fputs("
", f); + fputs("
\n", f); + fputs("", f); + fputs("
", f); + fputs("\n", f); + fflush(f); + printf("OOOOO [%ld] %s\n", buffer_position, buffer); + + send((size_t) new_socket, buffer, buffer_position, MSG_EOR); + // fclose(f_socket); + close((size_t) new_socket); + fclose(f_input); + fclose(f); + return NULL; } @@ -29,13 +78,17 @@ void serve(int server_fd) int addrlen = sizeof(address); warn("waiting for connections on %d", server_fd); - for(int new_socket = 0 + for(size_t new_socket = 0 ; 1 ; new_socket=accept(server_fd, (struct sockaddr*) &address, (socklen_t*) &addrlen)) { - warn("next: %d", new_socket); + warn("next: %ld\n", new_socket); + // set non blocking mode... + fcntl((size_t) new_socket, F_SETFL, + fcntl((size_t) new_socket, F_GETFL) | O_NONBLOCK); + // next_customer(new_socket); pthread_t thread_id; - pthread_create(&thread_id, NULL, next_customer, new_socket); + pthread_create(&thread_id, NULL, next_customer, (void*) new_socket); pthread_join(thread_id, NULL); } } -- cgit v1.2.3