projects

WebServ

A high-performance, non-blocking HTTP/1.1 server written from scratch in C98/C++, featuring a custom socket multiplexer and CGI executor.

RoleSystems Engineer
Client42 Project
Year2022
Technologies
C++Socket ProgrammingHTTP/1.1+3
WebServ cover

Overview

Lightweight HTTP web server from scratch using socket-based networking and manual HTTP parsing with CGI support.

The Challenge

Modern web servers like Nginx abstract away the immense complexity of the transport and application layers. The challenge here was to build a production-like server completely from scratch using raw POSIX system calls. This meant implementing non-blocking I/O multiplexing to handle thousands of concurrent connections on a single thread without race conditions, deadlocks, or dropping packets.

The Solution

C++ web server with socket-based networking, manual HTTP parsing, CGI/PHP execution support, and efficient static file serving.

Architecture & Topology

Core Implementation

// Handling non-blocking sockets in the event loop multiplexer
int flags = fcntl(client_fd, F_GETFL, 0);
if (fcntl(client_fd, F_SETFL, flags | O_NONBLOCK) == -1) {
    throw std::runtime_error("Failed to set non-blocking socket");
}
// State machine continues without blocking the main thread...

Technical Deep Dive

Event-Driven Multiplexing

Instead of an inefficient thread-per-connection model, the server relies on a highly optimized event loop using select(). Sockets are strictly set to non-blocking mode via fcntl(), ensuring the main event loop never blocks.

State Machine Parsing

Engineered a rigorous HTTP/1.1 parser capable of handling fragmented TCP packets. It gracefully manages chunked transfer encoding, multipart form data, and large file uploads by keeping state across asynchronous reads.

CGI Execution Engine

Built a robust Common Gateway Interface (CGI) to execute dynamic PHP/Python scripts. Required careful orchestration of fork(), execve(), and pipe() alongside proper waitpid handling to prevent zombie processes.

Custom Configuration Language

Designed a lexer and parser for an Nginx-style configuration file, allowing dynamic definition of server blocks, virtual hosts, ports, root directories, and custom error pages.