From bc8568f926d84b712033577d4325b73983179ff4 Mon Sep 17 00:00:00 2001 From: Francesco Date: Mon, 1 Dec 2025 22:47:16 +0100 Subject: [PATCH] style: add comments --- include/core/server.h | 17 +++++++++------- include/core/worker.h | 7 ++++++- include/utils/debug.h | 6 ++---- src/core/server.c | 42 +++++++++++++++++++++++----------------- src/core/worker.c | 45 ++++++++++++++++++++++++------------------- src/http/mime.c | 5 ++--- src/utils/error.c | 27 +++++++++++++------------- 7 files changed, 82 insertions(+), 67 deletions(-) diff --git a/include/core/server.h b/include/core/server.h index e917c48..8d26e35 100644 --- a/include/core/server.h +++ b/include/core/server.h @@ -9,26 +9,29 @@ #include "core/worker.h" #include "utils/error.h" -/* Clients max queue */ +/* Maximum queue of pending client connections */ #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 +/* Blocking timeout for epoll_wait in ms */ #define CWS_SERVER_EPOLL_TIMEOUT 3000 +/* Maximum allowed HTTP request size */ #define CWS_SERVER_MAX_REQUEST_SIZE (16 * 1024) /* 16KB */ +/* Number of worker threads */ #define CWS_WORKERS_NUM 6 -/* Main server loop */ +/* Global flag used to stop server */ extern volatile sig_atomic_t cws_server_run; typedef struct cws_server { - int epfd; - int sockfd; - cws_worker_s **workers; - cws_config_s *config; + int epfd; /* epoll instance for incoming connections */ + int sockfd; /* listening socket */ + cws_worker_s **workers; /* worker thread pool */ + cws_config_s *config; /* config pointer */ } cws_server_s; cws_return cws_server_setup(cws_server_s *server, cws_config_s *config); diff --git a/include/core/worker.h b/include/core/worker.h index 29aa82e..805c465 100644 --- a/include/core/worker.h +++ b/include/core/worker.h @@ -7,11 +7,16 @@ #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; typedef struct cws_worker { int epfd; - size_t clients_num; pthread_t thread; cws_config_s *config; } cws_worker_s; diff --git a/include/utils/debug.h b/include/utils/debug.h index 2fd8ddf..3a28809 100644 --- a/include/utils/debug.h +++ b/include/utils/debug.h @@ -22,14 +22,12 @@ #endif #ifdef EVELOPER -#define CWS_LOG_DEBUG(msg, ...) \ - fprintf(stdout, _DEBUG " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__) +#define CWS_LOG_DEBUG(msg, ...) fprintf(stdout, _DEBUG " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__) #else #define CWS_LOG_DEBUG(msg, ...) #endif -#define CWS_LOG_ERROR(msg, ...) \ - fprintf(stderr, _ERR " [%s:%d] " msg "\n", __FILE__, __LINE__, ##__VA_ARGS__) +#define CWS_LOG_ERROR(msg, ...) 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_INFO(msg, ...) fprintf(stdout, _INFO " " msg "\n", ##__VA_ARGS__) diff --git a/src/core/server.c b/src/core/server.c index 96afc32..2f5f870 100644 --- a/src/core/server.c +++ b/src/core/server.c @@ -12,29 +12,27 @@ #include "utils/net.h" #include +/* Prepare addrinfo hints for getaddrinfo() */ static void cws_server_setup_hints(struct addrinfo *hints, const char *hostname) { memset(hints, 0, sizeof *hints); - /* IPv4 or IPv6 */ - hints->ai_family = AF_UNSPEC; - - /* TCP */ - hints->ai_socktype = SOCK_STREAM; + hints->ai_family = AF_UNSPEC; /* Accept IPv4 or IPv6 */ + hints->ai_socktype = SOCK_STREAM; /* TCP socket */ if (hostname == NULL) { - /* Fill in IP for me */ - hints->ai_flags = AI_PASSIVE; + hints->ai_flags = AI_PASSIVE; /* Bind to all interfaces */ } } +/* Create epoll, set listening socket nonblocking, and register it */ static cws_return cws_server_setup_epoll(int server_fd, int *epfd_out) { int epfd = epoll_create1(0); if (epfd < 0) { return epfd; } - cws_return ret; - ret = cws_fd_set_nonblocking(server_fd); + /* Listening socket must be nonblocking for epoll-driven accept loop */ + cws_return ret = cws_fd_set_nonblocking(server_fd); if (ret != CWS_OK) { return ret; } @@ -45,6 +43,7 @@ static cws_return cws_server_setup_epoll(int server_fd, int *epfd_out) { return CWS_OK; } +/* Initialize listening socket, epoll instance, and worker threads */ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) { if (!config || !config->hostname || !config->port) { 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); - /* Setup basic stuff */ + /* Resolve hostname/port */ struct addrinfo hints; struct addrinfo *res; - cws_server_setup_hints(&hints, config->hostname); 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; } + /* Create listening socket */ server->sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (server->sockfd < 0) { CWS_LOG_ERROR("socket(): %s", strerror(errno)); return CWS_SOCKET_ERROR; } + /* Allow fast reuse of the port on restart */ const int opt = 1; status = setsockopt(server->sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt); if (status != 0) { @@ -77,6 +77,7 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) { return CWS_SETSOCKOPT_ERROR; } + /* Bind + listen on the configured address */ status = bind(server->sockfd, res->ai_addr, res->ai_addrlen); if (status != 0) { 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); - /* Setup epoll */ + /* Setup epoll for accepting new clients */ cws_return ret = cws_server_setup_epoll(server->sockfd, &server->epfd); if (ret != CWS_OK) { return ret; } - /* Setup workers */ + /* Spawn worker threads */ server->workers = cws_worker_new(CWS_WORKERS_NUM, config); if (server->workers == NULL) { return CWS_WORKER_ERROR; @@ -106,32 +107,33 @@ cws_return cws_server_setup(cws_server_s *server, cws_config_s *config) { return CWS_OK; } +/* Main event loop: accept clients and distribute them among workers */ cws_return cws_server_start(cws_server_s *server) { struct epoll_event events[128]; memset(events, 0, sizeof events); - int client_fd = 0; + size_t workers_index = 0; while (cws_server_run) { int nfds = epoll_wait(server->epfd, events, 128, -1); - /* epoll error */ + /* Epoll error */ if (nfds < 0) { continue; } - /* No events */ if (nfds == 0) { continue; } 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) { continue; } - /* Add client to a worker */ + /* Assign client to next worker using round-robin */ cws_fd_set_nonblocking(client_fd); cws_epoll_add(server->workers[workers_index]->epfd, client_fd); workers_index = (workers_index + 1) % CWS_WORKERS_NUM; @@ -141,6 +143,7 @@ cws_return cws_server_start(cws_server_s *server) { return CWS_OK; } +/* Accept client + log IP */ int cws_server_handle_new_client(int server_fd) { struct sockaddr_storage their_sa; char ip[INET_ADDRSTRLEN]; @@ -156,8 +159,10 @@ int cws_server_handle_new_client(int server_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) { socklen_t theirsa_size = sizeof(struct sockaddr_storage); + const int client_fd = accept(server_fd, (struct sockaddr *)their_sa, &theirsa_size); if (client_fd == -1) { @@ -169,6 +174,7 @@ int cws_server_accept_client(int server_fd, struct sockaddr_storage *their_sa) { return client_fd; } +/* Close sockets, epoll, and workers */ void cws_server_shutdown(cws_server_s *server) { if (!server) { return; diff --git a/src/core/worker.c b/src/core/worker.c index 2066f9e..9e92df7 100644 --- a/src/core/worker.c +++ b/src/core/worker.c @@ -11,31 +11,37 @@ #include "http/response.h" #include "utils/error.h" +/* Create epoll instance for a worker */ static cws_return worker_setup_epoll(cws_worker_s *worker) { worker->epfd = epoll_create1(0); if (worker->epfd == -1) { return CWS_EPOLL_CREATE_ERROR; } - return CWS_OK; } +/* Remove client from epoll and close socket */ static void worker_close_client(int epfd, int client_fd) { cws_epoll_del(epfd, 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) { ssize_t total_bytes = cws_read_data(client_fd, data); + 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; } if (total_bytes < 0) { - /* Something happened, close connection */ + /* Client closed or read error */ worker_close_client(epfd, client_fd); - 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) { string_s *data = string_new("", 4096); + cws_return ret = worker_read_data(epfd, client_fd, data); if (ret != CWS_OK) { string_free(data); return ret; } + /* Parse full HTTP request */ cws_request_s *request = cws_http_parse(data); string_free(data); if (request == NULL) { worker_close_client(epfd, client_fd); return CWS_HTTP_PARSE_ERROR; } + request->sockfd = client_fd; + /* TODO: do not send HTTP_OK */ cws_http_send_response(request, HTTP_OK); cws_http_free(request); @@ -66,25 +76,20 @@ static cws_return worker_handle_client_data(int epfd, int client_fd) { return CWS_OK; } +/* Worker thread: process events on its epoll instance */ static void *cws_worker_loop(void *arg) { cws_worker_s *worker = arg; struct epoll_event events[64]; - int nfds; - 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) { - continue; - } - - if (nfds == 0) { + if (nfds <= 0) { continue; } for (int i = 0; i < nfds; ++i) { - /* Handle client's data */ int client_fd = events[i].data.fd; worker_handle_client_data(worker->epfd, client_fd); } @@ -93,20 +98,20 @@ static void *cws_worker_loop(void *arg) { 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 **workers = malloc(workers_num * sizeof *workers); - if (workers == NULL) { + if (!workers) { return NULL; } memset(workers, 0, workers_num * sizeof *workers); for (size_t i = 0; i < workers_num; ++i) { workers[i] = malloc(sizeof(cws_worker_s)); - if (workers[i] == NULL) { + if (!workers[i]) { for (size_t j = 0; j < i; ++j) { free(workers[j]); } - free(workers); return NULL; } @@ -114,18 +119,17 @@ cws_worker_s **cws_worker_new(size_t workers_num, cws_config_s *config) { workers[i]->config = config; - /* Setup worker's epoll */ - int ret = worker_setup_epoll(workers[i]); - if (ret == -1) { + /* Create per-worker epoll instance */ + if (worker_setup_epoll(workers[i]) != CWS_OK) { for (size_t j = 0; j < i; ++j) { free(workers[j]); } - free(workers); return NULL; } } + /* Start worker threads */ for (size_t i = 0; i < workers_num; ++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; } +/* Join threads and free worker memory */ void cws_worker_free(cws_worker_s **workers, size_t workers_num) { if (!workers) { return; diff --git a/src/http/mime.c b/src/http/mime.c index bc52201..6c323aa 100644 --- a/src/http/mime.c +++ b/src/http/mime.c @@ -5,9 +5,8 @@ #include "http/request.h" -static mimetype mimetypes[] = { - {"html", "text/html"}, {"css", "text/css"}, {"js", "application/javascript"}, - {"jpg", "image/jpeg"}, {"png", "image/png"}, {"ico", "image/x-icon"}}; +static mimetype mimetypes[] = {{"html", "text/html"}, {"css", "text/css"}, {"js", "application/javascript"}, + {"jpg", "image/jpeg"}, {"png", "image/png"}, {"ico", "image/x-icon"}}; int http_get_content_type(const char *location_path, char *content_type) { /* Find last occurrence of a string */ diff --git a/src/utils/error.c b/src/utils/error.c index ac4a80a..09693cc 100644 --- a/src/utils/error.c +++ b/src/utils/error.c @@ -2,20 +2,19 @@ #include -static const cws_error_s errors[] = { - {CWS_OK, "No error"}, - {CWS_FD_NONBLOCKING_ERROR, "Failed to set socket as non-blocking"}, - {CWS_EPOLL_CREATE_ERROR, "Failed to create epoll instance"}, - {CWS_CLIENT_DISCONNECTED_ERROR, "Client disconnected"}, - {CWS_HTTP_PARSE_ERROR, "Failed to parse HTTP request"}, - {CWS_CONFIG_ERROR, "Invalid server configuration"}, - {CWS_GETADDRINFO_ERROR, "getaddrinfo() failed"}, - {CWS_SOCKET_ERROR, "Failed to create socket"}, - {CWS_SETSOCKOPT_ERROR, "setsockopt() failed"}, - {CWS_BIND_ERROR, "bind() failed"}, - {CWS_LISTEN_ERROR, "listen() failed"}, - {CWS_WORKER_ERROR, "Worker thread initialization failed"}, - {CWS_UNKNOWN_ERROR, "Unknown error"}}; +static const cws_error_s errors[] = {{CWS_OK, "No error"}, + {CWS_FD_NONBLOCKING_ERROR, "Failed to set socket as non-blocking"}, + {CWS_EPOLL_CREATE_ERROR, "Failed to create epoll instance"}, + {CWS_CLIENT_DISCONNECTED_ERROR, "Client disconnected"}, + {CWS_HTTP_PARSE_ERROR, "Failed to parse HTTP request"}, + {CWS_CONFIG_ERROR, "Invalid server configuration"}, + {CWS_GETADDRINFO_ERROR, "getaddrinfo() failed"}, + {CWS_SOCKET_ERROR, "Failed to create socket"}, + {CWS_SETSOCKOPT_ERROR, "setsockopt() failed"}, + {CWS_BIND_ERROR, "bind() failed"}, + {CWS_LISTEN_ERROR, "listen() failed"}, + {CWS_WORKER_ERROR, "Worker thread initialization failed"}, + {CWS_UNKNOWN_ERROR, "Unknown error"}}; const char *cws_error_str(cws_return code) { for (size_t i = 0; i < ARR_SIZE(errors); ++i) {