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

68
main.c
View File

@@ -1,73 +1,23 @@
#include "http/http_request.h"
#include "http/http_response.h"
#include "http/http_server.h"
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define DEFAULT_HTML "index.html"
int main() {
HttpServer server = {.port = 8080, .workers = 3};
if (http_server_setup(&server) != HTTP_SRS_SETUP)
exit(1);
const int PORT = 8080;
HttpServerRunStatus status;
int serverfd, clientfd;
ssize_t valread;
while ((status = http_server_run(&server)) == HTTP_SRS_RUNNING)
;
struct sockaddr_in address;
int opt = 1;
socklen_t addrlen = sizeof(address);
char request[BUFSIZ] = {0};
printf("Status: %d\n", status);
if ((serverfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(serverfd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(serverfd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((clientfd = accept(serverfd, (struct sockaddr *)&address, &addrlen)) <
0) {
perror("accept");
exit(EXIT_FAILURE);
}
valread = read(clientfd, request,
1024 - 1); // subtract 1 for the null
// terminator at the end
HttpRequest *req = handle_request(request);
HttpResponse *res;
if (!strcmp(req->path, "/")) {
res = from_file("./" DEFAULT_HTML);
} else {
char path[] = ".";
strcat(path, req->path);
res = from_file(path);
}
free(req);
http_respond(*res, clientfd);
free_response(res);
// closing the connected socket
close(clientfd);
// closing the listening socket
close(clientfd);
http_server_stop(&server);
return 0;
}