commit ddd169f21945431c412328580b48ed40eb9cfa09
parent 4bba916e0f4a54d98a3947df7e2d0714d92a8bab
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sun, 12 Jul 2026 18:22:42 +0000
parent 4bba916e0f4a54d98a3947df7e2d0714d92a8bab
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sun, 12 Jul 2026 18:22:42 +0000
Segregated network functionality into separate file Add server_fcgi.c for fcgi functionality using kcgi
6 files changed, 433 insertions(+), 256 deletions(-)
diff --git a/.gitignore b/.gitignore @@ -1,5 +1,6 @@ # ignore binaries -/fiche +fiche +fiche.fcgi # ignore default outpit dir code/
diff --git a/Makefile b/Makefile @@ -1,9 +1,16 @@ # for debug add -g -O0 to line below CFLAGS+=-pthread -O2 -Wall -Wextra -Wpedantic -Wstrict-overflow -fno-strict-aliasing -std=gnu11 -g -O0 prefix=/usr/local/bin +fiche.fcgi_CFLAGS = $(shell pkgconf --cflags kcgi) +fiche.fcgi_LDFLAGS = $(shell pkgconf --libs kcgi) -all: - ${CC} main.c fiche.c $(CFLAGS) -o fiche +fiche: + ${CC} main.c fiche.c server_raw.c $(CFLAGS) -o fiche + +fiche.fcgi: + ${CC} main.c fiche.c server_fcgi.c $(fiche.fcgi_LDFLAGS) $(fiche.fcgi_CFLAGS) -o fiche.fcgi + +all: fiche fiche.fcgi install: fiche install -m 0755 fiche $(prefix)
diff --git a/fiche.c b/fiche.c @@ -26,8 +26,6 @@ $ cat fiche.c | nc localhost 9999 ------------------------------------------------------------------------------- */ -#include "fiche.h" - #include <stdio.h> #include <stdarg.h> #include <stdlib.h> @@ -36,37 +34,19 @@ $ cat fiche.c | nc localhost 9999 #include <pwd.h> #include <time.h> #include <unistd.h> -#include <pthread.h> #include <fcntl.h> -#include <netdb.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/types.h> -#include <arpa/inet.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <netinet/in.h> +#include "fiche.h" /****************************************************************************** * Various declarations */ const char *Fiche_Symbols = "abcdefghijklmnopqrstuvwxyz0123456789"; - -/****************************************************************************** - * Inner structs - */ - -struct fiche_connection { - int socket; - struct sockaddr_in address; - - Fiche_Settings *settings; -}; - - /****************************************************************************** * Static function declarations */ @@ -91,23 +71,20 @@ static int perform_user_change(const Fiche_Settings *settings); /** * @brief Starts server with settings provided in Fiche_Settings struct */ -static int start_server(Fiche_Settings *settings); +int start_server(Fiche_Settings *settings); -/** - * @brief Dispatches incoming connections by spawning threads - */ -static void dispatch_connection(int socket, Fiche_Settings *settings); +ssize_t server_write(struct fiche_connection* _c, char* url, size_t len); +void server_cleanup(struct fiche_connection *); /** * @brief Handles connections * @remarks Is being run by dispatch_connection in separate threads * @arg args Struct fiche_connection containing connection details */ -static void *handle_connection(void *args); +void *handle_connection(void *args); // Server-related utils - /** * @brief Generates a slug that will be used for paste creation * @warning output has to be freed after using! @@ -143,41 +120,12 @@ static int create_directory(char *output_dir, char *slug); */ static int save_to_file(const Fiche_Settings *s, uint8_t *data, char *slug); - -// Logging-related - -/** - * @brief Displays error messages - */ -static void print_error(const char *format, ...); - - -/** - * @brief Displays status messages - */ -static void print_status(const char *format, ...); - - -/** - * @brief Displays horizontal line - */ -static void print_separator(); - - -/** - * @brief Saves connection entry to the logfile - */ -static void log_entry(const Fiche_Settings *s, const char *ip, - const char *hostname, const char *slug); - - /** * @brief Returns string containing current date * @warning Output has to be freed! */ static void get_date(char *buf); - /** * @brief Time seed */ @@ -285,12 +233,11 @@ int fiche_run(Fiche_Settings settings) { } - /****************************************************************************** * Static functions below */ -static void print_error(const char *format, ...) { +void print_error(const char *format, ...) { va_list args; va_start(args, format); @@ -301,8 +248,20 @@ static void print_error(const char *format, ...) { va_end(args); } +void print_status_with_date(const char *format, ...) { + va_list args; + va_start(args, format); + char date[64]; + get_date(date); -static void print_status(const char *format, ...) { + printf("[Fiche][STATUS] %s", date); + vprintf(format, args); + printf("\n"); + + va_end(args); +} + +void print_status(const char *format, ...) { va_list args; va_start(args, format); @@ -314,12 +273,12 @@ static void print_status(const char *format, ...) { } -static void print_separator() { +void print_separator() { printf("============================================================\n"); } -static void log_entry(const Fiche_Settings *s, const char *ip, +void log_entry(const Fiche_Settings *s, const char *ip, const char *hostname, const char *slug) { // Logging to file not enabled, finish here @@ -426,168 +385,8 @@ static int perform_user_change(const Fiche_Settings *settings) { } -static int start_server(Fiche_Settings *settings) { - - // Perform socket creation - int s = socket(AF_INET, SOCK_STREAM, 0); - if (s < 0) { - print_error("Couldn't create a socket!"); - return -1; - } - - // Set socket settings - if ( setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 } , sizeof(int)) != 0 ) { - print_error("Couldn't prepare the socket!"); - return -1; - } - - // Prepare address and port handler - struct sockaddr_in address; - address.sin_family = AF_INET; - address.sin_addr.s_addr = inet_addr(settings->listen_addr); - address.sin_port = htons(settings->port); - - // Bind to port - if ( bind(s, (struct sockaddr *) &address, sizeof(address)) != 0) { - print_error("Couldn't bind to the port: %d!", settings->port); - return -1; - } - - // Start listening - if ( listen(s, 128) != 0 ) { - print_error("Couldn't start listening on the socket!"); - return -1; - } - - print_status("Server started listening on: %s:%d.", - settings->listen_addr, settings->port); - print_separator(); - - // Run dispatching loop - while (1) { - dispatch_connection(s, settings); - } - - // Give some time for all threads to finish - // NOTE: this code is reached only in testing environment - // There is currently no way to kill the main thread from any thread - // Something like this can be done for testing purpouses: - // int i = 0; - // while (i < 3) { - // dispatch_connection(s, settings); - // i++; - // } - - sleep(5); - - return 0; -} - - -static void dispatch_connection(int socket, Fiche_Settings *settings) { - - // Create address structs for this socket - struct sockaddr_in address; - socklen_t addlen = sizeof(address); - - // Accept a connection and get a new socket id - const int s = accept(socket, (struct sockaddr *) &address, &addlen); - if (s < 0 ) { - print_error("Error on accepting connection!"); - return; - } - - // Set timeout for accepted socket - const struct timeval timeout = { 5, 0 }; - - if ( setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0 ) { - print_error("Couldn't set a timeout!"); - } - - if ( setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) != 0 ) { - print_error("Couldn't set a timeout!"); - } - - // Create an argument for the thread function - struct fiche_connection *c = malloc(sizeof(*c)); - if (!c) { - print_error("Couldn't allocate memory!"); - return; - } - c->socket = s; - c->address = address; - c->settings = settings; - - // Spawn a new thread to handle this connection - pthread_t id; - - if ( pthread_create(&id, NULL, &handle_connection, c) != 0 ) { - print_error("Couldn't spawn a thread!"); - return; - } - - // Detach thread if created succesfully - // TODO: consider using pthread_tryjoin_np - pthread_detach(id); - -} - - -static void *handle_connection(void *args) { - - // Cast args to it's previous type - struct fiche_connection *c = (struct fiche_connection *) args; - - // Get client's IP - const char *ip = inet_ntoa(c->address.sin_addr); - - // Get client's hostname - char hostname[1024]; - - if (getnameinfo((struct sockaddr *)&c->address, sizeof(c->address), - hostname, sizeof(hostname), NULL, 0, 0) != 0 ) { - - // Couldn't resolve a hostname - strcpy(hostname, "n/a"); - } - - // Print status on this connection - { - char date[64]; - get_date(date); - print_status("%s", date); - - print_status("Incoming connection from: %s (%s).", ip, hostname); - } - - // Create a buffer - uint8_t buffer[c->settings->buffer_len]; - memset(buffer, 0, c->settings->buffer_len); - - const int r = recv(c->socket, buffer, sizeof(buffer), MSG_WAITALL); - if (r <= 0) { - print_error("No data received from the client!"); - print_separator(); - - // Close the socket - close(c->socket); - - // Cleanup - free(c); - pthread_exit(NULL); - - return 0; - } - - // - Check if request was performed with a known protocol - // TODO - - // - Check if on whitelist - // TODO - - // - Check if on banlist - // TODO +void post_handle_connection(struct fiche_connection* c) { // Generate slug and use it to create an url char *slug; uint8_t extra = 0; @@ -613,12 +412,7 @@ static void *handle_connection(void *args) { print_error("Couldn't generate a valid slug!"); print_separator(); - // Cleanup - free(c); - free(slug); - close(c->socket); - pthread_exit(NULL); - return NULL; + goto post_handle_connection_final; } } @@ -630,27 +424,17 @@ static void *handle_connection(void *args) { print_error("Couldn't generate a slug!"); print_separator(); - close(c->socket); - - // Cleanup - free(c); - pthread_exit(NULL); - return NULL; + server_cleanup(c); + return; } // Save to file failed, we have to finish here - if ( save_to_file(c->settings, buffer, slug) != 0 ) { + if ( save_to_file(c->settings, c->buffer, slug) != 0 ) { print_error("Couldn't save a file!"); print_separator(); - close(c->socket); - - // Cleanup - free(c); - free(slug); - pthread_exit(NULL); - return NULL; + goto post_handle_connection_final; } // Write a response to the user @@ -662,26 +446,22 @@ static void *handle_connection(void *args) { snprintf(url, len, "%s%s%s%s", c->settings->domain, "/", slug, "\n"); // Send the response - write(c->socket, url, len); + server_write(c, url, len); } - print_status("Received %d bytes, saved to: %s.", r, slug); + print_status("Received %d bytes, saved to: %s.", c->rx_len, slug); print_separator(); // Log connection // TODO: log unsuccessful and rejected connections - log_entry(c->settings, ip, hostname, slug); + log_entry(c->settings, c->ip, c->hostname, slug); - // Close the connection - close(c->socket); +post_handle_connection_final: // Perform cleanup of values used in this thread free(slug); - free(c); - - pthread_exit(NULL); - - return NULL; + server_cleanup(c); + return; }
diff --git a/fiche.h b/fiche.h @@ -25,6 +25,7 @@ $ cat fiche.c | nc localhost 9999 #include <stdint.h> #include <stdbool.h> +#include <stddef.h> /** @@ -94,6 +95,45 @@ typedef struct Fiche_Settings { } Fiche_Settings; +struct fiche_connection { + char *hostname; + char *ip; + uint8_t* buffer; + size_t buffer_len; + size_t rx_len; + Fiche_Settings *settings; +}; + +// Logging-related + +/** + * @brief Displays error messages + */ +void print_error(const char *format, ...); + +/** + * @brief Displays status messages with date + */ +void print_status_with_date(const char *format, ...); + +/** + * @brief Displays status messages + */ +void print_status(const char *format, ...); + + +/** + * @brief Displays horizontal line + */ +void print_separator(); + + +/** + * @brief Saves connection entry to the logfile + */ +void log_entry(const Fiche_Settings *s, const char *ip, + const char *hostname, const char *slug); + /** * @brief Initializes Fiche_Settings instance @@ -115,5 +155,7 @@ int fiche_run(Fiche_Settings settings); */ extern const char *Fiche_Symbols; +void post_handle_connection(struct fiche_connection* c); + #endif
diff --git a/server_fcgi.c b/server_fcgi.c @@ -0,0 +1,148 @@ +#include <stddef.h> +#include <stdint.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> + +#include <sys/types.h> + +#include <kcgi.h> + +#include "fiche.h" + +struct fiche_connection_fcgi { + struct fiche_connection base; + struct kreq *request; + struct kfcgi *fcgi; + char *post_data; + size_t post_len; + char *authenticated_user; +}; + +static int fcgi_read_data(struct fiche_connection *c) { + struct fiche_connection_fcgi *fcgi = (struct fiche_connection_fcgi *)c; + struct kreq *r = fcgi->request; + + if (!r) return -1; + + + // Only handle POST requests + if (r->method != KMETHOD_POST) { + return -1; + } + + if (!(r->fieldsz && r->fields[0].valsz)) { + return -1; + // FIXME show error log + } + + // Allocate buffer + uint8_t* str = (uint8_t *) r->fields[0].val; + size_t str_len = r->fields[0].valsz; + // Zero-copy + c->buffer = str; + c->rx_len = str_len; + // Hallucinated + // Store authenticated user if available + // fcgi->authenticated_user = strdup(khttp_auth(fcgi->request)); + + return 0; +} + +// FCGI-specific write implementation +ssize_t server_write(struct fiche_connection *c, const char *data, size_t len) { + struct fiche_connection_fcgi *fcgi = (struct fiche_connection_fcgi *)c; + struct kreq *req = fcgi->request; + + // Send HTTP headers + khttp_head(req, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]); + khttp_head(req, kresps[KRESP_CONTENT_TYPE], "%s", "text/plain"); + khttp_body(req); + + // Send data + return khttp_write(req, data, len); +} + +// FCGI-specific close implementation +void server_cleanup(struct fiche_connection *c) { + struct fiche_connection_fcgi *fcgi = (struct fiche_connection_fcgi *)c; + + if (fcgi->request) { + khttp_free(fcgi->request); + fcgi->request = NULL; + } + + if (c->buffer) { + free(c->buffer); + c->buffer = NULL; + } + + if (fcgi->authenticated_user) { + free(fcgi->authenticated_user); + fcgi->authenticated_user = NULL; + } +} + +// Create an FCGI connection +static struct fiche_connection_fcgi* +create_fcgi_connection( + struct kreq *req, + struct kfcgi *fcgi, + Fiche_Settings *settings) { + + struct fiche_connection_fcgi *fcgi_conn = malloc(sizeof(*fcgi_conn)); + if (!fcgi_conn) return NULL; + + // Initialize base struct + fcgi_conn->base.buffer = NULL; + fcgi_conn->base.buffer_len = 0; + fcgi_conn->base.rx_len = 0; + fcgi_conn->base.settings = settings; + + // Initialize FCGI-specific fields + fcgi_conn->request = req; + fcgi_conn->fcgi = fcgi; + fcgi_conn->post_data = NULL; + fcgi_conn->post_len = 0; + fcgi_conn->authenticated_user = NULL; + + return fcgi_conn; +} + +int start_server(Fiche_Settings *settings) { + struct kreq r; + struct kfcgi *fcgi; + enum kcgi_err er; + + if (khttp_fcgi_init(&fcgi, NULL, 0, NULL, 0, 0) != KCGI_OK) { + fprintf(stderr, "Failed to initialize kcgi\n"); + return -1; + } + + printf("fiche FCGI server started\n"); + + for (;;) { + /* Set up the current HTTP context. */ + er = khttp_fcgi_parse(fcgi, &r); + if (er == KCGI_EXIT) + fprintf(stderr, "khttp_fcgi_parse: terminate\n"); + else if (er != KCGI_OK) + fprintf(stderr, "khttp_fcgi_parse: error: %d\n", er); + if (er != KCGI_OK) + break; + // Create FCGI connection with proper inheritance + struct fiche_connection_fcgi *fcgi_conn + = create_fcgi_connection(&r, fcgi, settings); + if (!fcgi_conn) { + khttp_free(&r); + continue; + } + + post_handle_connection((struct fiche_connection *)fcgi_conn); + + // Note: process_connection frees the connection + } + + khttp_fcgi_free(fcgi); + return 0; +}
diff --git a/server_raw.c b/server_raw.c @@ -0,0 +1,199 @@ +#include <stdlib.h> +#include <pthread.h> +#include <string.h> + +#include <unistd.h> + +#include <netdb.h> +#include <arpa/inet.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/in.h> + +#include "fiche.h" + + +static void *handle_connection(void *args); + +/** + * @brief Dispatches incoming connections by spawning threads + */ +static void dispatch_connection(int socket, Fiche_Settings *settings); + +struct fiche_connection_raw { + struct fiche_connection base; + int socket; + struct sockaddr_in address; + +}; + +int start_server(Fiche_Settings *settings) { + + // Perform socket creation + int s = socket(AF_INET, SOCK_STREAM, 0); + if (s < 0) { + print_error("Couldn't create a socket!"); + return -1; + } + + // Set socket settings + if ( setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 } , sizeof(int)) != 0 ) { + print_error("Couldn't prepare the socket!"); + return -1; + } + + // Prepare address and port handler + struct sockaddr_in address; + address.sin_family = AF_INET; + address.sin_addr.s_addr = inet_addr(settings->listen_addr); + address.sin_port = htons(settings->port); + + // Bind to port + if ( bind(s, (struct sockaddr *) &address, sizeof(address)) != 0) { + print_error("Couldn't bind to the port: %d!", settings->port); + return -1; + } + + // Start listening + if ( listen(s, 128) != 0 ) { + print_error("Couldn't start listening on the socket!"); + return -1; + } + + print_status("Server started listening on: %s:%d.", + settings->listen_addr, settings->port); + print_separator(); + + // Run dispatching loop + while (1) { + dispatch_connection(s, settings); + } + + // Give some time for all threads to finish + // NOTE: this code is reached only in testing environment + // There is currently no way to kill the main thread from any thread + // Something like this can be done for testing purpouses: + // int i = 0; + // while (i < 3) { + // dispatch_connection(s, settings); + // i++; + // } + + sleep(5); + + return 0; + +} + +static void dispatch_connection(int socket, Fiche_Settings *settings) { + + // Create address structs for this socket + struct sockaddr_in address; + socklen_t addlen = sizeof(address); + + // Accept a connection and get a new socket id + const int s = accept(socket, (struct sockaddr *) &address, &addlen); + if (s < 0 ) { + print_error("Error on accepting connection!"); + return; + } + + // Set timeout for accepted socket + const struct timeval timeout = { 5, 0 }; + + if ( setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0 ) { + print_error("Couldn't set a timeout!"); + } + + if ( setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) != 0 ) { + print_error("Couldn't set a timeout!"); + } + + // Create an argument for the thread function + struct fiche_connection_raw *c = malloc(sizeof(*c)); + if (!c) { + print_error("Couldn't allocate memory!"); + return; + } + c->socket = s; + c->address = address; + c->base.settings = settings; + + // Spawn a new thread to handle this connection + pthread_t id; + + if ( pthread_create(&id, NULL, &handle_connection, c) != 0 ) { + print_error("Couldn't spawn a thread!"); + return; + } + + // Detach thread if created succesfully + // TODO: consider using pthread_tryjoin_np + pthread_detach(id); + +} + +static void *handle_connection(void *args) { + + // Cast args to it's previous type + struct fiche_connection_raw *c = (struct fiche_connection_raw *) args; + + // Get client's IP + const char *ip = inet_ntoa(c->address.sin_addr); + + // Get client's hostname + char hostname[1024]; + + if (getnameinfo((struct sockaddr *)&c->address, sizeof(c->address), + hostname, sizeof(hostname), NULL, 0, 0) != 0 ) { + + // Couldn't resolve a hostname + strcpy(hostname, "n/a"); + } + + // Print status on this connection + print_status_with_date("Incoming connection from: %s (%s).", ip, hostname); + + // Create a buffer + c->base.buffer = (uint8_t *) malloc(c->base.settings->buffer_len); + memset(c->base.buffer, 0, c->base.settings->buffer_len); + + uint8_t *buffer = c->base.buffer; + c->base.rx_len = recv(c->socket, buffer, sizeof(buffer), MSG_WAITALL); + if (c->base.rx_len <= 0) { + print_error("No data received from the client!"); + print_separator(); + + // Close the socket + close(c->socket); + + // Cleanup + free(c); + pthread_exit(NULL); + return NULL; + } + + // - Check if request was performed with a known protocol + // TODO + + // - Check if on whitelist + // TODO + + // - Check if on banlist + // TODO + + post_handle_connection((struct fiche_connection *) c); + return NULL; +} + +void server_cleanup(struct fiche_connection* _c) { + struct fiche_connection_raw *c = (struct fiche_connection_raw *) _c; + close(c->socket); + free(c); + pthread_exit(NULL); +} + +ssize_t server_write(struct fiche_connection* _c, char* url, size_t len) { + struct fiche_connection_raw *c = (struct fiche_connection_raw *) _c; + return write(c->socket, url, len); +}
: nply/fiche2