bpaul-http

http server that will eventually be used for bpaul.xyz
Log | Files | Refs | README

commit 6f1cd0fc5e1fcbd85ce24b391319be9d5a0dc7ad
parent 6f5c18a1dcd1e0970546e3530cebc3980a624483
Author: benjamin paul <bpaul@bpaul.xyz>
Date:   Sun,  1 Aug 2021 20:59:21 +1000

memory debugging i think

Diffstat:
MMakefile | 2+-
Mfile.c | 5++++-
Mhttp.c | 2+-
Mmain.c | 10++++++----
Mtcp.c | 9++++-----
5 files changed, 16 insertions(+), 12 deletions(-)

diff --git a/Makefile b/Makefile @@ -1,2 +1,2 @@ all: - ${CC} *.c -o prog + ${CC} -g *.c -o prog diff --git a/file.c b/file.c @@ -1,3 +1,4 @@ +#include <string.h> #include <stdio.h> #include <stdlib.h> @@ -19,7 +20,9 @@ read_file(const char *name) { FILE *f = fopen(name, "r"); length = fsize(f); - buf = malloc(length); + + buf = calloc(length+1, 1); + fread(buf, 1, length, f); return buf; diff --git a/http.c b/http.c @@ -25,7 +25,7 @@ respond(char *payload) { "%s"; length = snprintf(NULL, 0, format, strlen(payload), payload); - response = malloc(length); + response = calloc(length+1, 1); sprintf(response, format, strlen(payload), payload); diff --git a/main.c b/main.c @@ -20,13 +20,14 @@ main() { printf("%s", request); char *file_name = requested_file(request); + /* Get rid of the leading / in the file name e.g. /index.html */ + file_name++; /* If file is not found */ - if (strcmp(file_name, "/") == 0) { - buf = read_file("index.html"); - } else { - file_name++; + if (access(file_name, F_OK) == 0) { buf = read_file(file_name); + } else { + buf = read_file("index.html"); } char *text = respond(buf); @@ -34,6 +35,7 @@ main() { free(request); free(buf); + free(file_name); free(text); } } diff --git a/tcp.c b/tcp.c @@ -67,11 +67,8 @@ read_socket(int sock) { char *buf, *buf2; ssize_t read_size, cur_size = 0; - buf = malloc(BUF_SIZE); - buf2 = malloc(BUF_SIZE); - - memset(buf, 0, BUF_SIZE); - memset(buf2, 0, BUF_SIZE); + buf = calloc(BUF_SIZE, 1); + buf2 = calloc(BUF_SIZE, 1); /* Keep reading until done */ do { @@ -82,5 +79,7 @@ read_socket(int sock) { strcat(buf, buf2); } while (read_size == BUF_SIZE); + free(buf2); + return buf; }