Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1· openaiHugging Face Frontier Reasoning Traces

Develop a multi-threaded file server in C with epoll-based I/O.

  1. User

    Develop a multi-threaded file server in C with epoll-based I/O.

  2. Assistant

    Considering concurrency in threads

    I’m thinking through how concurrency works here: the main thread reads the request, builds the path, and enqueues the job, while a worker thread takes care of opening and reading the file into a buffer. Then, I'd need to notify the main thread to adjust the epoll interest for EPOLLOUT. Since threads are sharing the epoll file descriptor, synchronizing modifications is crucial. I'll have to protect the connection structure while ensuring efficiency in handling tasks with worker threads.Planning connection I/O handling

    I’m focusing on how the main thread will manage the connection's I/O through its event loop. When EPOLLOUT is ready, I’ll write from the connection's buffer and then either reset for reading or close if done. I'll need to handle errors properly as well. For the protocol, I'll parse simple "GET filename\n" requests and accept newline-delimited paths treated as relative to the root directory.

    The typical server steps will include setting up sockets, creating an epoll instance, and handling incoming connection events. I’ll choose level-triggered mode for simplicity.Designing job handling logic

    I’m considering how to efficiently manage reading without needing to loop until EAGAIN. For clarity, I want to keep things simple while ensuring correctness. Even though using level-triggered epoll simplifies logic and avoids indefinite loops, it's essential to implement a thread pool too. I'll set up a global job queue with mutex and condition variables.

    My job structure will contain connection pointers and file paths. The main thread will enqueue jobs after parsing the read buffer for a newline. When a worker wakes up, it will handle the job, open the file, and manage errors as needed.Handling job and connection states

    I’m pondering whether to use mmap or read for file operations, and how to manage memory for job connections. I'll need to acquire the job's connection pointer and allocate memory for the header and file content. However, there's a risk that the connection could close during job processing, so I'll mark the connection state as CLOSED to avoid unsafe pointer referencing.

    We could add a "closed" flag and reference counting, but that complicates things. For educational purposes, maybe I’ll implement it simpler by assuming clients properly wait. If the main thread detects an error on a connection with an ongoing job, I should mark the state as CLOSING without freeing it yet. That does add some complexity too, though.Structuring a multi-threaded file server

    Considering this is for educational purposes, I plan to simplify how we handle mid-job disconnects in the code. The user wants a multi-threaded file server in C using epoll-based I/O, which is essential for clear architecture, even if robust safety isn’t required.

    The initial code could stay concise, maybe around 300-400 lines. I’ll structure it so the server connects, sends a filename, and then just closes the connection post-transfer, minimizing complexity. Each job will access a mutex to avoid race conditions, and I’ll incorporate a global epoll file descriptor for consistent access. Overall, I aim for a clear yet manageable design that addresses basic concurrency without going overboard on complexity.Managing client disconnects in a file server

    If a client disconnects before the job completes, it's critical to handle that correctly. I consider adding a closed flag and a reference counter. When enqueuing a job, the counter increments, and the worker decrements it when finished. The main thread won't free resources if the counter is greater than zero, allowing workers to finish.

    Since this is an educational example, I think it’s acceptable to simplify and not handle all edge cases. I’ll assume that clients behave, and I can include disclaimers about not addressing mid-request disconnects. The goal is to maintain clarity while preserving essential functionality without excessive complexity.Structuring a multi-threaded file server

    I'm designing a pseudo skeleton for a multi-threaded file server in C. The connection struct conn_t includes essential elements like file descriptors, locks, and buffers. I also have a job struct to queue tasks properly.

    In managing job processing, I plan synchronized functions—particularly in handle_write, where I need to ensure I unlock the mutex before closing the connection to avoid race conditions. The locking protocol must permit safe access and modifications during connection closures, emphasizing a refcount system to track references. This helps prevent premature freeing of connections while ensuring orderly resource management.Handling epoll events safely

    I'm considering how to manage epoll events and connection closures properly. I need to ensure that once we close a connection, we don't inadvertently deliver stale events referencing that connection. Since epoll_ctl(DEL) or close(fd) will prevent further events from being delivered, most existing events should be safe to handle before freeing any associated pointers.

    Still, I need to track connection states to avoid race conditions, particularly when jobs are still processing. Using a "want_close" flag could help to defer actual closure until workers finish their tasks. However, managing this adds complexity. For simplicity, I think it might be best to handle only one job at a time and ignore any early disconnects during processing.Managing connection states and closures

    I need to ensure that close_conn isn't called when the connection is in the PROCESSING state, indicating that a job is active. Instead, close_conn can only occur during the RECV or SEND states. If a worker fails while building a response, we still set an error response but transition through SEND eventually.

    We'll keep the logic simple: ignore EPOLLHUP or ERROR states during PROCESSING or SEND, and only handle them when in RECV. This helps us avoid closing connections prematurely while ensuring memory management is safe.Designing connection handling

    I need to ensure that the pointer for the worker remains valid throughout its lifecycle, particularly during the SEND state when EPOLLHUP might occur. The goal is to prevent use-after-free (UAF) issues by keeping the connection open until after the send operation is complete.

    For protocol design, I'm adopting a simple GET <filename>\n structure, while sanitizing file paths to avoid traversal vulnerabilities. I can implement response handling for success and errors, encapsulating this in a minimal, self-contained server code example. Now, let's start constructing the functional skeleton for server.c.Defining connection handling

    I'm setting up the listening socket event with epoll, ensuring to track listen_fd globally while keeping the pointer valid throughout. The close_conn function should manage epoll_ctl properly, avoiding unnecessary deletions for listening sockets.

    Next, I'm designing a thread pool for handling jobs, where workers will dequeue tasks and process them. In handle_read, I'll manage the connection state and only lock where necessary, aiming for simplicity by allowing the main thread to handle the RECV state without locks during read operations, while ensuring synchronization when switching to the PROCESSING state.Finalizing concurrency handling

    I'm clarifying how the worker sets the connection state to SEND after processing, and from that point, the main thread takes over for sending and closing operations. I realize that we don't need individual locks for each connection since there's no concurrent usage, but I need to protect the state changes. Using stdatomic.h for atomic operations might be ideal, but I think we can manage with a pthread_mutex_t lock for reading and writing states.

    In handle_read, I plan to lock before checks and unlock after operations, while ensuring that the worker can still process jobs without holding the lock during heavy I/O operations. The close connection function will also make use of this locking mechanism to maintain the needed structure without risking state conflicts.Designing connection handling

    First, when I accept a connection, I allocate memory for the connection struct and set its initial state to CONN_RECV. I use EPOLLIN for event notifications and associate the event with the connection.

    For handle_read, I ensure that the connection is in the correct state before reading data. If reading fails, I handle errors appropriately by closing the connection if necessary. I also manage file path limitations and security checks.

    In process_job, I open the requested file, handle potential errors, prepare a response, and update the connection state appropriately before switching to EPOLLOUT.

    When handling writes with handle_write, I take care to manage the connection's state, ensuring I don't call close operations multiple times. I also define clear connection states to maintain the integrity of operations across different stages. This way, I can effectively manage the connection lifecycle without running into issues like double-frees or invalid pointers.Implementing connection management

    I'm focusing on the close_conn function, which handles cleanup by removing the connection from epoll, closing the file descriptor, freeing memory, and destroying the mutex. I need to ensure that the connection pointer isn’t used afterwards, specifically since the worker may run after main has called close.

    Next, I've designed the event loop where I handle incoming events from epoll, checking the connection state properly for errors. During accept_new_connections, I ensure the listening socket is non-blocking to prevent it from blocking the process.

    In the process_job, I add error handling for large file sizes, setting a limit for safety, so the server doesn't deal with overly large files. Overall, I'm being careful with error management and ensuring the application operates smoothly. Below is a minimal, working example of a multi‑threaded file server in C that uses:

    • epoll for scalable, non‑blocking network I/O (single event loop thread),
    • a worker thread pool for file I/O and response preparation.

    Simple protocol (per connection):

    1. Client connects.
    2. Client sends a single line containing a relative filename, terminated by \n.
      • e.g. foo.txt\n
    3. Server responds with either:
      • OK <size>\n<file-bytes> on success, or
      • ERR <message>\n on error.
    4. Connection is then closed.

    Each request is served from a given root directory.


    server.c

    #define _GNU_SOURCE
    #include <arpa/inet.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <limits.h>
    #include <netinet/in.h>
    #include <pthread.h>
    #include <signal.h>
    #include <stddef.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/epoll.h>
    #include <sys/socket.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    #ifndef PATH_MAX
    #define PATH_MAX 4096
    #endif
    
    #define MAX_EVENTS     64
    #define READ_BUF_SIZE  4096
    #define MAX_PATH_LEN   512
    #define MAX_FILE_SIZE  (100 * 1024 * 1024)   /* 100 MB max for demo */
    #define DEFAULT_THREADS 4
    
    /* Connection state */
    typedef enum {
        CONN_RECV = 0,      /* Waiting for filename line */
        CONN_PROCESSING,    /* Job queued / being processed by worker */
        CONN_SEND           /* Response ready, sending */
    } conn_state_t;
    
    typedef struct conn {
        int fd;
        conn_state_t state;
    
        char  read_buf[READ_BUF_SIZE];
        size_t read_len;
    
        char  *write_buf;
        size_t write_len;
        size_t write_pos;
    
        pthread_mutex_t lock;
    } conn_t;
    
    /* Job for workers */
    typedef struct job {
        conn_t *conn;
        char filename[MAX_PATH_LEN];
        struct job *next;
    } job_t;
    
    /* Globals */
    static int g_epoll_fd  = -1;
    static int g_listen_fd = -1;
    static const char *g_root_dir = ".";
    static int g_num_threads = DEFAULT_THREADS;
    
    /* Job queue */
    static job_t *g_job_head = NULL;
    static job_t *g_job_tail = NULL;
    static pthread_mutex_t g_job_mutex = PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t  g_job_cond  = PTHREAD_COND_INITIALIZER;
    
    /* Utility */
    
    static void die(const char *msg)
    {
        perror(msg);
        exit(EXIT_FAILURE);
    }
    
    static int set_nonblocking(int fd)
    {
        int flags = fcntl(fd, F_GETFL, 0);
        if (flags == -1)
            return -1;
        if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
            return -1;
        return 0;
    }
    
    /* Connection management */
    
    static void close_conn(conn_t *c)
    {
        if (!c)
            return;
    
        epoll_ctl(g_epoll_fd, EPOLL_CTL_DEL, c->fd, NULL); /* ignore errors */
        close(c->fd);
    
        if (c->write_buf)
            free(c->write_buf);
    
        pthread_mutex_destroy(&c->lock);
        free(c);
    }
    
    static conn_t *conn_create(int fd)
    {
        conn_t *c = calloc(1, sizeof(conn_t));
        if (!c)
            return NULL;
    
        c->fd = fd;
        c->state = CONN_RECV;
        c->read_len = 0;
        c->write_buf = NULL;
        c->write_len = 0;
        c->write_pos = 0;
    
        if (pthread_mutex_init(&c->lock, NULL) != 0) {
            free(c);
            return NULL;
        }
        return c;
    }
    
    /* Job queue */
    
    static void enqueue_job(conn_t *c, const char *filename)
    {
        job_t *job = malloc(sizeof(job_t));
        if (!job) {
            /* In a real server, you'd send an error back instead */
            fprintf(stderr, "Out of memory in enqueue_job\n");
            close_conn(c);
            return;
        }
        job->conn = c;
        strncpy(job->filename, filename, MAX_PATH_LEN - 1);
        job->filename[MAX_PATH_LEN - 1] = '\0';
        job->next = NULL;
    
        pthread_mutex_lock(&g_job_mutex);
        if (g_job_tail)
            g_job_tail->next = job;
        else
            g_job_head = job;
        g_job_tail = job;
        pthread_cond_signal(&g_job_cond);
        pthread_mutex_unlock(&g_job_mutex);
    }
    
    static job_t *dequeue_job(void)
    {
        pthread_mutex_lock(&g_job_mutex);
        while (g_job_head == NULL) {
            pthread_cond_wait(&g_job_cond, &g_job_mutex);
        }
        job_t *job = g_job_head;
        g_job_head = job->next;
        if (!g_job_head)
            g_job_tail = NULL;
        pthread_mutex_unlock(&g_job_mutex);
        return job;
    }
    
    /* Worker thread: file I/O and response building */
    
    static void build_error_response(conn_t *c, const char *msg)
    {
        size_t len = strlen(msg);
        char *buf = malloc(len + 5); /* "ERR " + msg + '\n' */
        if (!buf) {
            /* Fatal for this connection */
            close_conn(c);
            return;
        }
        int n = snprintf(buf, len + 5, "ERR %s\n", msg);
        if (n < 0) {
            free(buf);
            close_conn(c);
            return;
        }
    
        pthread_mutex_lock(&c->lock);
        if (c->state != CONN_PROCESSING) {
            pthread_mutex_unlock(&c->lock);
            free(buf);
            return;
        }
        c->write_buf = buf;
        c->write_len = (size_t)n;
        c->write_pos = 0;
        c->state = CONN_SEND;
        pthread_mutex_unlock(&c->lock);
    
        struct epoll_event ev;
        ev.events = EPOLLOUT;
        ev.data.ptr = c;
        if (epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, c->fd, &ev) == -1) {
            perror("epoll_ctl MOD (error response)");
            close_conn(c);
        }
    }
    
    static void *worker_main(void *arg)
    {
        (void)arg;
        for (;;) {
            job_t *job = dequeue_job();
            conn_t *c = job->conn;
    
            /* Build full path */
            char fullpath[PATH_MAX];
            int n = snprintf(fullpath, sizeof(fullpath),
                             "%s/%s", g_root_dir, job->filename);
            if (n <= 0 || n >= (int)sizeof(fullpath)) {
                build_error_response(c, "path too long");
                free(job);
                continue;
            }
    
            /* Basic security: disallow ".." in path */
            if (strstr(job->filename, "..")) {
                build_error_response(c, "invalid path");
                free(job);
                continue;
            }
    
            int fd = open(fullpath, O_RDONLY);
            if (fd < 0) {
                build_error_response(c, "cannot open file");
                free(job);
                continue;
            }
    
            struct stat st;
            if (fstat(fd, &st) < 0) {
                close(fd);
                build_error_response(c, "stat failed");
                free(job);
                continue;
            }
    
            if (!S_ISREG(st.st_mode) || st.st_size < 0) {
                close(fd);
                build_error_response(c, "not a regular file");
                free(job);
                continue;
            }
    
            if ((off_t)st.st_size > (off_t)MAX_FILE_SIZE) {
                close(fd);
                build_error_response(c, "file too large");
                free(job);
                continue;
            }
    
            off_t fsize = st.st_size;
            char header[64];
            int hlen = snprintf(header, sizeof(header),
                                "OK %lld\n", (long long)fsize);
            if (hlen <= 0 || hlen >= (int)sizeof(header)) {
                close(fd);
                build_error_response(c, "header error");
                free(job);
                continue;
            }
    
            size_t total_len = (size_t)hlen + (size_t)fsize;
            char *buf = malloc(total_len);
            if (!buf) {
                close(fd);
                build_error_response(c, "out of memory");
                free(job);
                continue;
            }
    
            memcpy(buf, header, (size_t)hlen);
    
            size_t offset = (size_t)hlen;
            while (offset < total_len) {
                ssize_t r = read(fd, buf + offset, total_len - offset);
                if (r < 0) {
                    if (errno == EINTR)
                        continue;
                    /* Read error: send a generic error instead */
                    free(buf);
                    close(fd);
                    build_error_response(c, "read error");
                    goto job_done;
                } else if (r == 0) {
                    /* EOF before expected size; shrink length */
                    total_len = offset;
                    break;
                } else {
                    offset += (size_t)r;
                }
            }
    
            close(fd);
    
            /* Install response into connection and switch to SEND state */
            pthread_mutex_lock(&c->lock);
            if (c->state != CONN_PROCESSING) {
                pthread_mutex_unlock(&c->lock);
                free(buf);
                goto job_done;
            }
            c->write_buf = buf;
            c->write_len = total_len;
            c->write_pos = 0;
            c->state = CONN_SEND;
            pthread_mutex_unlock(&c->lock);
    
            struct epoll_event ev;
            ev.events = EPOLLOUT;
            ev.data.ptr = c;
            if (epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, c->fd, &ev) == -1) {
                perror("epoll_ctl MOD (OK response)");
                close_conn(c);
            }
    
    job_done:
            free(job);
        }
        return NULL;
    }
    
    /* I/O handlers (main / epoll thread) */
    
    static void handle_read(conn_t *c)
    {
        pthread_mutex_lock(&c->lock);
        if (c->state != CONN_RECV) {
            pthread_mutex_unlock(&c->lock);
            return;
        }
    
        ssize_t n = read(c->fd,
                         c->read_buf + c->read_len,
                         sizeof(c->read_buf) - 1 - c->read_len);
        if (n <= 0) {
            if (n == 0 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
                pthread_mutex_unlock(&c->lock);
                close_conn(c);
                return;
            }
            pthread_mutex_unlock(&c->lock);
            return;
        }
    
        c->read_len += (size_t)n;
        c->read_buf[c->read_len] = '\0';
    
        /* Look for a newline: one-line request "filename\n" */
        char *nl = memchr(c->read_buf, '\n', c->read_len);
        if (!nl) {
            /* Not complete yet */
            pthread_mutex_unlock(&c->lock);
            return;
        }
    
        size_t line_len = (size_t)(nl - c->read_buf);
        if (line_len > 0 && c->read_buf[line_len - 1] == '\r')
            line_len--;
    
        if (line_len == 0 || line_len >= MAX_PATH_LEN) {
            pthread_mutex_unlock(&c->lock);
            close_conn(c);
            return;
        }
    
        char filename[MAX_PATH_LEN];
        memcpy(filename, c->read_buf, line_len);
        filename[line_len] = '\0';
    
        /* Only one request per connection, we ignore any extra data */
        c->state = CONN_PROCESSING;
        pthread_mutex_unlock(&c->lock);
    
        enqueue_job(c, filename);
    }
    
    static void handle_write(conn_t *c)
    {
        pthread_mutex_lock(&c->lock);
        if (c->state != CONN_SEND) {
            pthread_mutex_unlock(&c->lock);
            return;
        }
    
        while (c->write_pos < c->write_len) {
            ssize_t n = write(c->fd,
                              c->write_buf + c->write_pos,
                              c->write_len - c->write_pos);
            if (n > 0) {
                c->write_pos += (size_t)n;
            } else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
                /* Can't write more now */
                pthread_mutex_unlock(&c->lock);
                return;
            } else {
                /* Error or peer closed */
                pthread_mutex_unlock(&c->lock);
                close_conn(c);
                return;
            }
        }
    
        pthread_mutex_unlock(&c->lock);
        /* All data written: close connection */
        close_conn(c);
    }
    
    /* Accept new clients */
    
    static void accept_new_connections(void)
    {
        for (;;) {
            struct sockaddr_in cliaddr;
            socklen_t clilen = sizeof(cliaddr);
            int cfd = accept(g_listen_fd, (struct sockaddr *)&cliaddr, &clilen);
            if (cfd < 0) {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                    break;  /* All pending connections processed */
                perror("accept");
                break;
            }
    
            if (set_nonblocking(cfd) == -1) {
                perror("set_nonblocking (client)");
                close(cfd);
                continue;
            }
    
            conn_t *c = conn_create(cfd);
            if (!c) {
                fprintf(stderr, "Failed to create connection object\n");
                close(cfd);
                continue;
            }
    
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.ptr = c;
            if (epoll_ctl(g_epoll_fd, EPOLL_CTL_ADD, cfd, &ev) == -1) {
                perror("epoll_ctl ADD (client)");
                close_conn(c);
                continue;
            }
        }
    }
    
    /* Main */
    
    int main(int argc, char *argv[])
    {
        if (argc < 3) {
            fprintf(stderr,
                    "Usage: %s <port> <root-dir> [threads]\n"
                    "Example: %s 8080 ./files 4\n",
                    argv[0], argv[0]);
            return EXIT_FAILURE;
        }
    
        int port = atoi(argv[1]);
        if (port <= 0 || port > 65535) {
            fprintf(stderr, "Invalid port: %s\n", argv[1]);
            return EXIT_FAILURE;
        }
    
        g_root_dir = argv[2];
        if (argc >= 4) {
            g_num_threads = atoi(argv[3]);
            if (g_num_threads <= 0)
                g_num_threads = DEFAULT_THREADS;
        }
    
        /* Ignore SIGPIPE so writes to closed sockets don't kill the process */
        signal(SIGPIPE, SIG_IGN);
    
        /* Create listening socket */
        g_listen_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (g_listen_fd < 0)
            die("socket");
    
        int opt = 1;
        if (setsockopt(g_listen_fd, SOL_SOCKET, SO_REUSEADDR,
                       &opt, sizeof(opt)) == -1) {
            die("setsockopt");
        }
    
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family      = AF_INET;
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        addr.sin_port        = htons((uint16_t)port);
    
        if (bind(g_listen_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
            die("bind");
    
        if (listen(g_listen_fd, SOMAXCONN) < 0)
            die("listen");
    
        if (set_nonblocking(g_listen_fd) == -1)
            die("set_nonblocking (listen)");
    
        /* Create epoll instance */
        g_epoll_fd = epoll_create1(0);
        if (g_epoll_fd == -1)
            die("epoll_create1");
    
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.ptr = NULL;          /* NULL marks the listening socket */
        if (epoll_ctl(g_epoll_fd, EPOLL_CTL_ADD, g_listen_fd, &ev) == -1)
            die("epoll_ctl ADD (listen)");
    
        /* Start worker threads */
        pthread_t *threads = calloc((size_t)g_num_threads, sizeof(pthread_t));
        if (!threads)
            die("calloc threads");
    
        for (int i = 0; i < g_num_threads; ++i) {
            if (pthread_create(&threads[i], NULL, worker_main, NULL) != 0)
                die("pthread_create");
            pthread_detach(threads[i]); /* server never joins */
        }
    
        printf("Server listening on port %d, root dir '%s', threads %d\n",
               port, g_root_dir, g_num_threads);
    
        /* Event loop */
        struct epoll_event events[MAX_EVENTS];
    
        for (;;) {
            int n = epoll_wait(g_epoll_fd, events, MAX_EVENTS, -1);
            if (n < 0) {
                if (errno == EINTR)
                    continue;
                die("epoll_wait");
            }
    
            for (int i = 0; i < n; ++i) {
                if (events[i].data.ptr == NULL) {
                    /* Event on listening socket */
                    accept_new_connections();
                } else {
                    conn_t *c = (conn_t *)events[i].data.ptr;
                    uint32_t e = events[i].events;
    
                    if (e & (EPOLLERR | EPOLLHUP)) {
                        /*
                         * If we haven't queued a job yet, just close.
                         * If a job is in progress (PROCESSING) or sending,
                         * we'll close later after send/write fails.
                         */
                        pthread_mutex_lock(&c->lock);
                        conn_state_t st = c->state;
                        pthread_mutex_unlock(&c->lock);
                        if (st == CONN_RECV) {
                            close_conn(c);
                            continue;
                        }
                    }
    
                    if (e & EPOLLIN)
                        handle_read(c);
                    if (e & EPOLLOUT)
                        handle_write(c);
                }
            }
        }
    
        return 0;
    }
    

    Build and run

    gcc -Wall -O2 -pthread server.c -o file_server
    
    # Create directory with some files
    mkdir -p files
    echo "Hello world" > files/hello.txt
    
    # Run server (port 8080, root dir ./files, 4 worker threads)
    ./file_server 8080 files 4
    

    Test with nc (netcat)

    # In another terminal:
    printf "hello.txt\n" | nc 127.0.0.1 8080
    
    # Expected output:
    OK 12
    Hello world
    

    Notes / limitations

    • Designed for Linux (uses epoll).
    • Very simple text protocol, one request per connection.
    • Reads entire file into memory before sending; limits file size (100 MB).
    • Error handling and concurrency are simplified for clarity; not production‑ready.
    • Path sanitization is minimal (.. disallowed); you may want stricter checks.

    If you want, I can extend this to basic HTTP (GET /path) handling or show a matching client implementation.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.