If file non existant crashing resolved
This commit is contained in:
98
http/http_server.c
Normal file
98
http/http_server.c
Normal file
@@ -0,0 +1,98 @@
|
||||
#include "http_server.h"
|
||||
#include "http_content_type.h"
|
||||
#include "http_request.h"
|
||||
#include "http_response.h"
|
||||
#include "http_status.h"
|
||||
#include <asm-generic/socket.h>
|
||||
#include <malloc.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
HttpServerRunStatus http_server_setup(HttpServer *s) {
|
||||
int opt = 1;
|
||||
|
||||
if ((s->server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
|
||||
return HTTP_SRS_SOCKET_FAILED;
|
||||
|
||||
if (setsockopt(s->server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
|
||||
return HTTP_SRS_SETSOCKOPT_FAILED;
|
||||
|
||||
if (s->address == NULL) {
|
||||
printf("Setting server address\n");
|
||||
s->address = malloc(sizeof(*s->address));
|
||||
s->address->sin_family = AF_INET;
|
||||
s->address->sin_addr.s_addr = INADDR_ANY;
|
||||
s->address->sin_port = htons(s->port);
|
||||
}
|
||||
|
||||
if (bind(s->server_fd, (struct sockaddr *)s->address, sizeof(*s->address)) <
|
||||
0)
|
||||
return HTTP_SRS_BIND_FAILED;
|
||||
|
||||
if (listen(s->server_fd, s->workers) < 0)
|
||||
return HTTP_SRS_LISTEN_FAILED;
|
||||
|
||||
return HTTP_SRS_SETUP;
|
||||
}
|
||||
|
||||
HttpServerRunStatus http_server_run(HttpServer *s) {
|
||||
int client_fd;
|
||||
ssize_t valread;
|
||||
|
||||
socklen_t addrlen = sizeof(*s->address);
|
||||
|
||||
if ((client_fd =
|
||||
accept(s->server_fd, (struct sockaddr *)s->address, &addrlen)) < 0)
|
||||
return HTTP_SRS_ACCEPT_FAILED;
|
||||
|
||||
char request[BUFSIZ] = {0};
|
||||
|
||||
if ((valread = read(client_fd, request, 1024 - 1)) < 0)
|
||||
return HTTP_SRS_READ_FAILED;
|
||||
|
||||
HttpRequest *req = handle_request(request);
|
||||
if (req == NULL)
|
||||
return HTTP_SRS_HANDLE_REQUEST_FAILED;
|
||||
|
||||
HttpResponse *res;
|
||||
|
||||
if (!strcmp(req->path, "/")) {
|
||||
res = from_file("./" DEFAULT_HTML);
|
||||
} else {
|
||||
char path[] = ".";
|
||||
strcat(path, req->path);
|
||||
res = from_file(path);
|
||||
}
|
||||
// print_request(req);
|
||||
// free_request(req);
|
||||
if (res == NULL) {
|
||||
HttpResponse __res = {
|
||||
.status_code = HTTP_NOT_FOUND,
|
||||
.body = "",
|
||||
.content_type = HTTP_CT_PLAIN_TEXT,
|
||||
.content_length = 1,
|
||||
.body_in_heap = false,
|
||||
};
|
||||
res = malloc(sizeof(__res));
|
||||
*res = __res;
|
||||
}
|
||||
|
||||
http_respond(res, client_fd);
|
||||
free_response(res);
|
||||
close(client_fd);
|
||||
|
||||
return HTTP_SRS_RUNNING;
|
||||
}
|
||||
|
||||
HttpServerRunStatus http_server_stop(HttpServer *s) {
|
||||
|
||||
close(s->server_fd);
|
||||
|
||||
if (s->address != NULL)
|
||||
free(s->address);
|
||||
|
||||
return HTTP_SRS_STOPPED;
|
||||
}
|
||||
Reference in New Issue
Block a user