92 lines
2.0 KiB
C
92 lines
2.0 KiB
C
#include "http_content_type.h"
|
|
#include "http_response.h"
|
|
#include "http_status.h"
|
|
#include <stddef.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <unistd.h>
|
|
|
|
bool construct_response(HttpResponse __res, char *out) {
|
|
unsigned long length;
|
|
if ((length = strlen(__res.body)) > __res.content_length) {
|
|
fprintf(stderr, "[ERROR] %s: %lu > %lu",
|
|
"The size of the body is greater than what was set in "
|
|
"content_length.",
|
|
length, __res.content_length);
|
|
return false;
|
|
}
|
|
|
|
char status_message[256];
|
|
http_status_message(__res.status_code, status_message, 256);
|
|
char content_type[256];
|
|
http_content_type(__res.content_type, content_type, 256);
|
|
sprintf(
|
|
out,
|
|
"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %lu\r\n\r\n%s",
|
|
__res.status_code, status_message, content_type, __res.content_length,
|
|
__res.body);
|
|
|
|
return true;
|
|
}
|
|
|
|
void http_respond(HttpResponse __res, int clientfd) {
|
|
char response[BUFSIZ];
|
|
// TODO: Handle return
|
|
construct_response(__res, response);
|
|
|
|
send(clientfd, response, strlen(response), 0);
|
|
}
|
|
|
|
char *read_file(const char *__path) {
|
|
if (access(__path, F_OK) != 0) {
|
|
return NULL;
|
|
}
|
|
|
|
FILE *f = fopen(__path, "r");
|
|
if (f == NULL) {
|
|
return NULL;
|
|
}
|
|
fseek(f, 0, SEEK_END);
|
|
size_t length = ftell(f);
|
|
rewind(f);
|
|
|
|
char *content = malloc(length * sizeof(char));
|
|
|
|
if (content == NULL) {
|
|
fclose(f);
|
|
return NULL;
|
|
}
|
|
|
|
size_t bytesRead = fread(content, sizeof(char), length, f);
|
|
content[bytesRead] = 0;
|
|
|
|
fclose(f);
|
|
|
|
return content;
|
|
}
|
|
|
|
HttpResponse *from_file(const char *__path) {
|
|
char *content = read_file(__path);
|
|
if (content == NULL)
|
|
return NULL;
|
|
|
|
HttpResponse response = {.status_code = HTTP_OK,
|
|
.content_length = strlen(content),
|
|
.content_type = HTTP_CT_HTML,
|
|
.body = content};
|
|
|
|
HttpResponse *res = malloc(sizeof(response));
|
|
*res = response;
|
|
|
|
return res;
|
|
}
|
|
|
|
void free_response(HttpResponse *__res) {
|
|
if (__res->body != NULL)
|
|
free(__res->body);
|
|
|
|
free(__res);
|
|
}
|