reading http request. ready for parsing

This commit is contained in:
2025-06-16 23:13:18 +02:00
parent 2e22186952
commit 9adeaa8ff9
2 changed files with 56 additions and 3 deletions

54
http.c
View File

@ -2,6 +2,7 @@
#include <strops.h> #include <strops.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
/* TODO: https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable */ /* TODO: https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable */
int http_init(int port, int connection_amount) { int http_init(int port, int connection_amount) {
@ -42,13 +43,62 @@ HTTP_Request* http_accept(int server) {
/* TODO: Read entire message and parse into request struct */ /* TODO: Read entire message and parse into request struct */
ssize_t bytes_read; ssize_t bytes_read;
size_t bufsize = 1024; size_t bufsize = 4096;
char buf[bufsize]; char buf[bufsize];
bytes_read = read(request->client_sock, buf, bufsize - 1); bytes_read = read(request->client_sock, buf, bufsize - 1);
if (bytes_read == -1) { if (bytes_read == -1) {
perror("Failed to read data"); perror("Failed to read data");
} }
printf("%s", buf);
/* TODO: read tmp line by line */
char *tmp = strops_trim_left_string(buf, "\r\n");
size_t lines_count = 0;
size_t lines_capacity = 10;
char **lines = malloc(lines_capacity * sizeof (char*));
size_t i;
while (strops_length(tmp) > 0) {
char *line = malloc(strops_length(tmp));
memset(line, 0, strops_length(tmp));
for (i = 0; i < strops_length(tmp); i++) {
if (tmp[i] == '\r' && tmp[i + 1] == '\n') {
i += 2;
break;
}
line[i] = tmp[i];
}
for (; i > 0; i--) {
strops_remove_at_pos_char_inplace(tmp, 0);
}
if (lines_count >= lines_capacity) {
lines_capacity *= 2;
lines = realloc(lines, lines_capacity * sizeof (char*));
}
lines[lines_count] = line;
lines_count++;
}
free(tmp);
/* TODO: Parse lines */
/* TODO: find suitable data structure for field-lines */
/*
request-line => method target version
seperated by whitespace (SP)
field-line => field-name:field-value
seperated by a single colon => ':'
field-value may have leading and trailing optionial whitespace (OWS)
*/
for (i = 0; i < lines_count; i++) {
printf("%s\n", lines[i]);
}
/* TODO: remeber to delete this code after finishing parsing code */
for (i = lines_count; i > 0; i--) {
free(lines[i]);
}
free(lines);
return request;
} }

View File

@ -20,6 +20,10 @@ HTTP_Response* handle_client(HTTP_Request *request) {
return NULL; return NULL;
} }
/*
TODO: implement signals
TODO: graceful server shutdown
*/
int main() { int main() {
int ret; int ret;
int server; int server;
@ -37,7 +41,6 @@ int main() {
handle_client(request); handle_client(request);
close(request->client_sock); close(request->client_sock);
free(request); free(request);
break;
} }
close(server); close(server);