style: add comments

This commit is contained in:
2025-12-01 22:47:16 +01:00
parent f08e17d8c8
commit bc8568f926
7 changed files with 82 additions and 67 deletions

View File

@@ -9,26 +9,29 @@
#include "core/worker.h" #include "core/worker.h"
#include "utils/error.h" #include "utils/error.h"
/* Clients max queue */ /* Maximum queue of pending client connections */
#define CWS_SERVER_BACKLOG 128 #define CWS_SERVER_BACKLOG 128
/* Size of the epoll_event array */ /* Max number of epoll events processed per iteration */
#define CWS_SERVER_EPOLL_MAXEVENTS 64 #define CWS_SERVER_EPOLL_MAXEVENTS 64
/* Blocking timeout for epoll_wait in ms */
#define CWS_SERVER_EPOLL_TIMEOUT 3000 #define CWS_SERVER_EPOLL_TIMEOUT 3000
/* Maximum allowed HTTP request size */
#define CWS_SERVER_MAX_REQUEST_SIZE (16 * 1024) /* 16KB */ #define CWS_SERVER_MAX_REQUEST_SIZE (16 * 1024) /* 16KB */
/* Number of worker threads */
#define CWS_WORKERS_NUM 6 #define CWS_WORKERS_NUM 6
/* Main server loop */ /* Global flag used to stop server */
extern volatile sig_atomic_t cws_server_run; extern volatile sig_atomic_t cws_server_run;
typedef struct cws_server { typedef struct cws_server {
int epfd; int epfd; /* epoll instance for incoming connections */
int sockfd; int sockfd; /* listening socket */
cws_worker_s **workers; cws_worker_s **workers; /* worker thread pool */
cws_config_s *config; cws_config_s *config; /* config pointer */
} cws_server_s; } cws_server_s;
cws_return cws_server_setup(cws_server_s *server, cws_config_s *config); cws_return cws_server_setup(cws_server_s *server, cws_config_s *config);

View File

@@ -7,11 +7,16 @@
#include "config/config.h" #include "config/config.h"
/* Blocking timeout for epoll_wait in ms */
#define WORKER_EPOLL_TIMEOUT 250
/* Max number of epoll events processed per iteration */
#define WORKER_EPOLL_MAX_EVENTS 64
extern volatile sig_atomic_t cws_server_run; extern volatile sig_atomic_t cws_server_run;
typedef struct cws_worker { typedef struct cws_worker {
int epfd; int epfd;
size_t clients_num;
pthread_t thread; pthread_t thread;
cws_config_s *config; cws_config_s *config;
} cws_worker_s; } cws_worker_s;

View File

@@ -22,14 +22,12 @@
#endif #endif
#ifdef EVELOPER #ifdef EVELOPER
#define CWS_LOG_DEBUG(msg, ...) \ #define CWS_LOG_DEBUG(msg, ...) fprintf(stdout, _DEBUG " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__)
fprintf(stdout, _DEBUG " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else #else
#define CWS_LOG_DEBUG(msg, ...) #define CWS_LOG_DEBUG(msg, ...)
#endif #endif
#define CWS_LOG_ERROR(msg, ...) \ #define CWS_LOG_ERROR(msg, ...) fprintf(stderr, _ERR " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__)
fprintf(stderr, _ERR " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#define CWS_LOG_WARNING(msg, ...) fprintf(stdout, _WARNING " " msg "\n", ##__VA_ARGS__) #define CWS_LOG_WARNING(msg, ...) fprintf(stdout, _WARNING " " msg "\n", ##__VA_ARGS__)
#define CWS_LOG_INFO(msg, ...) fprintf(stdout, _INFO " " msg "\n", ##__VA_ARGS__) #define CWS_LOG_INFO(msg, ...) fprintf(stdout, _INFO " " msg "\n", ##__VA_ARGS__)

View File

@@ -12,29 +12,27 @@
#include "utils/net.h" #include "utils/net.h"
#include <unistd.h> #include <unistd.h>
/* Prepare addrinfo hints for getaddrinfo() */
static void cws_server_setup_hints(struct addrinfo *hints, const char *hostname) { static void cws_server_setup_hints(struct addrinfo *hints, const char *hostname) {
memset(hints, 0, sizeof *hints); memset(hints, 0, sizeof *hints);
/* IPv4 or IPv6 */ hints->ai_family = AF_UNSPEC; /* Accept IPv4 or IPv6 */
hints->ai_family = AF_UNSPEC; hints->ai_socktype = SOCK_STREAM; /* TCP socket */
/* TCP */
hints->ai_socktype = SOCK_STREAM;
if (hostname == NULL) { if (hostname == NULL) {
/* Fill in IP for me */ hints->ai_flags = AI_PASSIVE; /* Bind to all interfaces */
hints->ai_flags = AI_PASSIVE;
} }
} }
/* Create epoll, set listening socket nonblocking, and register it */
static cws_return cws_server_setup_epoll(int server_fd, int *epfd_out) { static cws_return cws_server_setup_epoll(int server_fd, int *epfd_out) {
int epfd = epoll_create1(0); int epfd = epoll_create1(0);
if (epfd < 0) { if (epfd < 0) {
return epfd; return epfd;
} }
cws_return ret; /* Listening socket must be nonblocking for epoll-driven accept loop */
ret = cws_fd_set_nonblocking(server_fd); cws_return ret = cws_fd_set_nonblocking(server_fd);
if (ret != CWS_OK) { if (ret != CWS_OK) {
return ret; return ret;
} }
@@ -45,6 +43,7 @@ static cws_return cws_server_setup_epoll(int server_fd, int *epfd_out) {
return CWS_OK; return CWS_OK;
} }
/* Initialize listening socket, epoll instance, and worker threads */
cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) { cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) {
if (!config || !config->hostname || !config->port) { if (!config || !config->hostname || !config->port) {
return CWS_CONFIG_ERROR; return CWS_CONFIG_ERROR;
@@ -52,10 +51,9 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) {
memset(server, 0, sizeof *server); memset(server, 0, sizeof *server);
/* Setup basic stuff */ /* Resolve hostname/port */
struct addrinfo hints; struct addrinfo hints;
struct addrinfo *res; struct addrinfo *res;
cws_server_setup_hints(&hints, config->hostname); cws_server_setup_hints(&hints, config->hostname);
int status = getaddrinfo(config->hostname, config->port, &hints, &res); int status = getaddrinfo(config->hostname, config->port, &hints, &res);
@@ -64,12 +62,14 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) {
return CWS_GETADDRINFO_ERROR; return CWS_GETADDRINFO_ERROR;
} }
/* Create listening socket */
server->sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); server->sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (server->sockfd < 0) { if (server->sockfd < 0) {
CWS_LOG_ERROR("socket(): %s", strerror(errno)); CWS_LOG_ERROR("socket(): %s", strerror(errno));
return CWS_SOCKET_ERROR; return CWS_SOCKET_ERROR;
} }
/* Allow fast reuse of the port on restart */
const int opt = 1; const int opt = 1;
status = setsockopt(server->sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt); status = setsockopt(server->sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);
if (status != 0) { if (status != 0) {
@@ -77,6 +77,7 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) {
return CWS_SETSOCKOPT_ERROR; return CWS_SETSOCKOPT_ERROR;
} }
/* Bind + listen on the configured address */
status = bind(server->sockfd, res->ai_addr, res->ai_addrlen); status = bind(server->sockfd, res->ai_addr, res->ai_addrlen);
if (status != 0) { if (status != 0) {
CWS_LOG_ERROR("bind(): %s", strerror(errno)); CWS_LOG_ERROR("bind(): %s", strerror(errno));
@@ -91,13 +92,13 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) {
freeaddrinfo(res); freeaddrinfo(res);
/* Setup epoll */ /* Setup epoll for accepting new clients */
cws_return ret = cws_server_setup_epoll(server->sockfd, &server->epfd); cws_return ret = cws_server_setup_epoll(server->sockfd, &server->epfd);
if (ret != CWS_OK) { if (ret != CWS_OK) {
return ret; return ret;
} }
/* Setup workers */ /* Spawn worker threads */
server->workers = cws_worker_new(CWS_WORKERS_NUM, config); server->workers = cws_worker_new(CWS_WORKERS_NUM, config);
if (server->workers == NULL) { if (server->workers == NULL) {
return CWS_WORKER_ERROR; return CWS_WORKER_ERROR;
@@ -106,32 +107,33 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) {
return CWS_OK; return CWS_OK;
} }
/* Main event loop: accept clients and distribute them among workers */
cws_return cws_server_start(cws_server_s *server) { cws_return cws_server_start(cws_server_s *server) {
struct epoll_event events[128]; struct epoll_event events[128];
memset(events, 0, sizeof events); memset(events, 0, sizeof events);
int client_fd = 0;
size_t workers_index = 0; size_t workers_index = 0;
while (cws_server_run) { while (cws_server_run) {
int nfds = epoll_wait(server->epfd, events, 128, -1); int nfds = epoll_wait(server->epfd, events, 128, -1);
/* epoll error */ /* Epoll error */
if (nfds < 0) { if (nfds < 0) {
continue; continue;
} }
/* No events */
if (nfds == 0) { if (nfds == 0) {
continue; continue;
} }
for (int i = 0; i < nfds; ++i) { for (int i = 0; i < nfds; ++i) {
client_fd = cws_server_handle_new_client(server->sockfd); /* Accept incoming connection */
int client_fd = cws_server_handle_new_client(server->sockfd);
if (client_fd < 0) { if (client_fd < 0) {
continue; continue;
} }
/* Add client to a worker */ /* Assign client to next worker using round-robin */
cws_fd_set_nonblocking(client_fd); cws_fd_set_nonblocking(client_fd);
cws_epoll_add(server->workers[workers_index]->epfd, client_fd); cws_epoll_add(server->workers[workers_index]->epfd, client_fd);
workers_index = (workers_index + 1) % CWS_WORKERS_NUM; workers_index = (workers_index + 1) % CWS_WORKERS_NUM;
@@ -141,6 +143,7 @@ cws_return cws_server_start(cws_server_s *server) {
return CWS_OK; return CWS_OK;
} }
/* Accept client + log IP */
int cws_server_handle_new_client(int server_fd) { int cws_server_handle_new_client(int server_fd) {
struct sockaddr_storage their_sa; struct sockaddr_storage their_sa;
char ip[INET_ADDRSTRLEN]; char ip[INET_ADDRSTRLEN];
@@ -156,8 +159,10 @@ int cws_server_handle_new_client(int server_fd) {
return client_fd; return client_fd;
} }
/* Wrapper around accept() with logging and error handling */
int cws_server_accept_client(int server_fd, struct sockaddr_storage *their_sa) { int cws_server_accept_client(int server_fd, struct sockaddr_storage *their_sa) {
socklen_t theirsa_size = sizeof(struct sockaddr_storage); socklen_t theirsa_size = sizeof(struct sockaddr_storage);
const int client_fd = accept(server_fd, (struct sockaddr *)their_sa, &theirsa_size); const int client_fd = accept(server_fd, (struct sockaddr *)their_sa, &theirsa_size);
if (client_fd == -1) { if (client_fd == -1) {
@@ -169,6 +174,7 @@ int cws_server_accept_client(int server_fd, struct sockaddr_storage *their_sa) {
return client_fd; return client_fd;
} }
/* Close sockets, epoll, and workers */
void cws_server_shutdown(cws_server_s *server) { void cws_server_shutdown(cws_server_s *server) {
if (!server) { if (!server) {
return; return;

View File

@@ -11,31 +11,37 @@
#include "http/response.h" #include "http/response.h"
#include "utils/error.h" #include "utils/error.h"
/* Create epoll instance for a worker */
static cws_return worker_setup_epoll(cws_worker_s *worker) { static cws_return worker_setup_epoll(cws_worker_s *worker) {
worker->epfd = epoll_create1(0); worker->epfd = epoll_create1(0);
if (worker->epfd == -1) { if (worker->epfd == -1) {
return CWS_EPOLL_CREATE_ERROR; return CWS_EPOLL_CREATE_ERROR;
} }
return CWS_OK; return CWS_OK;
} }
/* Remove client from epoll and close socket */
static void worker_close_client(int epfd, int client_fd) { static void worker_close_client(int epfd, int client_fd) {
cws_epoll_del(epfd, client_fd); cws_epoll_del(epfd, client_fd);
close(client_fd); close(client_fd);
} }
/* Read client request data; 0 = incomplete, <0 = disconnect */
static cws_return worker_read_data(int epfd, int client_fd, string_s *data) { static cws_return worker_read_data(int epfd, int client_fd, string_s *data) {
ssize_t total_bytes = cws_read_data(client_fd, data); ssize_t total_bytes = cws_read_data(client_fd, data);
if (total_bytes == 0) { if (total_bytes == 0) {
/* Request not completed yet */ /* Partial request; wait for more data */
/*
* TODO: do not return CWS_OK
* instead free data and continue
*/
return CWS_OK; return CWS_OK;
} }
if (total_bytes < 0) { if (total_bytes < 0) {
/* Something happened, close connection */ /* Client closed or read error */
worker_close_client(epfd, client_fd); worker_close_client(epfd, client_fd);
return CWS_CLIENT_DISCONNECTED_ERROR; return CWS_CLIENT_DISCONNECTED_ERROR;
} }
@@ -44,20 +50,24 @@ static cws_return worker_read_data(int epfd, int client_fd, string_s *data) {
static cws_return worker_handle_client_data(int epfd, int client_fd) { static cws_return worker_handle_client_data(int epfd, int client_fd) {
string_s *data = string_new("", 4096); string_s *data = string_new("", 4096);
cws_return ret = worker_read_data(epfd, client_fd, data); cws_return ret = worker_read_data(epfd, client_fd, data);
if (ret != CWS_OK) { if (ret != CWS_OK) {
string_free(data); string_free(data);
return ret; return ret;
} }
/* Parse full HTTP request */
cws_request_s *request = cws_http_parse(data); cws_request_s *request = cws_http_parse(data);
string_free(data); string_free(data);
if (request == NULL) { if (request == NULL) {
worker_close_client(epfd, client_fd); worker_close_client(epfd, client_fd);
return CWS_HTTP_PARSE_ERROR; return CWS_HTTP_PARSE_ERROR;
} }
request->sockfd = client_fd; request->sockfd = client_fd;
/* TODO: do not send HTTP_OK */
cws_http_send_response(request, HTTP_OK); cws_http_send_response(request, HTTP_OK);
cws_http_free(request); cws_http_free(request);
@@ -66,25 +76,20 @@ static cws_return worker_handle_client_data(int epfd, int client_fd) {
return CWS_OK; return CWS_OK;
} }
/* Worker thread: process events on its epoll instance */
static void *cws_worker_loop(void *arg) { static void *cws_worker_loop(void *arg) {
cws_worker_s *worker = arg; cws_worker_s *worker = arg;
struct epoll_event events[64]; struct epoll_event events[64];
int nfds;
while (cws_server_run) { while (cws_server_run) {
nfds = epoll_wait(worker->epfd, events, 64, 250); /* 250 ms timeout allows periodic shutdown checking */
int nfds = epoll_wait(worker->epfd, events, WORKER_EPOLL_MAX_EVENTS, WORKER_EPOLL_TIMEOUT);
if (nfds < 0) { if (nfds <= 0) {
continue;
}
if (nfds == 0) {
continue; continue;
} }
for (int i = 0; i < nfds; ++i) { for (int i = 0; i < nfds; ++i) {
/* Handle client's data */
int client_fd = events[i].data.fd; int client_fd = events[i].data.fd;
worker_handle_client_data(worker->epfd, client_fd); worker_handle_client_data(worker->epfd, client_fd);
} }
@@ -93,20 +98,20 @@ static void *cws_worker_loop(void *arg) {
return NULL; return NULL;
} }
/* Allocate workers, create per-worker epoll, then spawn worker threads */
cws_worker_s **cws_worker_new(size_t workers_num, cws_config_s *config) { cws_worker_s **cws_worker_new(size_t workers_num, cws_config_s *config) {
cws_worker_s **workers = malloc(workers_num * sizeof *workers); cws_worker_s **workers = malloc(workers_num * sizeof *workers);
if (workers == NULL) { if (!workers) {
return NULL; return NULL;
} }
memset(workers, 0, workers_num * sizeof *workers); memset(workers, 0, workers_num * sizeof *workers);
for (size_t i = 0; i < workers_num; ++i) { for (size_t i = 0; i < workers_num; ++i) {
workers[i] = malloc(sizeof(cws_worker_s)); workers[i] = malloc(sizeof(cws_worker_s));
if (workers[i] == NULL) { if (!workers[i]) {
for (size_t j = 0; j < i; ++j) { for (size_t j = 0; j < i; ++j) {
free(workers[j]); free(workers[j]);
} }
free(workers); free(workers);
return NULL; return NULL;
} }
@@ -114,18 +119,17 @@ cws_worker_s **cws_worker_new(size_t workers_num, cws_config_s *config) {
workers[i]->config = config; workers[i]->config = config;
/* Setup worker's epoll */ /* Create per-worker epoll instance */
int ret = worker_setup_epoll(workers[i]); if (worker_setup_epoll(workers[i]) != CWS_OK) {
if (ret == -1) {
for (size_t j = 0; j < i; ++j) { for (size_t j = 0; j < i; ++j) {
free(workers[j]); free(workers[j]);
} }
free(workers); free(workers);
return NULL; return NULL;
} }
} }
/* Start worker threads */
for (size_t i = 0; i < workers_num; ++i) { for (size_t i = 0; i < workers_num; ++i) {
pthread_create(&workers[i]->thread, NULL, cws_worker_loop, workers[i]); pthread_create(&workers[i]->thread, NULL, cws_worker_loop, workers[i]);
} }
@@ -133,6 +137,7 @@ cws_worker_s **cws_worker_new(size_t workers_num, cws_config_s *config) {
return workers; return workers;
} }
/* Join threads and free worker memory */
void cws_worker_free(cws_worker_s **workers, size_t workers_num) { void cws_worker_free(cws_worker_s **workers, size_t workers_num) {
if (!workers) { if (!workers) {
return; return;

View File

@@ -5,9 +5,8 @@
#include "http/request.h" #include "http/request.h"
static mimetype mimetypes[] = { static mimetype mimetypes[] = {{"html", "text/html"}, {"css", "text/css"}, {"js", "application/javascript"},
{"html", "text/html"}, {"css", "text/css"}, {"js", "application/javascript"}, {"jpg", "image/jpeg"}, {"png", "image/png"}, {"ico", "image/x-icon"}};
{"jpg", "image/jpeg"}, {"png", "image/png"}, {"ico", "image/x-icon"}};
int http_get_content_type(const char *location_path, char *content_type) { int http_get_content_type(const char *location_path, char *content_type) {
/* Find last occurrence of a string */ /* Find last occurrence of a string */

View File

@@ -2,20 +2,19 @@
#include <stddef.h> #include <stddef.h>
static const cws_error_s errors[] = { static const cws_error_s errors[] = {{CWS_OK, "No error"},
{CWS_OK, "No error"}, {CWS_FD_NONBLOCKING_ERROR, "Failed to set socket as non-blocking"},
{CWS_FD_NONBLOCKING_ERROR, "Failed to set socket as non-blocking"}, {CWS_EPOLL_CREATE_ERROR, "Failed to create epoll instance"},
{CWS_EPOLL_CREATE_ERROR, "Failed to create epoll instance"}, {CWS_CLIENT_DISCONNECTED_ERROR, "Client disconnected"},
{CWS_CLIENT_DISCONNECTED_ERROR, "Client disconnected"}, {CWS_HTTP_PARSE_ERROR, "Failed to parse HTTP request"},
{CWS_HTTP_PARSE_ERROR, "Failed to parse HTTP request"}, {CWS_CONFIG_ERROR, "Invalid server configuration"},
{CWS_CONFIG_ERROR, "Invalid server configuration"}, {CWS_GETADDRINFO_ERROR, "getaddrinfo() failed"},
{CWS_GETADDRINFO_ERROR, "getaddrinfo() failed"}, {CWS_SOCKET_ERROR, "Failed to create socket"},
{CWS_SOCKET_ERROR, "Failed to create socket"}, {CWS_SETSOCKOPT_ERROR, "setsockopt() failed"},
{CWS_SETSOCKOPT_ERROR, "setsockopt() failed"}, {CWS_BIND_ERROR, "bind() failed"},
{CWS_BIND_ERROR, "bind() failed"}, {CWS_LISTEN_ERROR, "listen() failed"},
{CWS_LISTEN_ERROR, "listen() failed"}, {CWS_WORKER_ERROR, "Worker thread initialization failed"},
{CWS_WORKER_ERROR, "Worker thread initialization failed"}, {CWS_UNKNOWN_ERROR, "Unknown error"}};
{CWS_UNKNOWN_ERROR, "Unknown error"}};
const char *cws_error_str(cws_return code) { const char *cws_error_str(cws_return code) {
for (size_t i = 0; i < ARR_SIZE(errors); ++i) { for (size_t i = 0; i < ARR_SIZE(errors); ++i) {