How yellow-camper/libevhtp works
Project Type and Purpose
• Libevhtp is a native C library that builds on top of the Libevent event loop to provide a lightweight, high-performance HTTP(S) server API.
• Its primary role is not a standalone application but as a reusable networking component: it accepts connections, parses HTTP requests, dispatches user-provided callbacks (handlers), and writes responses.
File Structure Analysis
• Top-level:
• core source files (evhtp.c, parser.c, thread.c, sslutils.c, log.c, numtoa.c)
• public headers under include/evhtp
• internal headers in include/ and compat/ for portability
• CMakeLists.txt, cmake/ and build/ for build configuration and packaging
• examples/ demonstrating usage patterns (basic server, chunked, vhost, HTTPS, threaded server, etc.)
• dist/, .travis.yml, .gitignore, LICENSE, README.md for project maintenance
• The modular directory layout indicates a separation between:
• Core engine (connection management & event loop integration)
• HTTP parsing
• Threading support
• SSL support (optional)
• Logging and utility functions
README Insights
• Lists dependencies: Libevent2, OpenSSL (optional), pthreads, oniguruma (regex).
• Describes build steps, supported platforms, and points to performance benchmarks.
a. Main Components
• External Clients (HTTP or HTTPS requesters)
• TCP/IP layer (OS sockets)
• Libevent Event Loop
• Libevhtp Core Module (connection lifecycle, request/response objects)
• HTTP Parser Submodule
• Thread Pool Submodule (optional pthreads dispatch)
• SSL/TLS Submodule (wrapping socket I/O via OpenSSL)
• Regex/Router Submodule (using oniguruma for URI matching, vhost)
• User-Defined Callbacks / Application Logic
• Logging / Refcount / Utilities
b. Relationships & Data Flow
1. Client → TCP Socket accept()
2. Socket registered with Libevent → socket event triggers
3. Libevent calls into Libevhtp Core → Core reads raw bytes
4. Raw bytes → HTTP Parser → parsed evhtp_request object
5. Router / Regex → Lookup matched callback (vhost, regex route)
6. Dispatch to Thread Pool OR direct event-loop thread (configurable)
7. User Callback processes request → constructs evhtp_headers, body
8. evhtp constructs HTTP response → writes to socket buffer
9. Libevent monitors socket WRITE events → sends bytes back to client
10. Optional SSL/TLS wrapper: stepping in at read/write phases
c. Architectural Patterns & Principles
• Reactor Pattern (Libevent event loop dispatch)
• Modular design: core engine + optional submodules (SSL, threading, regex)
• Callback-based extensibility for request handling
• Reference counting for request/connection objects to manage lifecycle
d. Key Technologies & Libraries
• Libevent2 (event-driven I/O)
• CMake (build & packaging)
• OpenSSL (HTTPS support)
• pthreads (concurrency)
• Oniguruma (regex-based routing)