This document describes every .pbi module in src/ and the entry-point main.pb. For each module the public API (procedures and exported globals), the compile-time dependencies, and notable implementation details are listed.
Inclusion order follows main.pb and tests/TestCommon.pbi. The XIncludeFile
directive is idempotent — each file is compiled at most once per compilation unit.
Tutorial: For a step-by-step walkthrough of how all modules fit together, see
BUILD_OUR_HTTP_SERVER.md.
Purpose: Application-wide constants, HTTP status codes, and buffer size definitions. No procedures. No globals.
| Constant | Value | Meaning |
|---|---|---|
#APP_NAME |
"PureSimpleHTTPServer" |
Used in Server: response header |
#APP_VERSION |
"2.5.0" |
Used in startup banner |
#HTTP_200 ... #HTTP_500 |
200-500 | HTTP status code shorthand. #HTTP_204 (204 No Content) added in v2.4.0, #HTTP_401 (401 Unauthorized) added in v2.5.0 |
#RECV_BUFFER_SIZE |
65536 | Per-connection TCP receive buffer (64 KB) |
#SEND_CHUNK_SIZE |
65536 | File send chunk size (64 KB) |
#MAX_HEADER_SIZE |
8192 | Maximum accepted request header block (8 KB) |
#DEFAULT_PORT |
8080 | Listening port when none is specified |
#DEFAULT_INDEX |
"index.html" |
Default index file name |
None. Must be the first XIncludeFile in any compilation unit.
Purpose: Shared structure definitions used across multiple modules.
Filled by ParseHttpRequest in HttpParser.pbi.
| Field | Type | Description |
|---|---|---|
Method |
.s |
HTTP method |
Path |
.s |
Decoded, normalized URL path |
QueryString |
.s |
Raw query string or "" |
Version |
.s |
"HTTP/1.1" or "HTTP/1.0" |
RawHeaders |
.s |
Raw header lines |
ContentLength |
.i |
Value of Content-Length, or 0 |
Body |
.s |
Request body, if any |
IsValid |
.i |
#True when parsing succeeded |
ErrorCode |
.i |
HTTP status code on parse failure |
Used by middleware to build responses. The chain runner (RunRequest) owns the
final *Body and frees it.
| Field | Type | Description |
|---|---|---|
StatusCode |
.i |
HTTP status code |
Headers |
.s |
Response headers (each line ends with #CRLF$) |
*Body |
.i |
Pointer to allocated body buffer |
BodySize |
.i |
Body size in bytes |
Handled |
.i |
#True if a middleware produced a response |
Passed through the middleware chain.
| Field | Type | Description |
|---|---|---|
ChainIndex |
.i |
Current position in the chain (-1 initially) |
Connection |
.i |
TCP connection ID |
*Config |
.i |
Pointer to ServerConfig |
BytesSent |
.i |
Set by RunRequest after sending |
Vtable-based writer abstraction for body output.
| Field | Type | Description |
|---|---|---|
Write |
ProtoWrite |
Function pointer: write bytes |
Flush |
ProtoFlush |
Function pointer: flush/finalize |
*inner |
*ResponseWriter |
Wrapped writer (0 for terminal) |
*ctx |
.i |
Opaque state pointer |
connection |
.i |
TCP connection ID (PlainWriter) |
| Field | Type | Description |
|---|---|---|
Start |
.i |
First byte (inclusive) |
End |
.i |
Last byte (inclusive) |
IsValid |
.i |
#True if satisfiable |
| Field | Type | Description |
|---|---|---|
Port |
.i |
Listening port |
RootDirectory |
.s |
Document root |
IndexFiles |
.s |
Comma-separated index file names |
BrowseEnabled |
.i |
Directory listing flag |
SpaFallback |
.i |
SPA mode flag |
HiddenPatterns |
.s |
Comma-separated blocked segments |
LogFile |
.s |
Access log path |
MaxConnections |
.i |
Max concurrent connections |
ErrorLogFile |
.s |
Error log path |
LogLevel |
.i |
Error log threshold |
LogSizeMB |
.i |
Size-rotation threshold |
LogKeepCount |
.i |
Archive keep count |
LogDaily |
.i |
Daily rotation flag |
PidFile |
.s |
PID file path |
CleanUrls |
.i |
Clean URL flag |
RewriteFile |
.s |
Rewrite conf path |
ServiceMode |
.i |
Windows service flag |
ServiceName |
.s |
Windows service name |
TlsCert |
.s |
TLS certificate path (v2.1.0+) |
TlsKey |
.s |
TLS key path (v2.1.0+) |
AutoTlsDomain |
.s |
Auto-TLS domain (v2.2.0+) |
NoGzip |
.i |
Disable gzip flag (v2.3.0+) |
HealthPath |
.s |
Health check endpoint path (v2.4.0+) |
CorsEnabled |
.i |
CORS enabled flag (v2.4.0+) |
CorsOrigin |
.s |
CORS specific origin (v2.4.0+) |
SecurityHeaders |
.i |
Security headers flag (v2.4.0+) |
ErrorPagesDir |
.s |
Custom error pages directory (v2.5.0+) |
BasicAuthUser |
.s |
Basic auth username (v2.5.0+) |
BasicAuthPass |
.s |
Basic auth password (v2.5.0+) |
CacheMaxAge |
.i |
Cache-Control max-age in seconds (v2.5.0+) |
Global.pbi
Purpose: RFC 7231 HTTP date formatting.
Returns a string like "Sat, 14 Mar 2026 00:00:00 GMT".
Purpose: URL percent-decoding and path normalization.
Purpose: HTTP/1.1 request parser.
Purpose: HTTP/1.1 response builder.
FillTextResponse(*resp.ResponseBuffer, statusCode.i, contentType.s, body.s) — Fill a ResponseBuffer with UTF-8 text (v2.0.0+). Allocates the body buffer.
Purpose: TCP server event loop, thread-per-connection dispatch, TLS support.
| Global | Type | Description |
|---|---|---|
g_Handler |
ConnectionHandlerProto |
Request handler function pointer |
g_Running |
.i |
Server loop active flag |
g_CloseMutex |
.i |
Close queue mutex |
g_CloseList |
NewList .i() |
Close queue |
g_TlsEnabled |
.i |
TLS active flag (v2.1.0+) |
g_TlsKey |
.s |
PEM key content (v2.1.0+) |
g_TlsCert |
.s |
PEM cert content (v2.1.0+) |
g_ServerID |
.i |
Network server handle |
g_ServerPort |
.i |
Current listening port |
g_RestartFlag |
.i |
Server restart signal (v2.2.0+) |
Purpose: MIME type lookup by file extension.
Purpose: Access log (Apache CLF), error log, rotation, SIGHUP reopen.
OpenLogFile(path.s) -> .i/CloseLogFile()OpenErrorLog(path.s) -> .i/CloseErrorLog()LogAccess(ip, method, path, protocol, status, bytes, referer, userAgent)LogError(level.s, message.s)StartDailyRotation()/StopDailyRotation()
Purpose: Utility functions used by middleware for file serving.
IsHiddenPath(urlPath.s, hiddenPatterns.s) -> .i — Check blocked segments.
Dependencies: Global.pbi, Types.pbi, DateHelper.pbi, HttpParser.pbi, HttpResponse.pbi, MimeTypes.pbi
Purpose: HTML directory listing generator.
Purpose: HTTP Range header parser.
Purpose: In-memory asset serving from compiled-in ZIP archive.
Purpose: Configuration defaults, CLI parsing, PEM file reading.
Recognized flags: --port, --root, --browse, --spa, --log, --error-log,
--log-level, --log-size, --log-keep, --no-log-daily, --pid-file,
--clean-urls, --rewrite, --tls-cert, --tls-key, --auto-tls, --no-gzip,
--health, --cors, --cors-origin, --security-headers,
--error-pages, --basic-auth, --cache-max-age,
--service, --service-name.
Purpose: URL rewrite/redirect rule evaluation. Thread-safe via g_RewriteMutex.
Purpose: Middleware chain infrastructure, all 15 middleware, and utility functions.
RunRequest(connection.i, raw.s, *cfg.ServerConfig) -> .i — Chain runner: parse → chain → send → free → log.
Middleware_Rewrite— URL rewrite/redirect rulesMiddleware_HealthCheck— Short-circuit health check endpoint (200 JSON)Middleware_IndexFile— Directory → index file resolutionMiddleware_CleanUrls— Extensionless →.htmlfallbackMiddleware_SpaFallback— 404 → root index for SPAsMiddleware_HiddenPath— Block.git/.envpaths (403)Middleware_Cors— CORS preflight (204) and header post-processingMiddleware_BasicAuth— HTTP Basic Authentication (401 if invalid/missing)Middleware_SecurityHeaders— Append security headers to responsesMiddleware_ETag304— Return 304 on ETag matchMiddleware_GzipSidecar— Serve pre-compressed.gzfilesMiddleware_GzipCompress— Dynamic gzip compression (post-processing)Middleware_EmbeddedAssets— Serve from in-memory packMiddleware_FileServer— Serve from disk (200 + 206 range)Middleware_DirectoryListing— HTML directory listing
FillErrorResponse(*resp.ResponseBuffer, statusCode.i, *cfg.ServerConfig) — Fill response with custom error page from ErrorPagesDir or plain-text fallback (v2.5.0+).
GzipCompressBuffer(*input, inputSize.i, *outSize.Integer) -> .i — Compress to gzip format. Caller must FreeMemory().
Global.pbi, Types.pbi, HttpParser.pbi, HttpResponse.pbi, MimeTypes.pbi,
DateHelper.pbi, Logger.pbi, FileServer.pbi, DirectoryListing.pbi,
RangeParser.pbi, EmbeddedAssets.pbi, RewriteEngine.pbi
Purpose: Automatic TLS certificate management via acme.sh.
| Global | Type | Description |
|---|---|---|
g_AutoTlsDomain |
.s |
Domain for auto-TLS |
g_AcmeChallengeDir |
.s |
ACME challenge directory path |
Purpose: Windows Service API wrapper. Provides no-op stubs on non-Windows platforms.
Purpose: POSIX SIGHUP handler for logrotate integration. No-op on Windows.
Purpose: Application entry point. Includes all modules, defines
RunRequestWrapper, and runs the startup/shutdown sequence.
| Global | Type | Description |
|---|---|---|
g_Config |
ServerConfig |
Runtime configuration |
LoadDefaults → ParseCLI → Windows service handling
→ InitRewriteEngine → LoadGlobalRules
→ configure Logger globals → getpid
→ OpenLogFile → OpenErrorLog → write PID file
→ StartDailyRotation → InstallSignalHandlers
→ TLS setup (auto-tls or manual)
→ startup banner → BuildChain → g_Handler = @RunRequestWrapper()
→ StartServer (blocks)
StopCertRenewal → StopHttpRedirect (if auto-tls)
→ RemoveSignalHandlers → StopDailyRotation
→ CloseLogFile → CloseErrorLog → DeleteFile(PidFile)
→ CleanupRewriteEngine → CloseEmbeddedPack