If file non existant crashing resolved

This commit is contained in:
cdricms
2024-11-15 10:56:07 +01:00
parent 9ccde76edc
commit ce2edb6293
8 changed files with 209 additions and 74 deletions

View File

@@ -1,5 +1,5 @@
#include "http_content_type.h"
#include "http_response.h"
#include "http_content_type.h"
#include "http_status.h"
#include <stddef.h>
#include <stdio.h>
@@ -31,15 +31,18 @@ bool construct_response(HttpResponse __res, char *out) {
return true;
}
void http_respond(HttpResponse __res, int clientfd) {
void http_respond(HttpResponse *__res, int clientfd) {
if (__res == NULL)
return;
char response[BUFSIZ];
// TODO: Handle return
construct_response(__res, response);
construct_response(*__res, response);
send(clientfd, response, strlen(response), 0);
}
char *read_file(const char *__path) {
// If the file does not exist
if (access(__path, F_OK) != 0) {
return NULL;
}
@@ -48,10 +51,12 @@ char *read_file(const char *__path) {
if (f == NULL) {
return NULL;
}
// Get the length of the file
fseek(f, 0, SEEK_END);
size_t length = ftell(f);
rewind(f);
// Initialize a value to get the content
char *content = malloc(length * sizeof(char));
if (content == NULL) {
@@ -59,6 +64,7 @@ char *read_file(const char *__path) {
return NULL;
}
// Read the file into content and set the last char to \0
size_t bytesRead = fread(content, sizeof(char), length, f);
content[bytesRead] = 0;
@@ -72,10 +78,13 @@ HttpResponse *from_file(const char *__path) {
if (content == NULL)
return NULL;
HttpResponse response = {.status_code = HTTP_OK,
.content_length = strlen(content),
.content_type = HTTP_CT_HTML,
.body = content};
HttpResponse response = {
.status_code = HTTP_OK,
.content_length = strlen(content),
.content_type = HTTP_CT_HTML,
.body = content,
.body_in_heap = true,
};
HttpResponse *res = malloc(sizeof(response));
*res = response;
@@ -84,7 +93,7 @@ HttpResponse *from_file(const char *__path) {
}
void free_response(HttpResponse *__res) {
if (__res->body != NULL)
if (__res->body != NULL && __res->body_in_heap)
free(__res->body);
free(__res);