Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #pragma once
26 :
27 : #include <stdint.h>
28 : #include <sys/types.h>
29 :
30 : #include "chttp.h"
31 : #include "clogger.h"
32 : #include "common.h"
33 :
34 : // Everything from here to the matching pop is the public ABI and the shared
35 : // library exports it. The library builds with -fvisibility=hidden, so anything
36 : // outside these blocks stays internal.
37 : #pragma GCC visibility push(default)
38 :
39 : // An HTTP/1.1 server on a shared ceventloop reactor, with routes, path
40 : // parameters, middleware, sub-routers, streaming bodies and optional TLS. The
41 : // first chttpsvr_start() brings up the shared reactor (the engine) and
42 : // destroying the last running server takes it down, so you rarely touch the
43 : // engine yourself. Several servers can run at once, each with its own port,
44 : // routes, pools and logger. The usual shape is chttpsvr_construct(),
45 : // chttpsvr_register_handler(), chttpsvr_start(srv, &cfg),
46 : // chttpsvr_engine_wait() and chttpsvr_destroy().
47 : //
48 : // The server routes a request as soon as its headers are parsed, before it
49 : // reads a body byte, so the reactor thread never runs your code and never waits
50 : // for a slow body. A buffered route runs on the server's worker pool once its
51 : // whole body is in memory; a body or a response that stalls parks its
52 : // connection with no thread, and any free worker picks it up again later. A
53 : // streaming route runs on a separate streaming pool and pulls its body with
54 : // chttpsvr_req_read(). Handlers and middleware may block. A handler counts as a
55 : // thread of its own server: chttpsvr_destroy(), a restart and
56 : // chttpsvr_engine_wait() are refused or fatal there, while
57 : // chttpsvr_engine_stop() is safe.
58 : //
59 : // The server refuses a malformed request before any route sees it and closes
60 : // the connection after the answer: 505 for a version other than HTTP/1.x, 400
61 : // for a bad Host, a line above 8 KiB, more than 100 header lines or a header
62 : // block above max_header_bytes, and 501 for a transfer coding other than
63 : // chunked.
64 : //
65 : // Routers are tried from the most specific mount prefix to the least, and the
66 : // root router last. A mount owns every path under its prefix (judged on the
67 : // decoded path): Its routes answer, or it answers 404 or 405 itself, and its
68 : // middleware runs either way, so a guard on a mount covers all of its paths
69 : // (a nested mount owns its own paths and needs its own guard).
70 : // Inside one router, routes are tried in registration order. A CHTTP_GET route
71 : // also serves HEAD. Paths and {param} values are decoded and can hold '/' (from
72 : // %2F) or be "..", so never use them as file names unchecked. Each router holds
73 : // at most 32 middleware, and a request whose global plus sub-router chain is
74 : // longer than 32 gets 500.
75 : //
76 : // Point chttpsvr_config.tls at a chttp_tls_config to serve HTTPS; a
77 : // ca_bundle_path there turns on mutual TLS. The man pages (chttpserver(7) and
78 : // one page per function) hold the full contract.
79 :
80 : // The opaque server struct. You only ever hold a chttpsvr handle to it.
81 : typedef struct chttpserver chttpserver;
82 :
83 : // A server handle. It's a value (a slot index and a generation packed into 64
84 : // bits), not a pointer, so the library detects a stale handle instead of
85 : // touching freed memory. Compare it with CHTTPSVR_NULL and never cast it to a
86 : // pointer.
87 : typedef uint64_t chttpsvr;
88 :
89 : // The "no server" value, which a failed create returns and a destroy leaves
90 : // behind. It's 0, so if (!srv) works.
91 : #define CHTTPSVR_NULL ((chttpsvr)0)
92 :
93 : // A sub-router that groups routes and middleware under a path prefix. The
94 : // server owns it.
95 : typedef struct chttpsvr_router chttpsvr_router;
96 :
97 : // The request that a handler or middleware reads through the chttpsvr_req_
98 : // functions. It's valid only while the chain for that request runs.
99 : typedef struct chttpsvr_req chttpsvr_req;
100 :
101 : // The response that a handler fills through the chttpsvr_resp_ functions; the
102 : // server sends it after the handler returns.
103 : typedef struct chttpsvr_resp chttpsvr_resp;
104 :
105 : // A request handler, which is how your code answers a matched route. It runs on
106 : // a thread of the server's worker pool (buffered route) or streaming pool
107 : // (streaming route) and may block. req and resp are valid only during the call,
108 : // and ctx is the pointer you gave at registration.
109 : typedef void (*chttpsvr_handler_fn)(chttpsvr_req *req, chttpsvr_resp *resp,
110 : void *ctx);
111 :
112 : // Hands the request to the next middleware, or to the final handler when none
113 : // is left. Each middleware gets one, and a middleware that doesn't call it
114 : // stops the chain there. Call it at most once per middleware call, because a
115 : // second call moves the chain on once more.
116 : typedef void (*chttpsvr_next_fn)(chttpsvr_req *req, chttpsvr_resp *resp);
117 :
118 : // A middleware. It runs before the handler on the same pool thread and may
119 : // block, and global middleware runs before sub-router middleware. ctx is the
120 : // pointer you passed to chttpsvr_use() or chttpsvr_router_use(), and next hands
121 : // the request on.
122 : typedef void (*chttpsvr_middleware_fn)(chttpsvr_req *req, chttpsvr_resp *resp,
123 : void *ctx, chttpsvr_next_fn next);
124 :
125 : // A worker_queue_capacity or streaming_queue_capacity for a queue with no
126 : // limit, where an overflow never gives 503. Such a queue grows without bound
127 : // under a long overload, so a finite one is usually the better choice.
128 : #define CHTTPSVR_QUEUE_UNBOUNDED ((size_t)-1)
129 :
130 : // A min_transfer_rate_bps that turns the minimum transfer rate off, so only the
131 : // gap and total limits bound a slow client.
132 : #define CHTTPSVR_NO_RATE_FLOOR ((unsigned)-1)
133 :
134 : // A max_partial_body_memory that puts no limit on the memory buffered bodies
135 : // hold.
136 : #define CHTTPSVR_NO_MEMORY_CAP ((size_t)-1)
137 :
138 : // A body_memory_wait_timeout_us or streaming_queue_timeout_us that lets a
139 : // request wait with no deadline.
140 : #define CHTTPSVR_NO_DEADLINE UINT64_MAX
141 :
142 : // A streaming_thread_count that runs streaming handlers on the worker pool,
143 : // with no pool of their own.
144 : #define CHTTPSVR_STREAMING_POOL_OFF (-1)
145 :
146 : // The configuration that chttpsvr_start() takes. Start from
147 : // CHTTPSVR_CONFIG_DEFAULT and change the fields you need. Every _us field
148 : // counts microseconds. The server rounds it up to whole milliseconds and
149 : // saturates a value too large to keep at its longest finite limit (at least 24
150 : // days), so only CHTTPSVR_NO_DEADLINE means no limit.
151 : typedef struct chttpsvr_config {
152 : // Bind address, with the rules of Go's listener. NULL or "" listens on every
153 : // interface through one dual-stack [::] socket (0.0.0.0 on a host without
154 : // IPv6). A literal address listens on that address alone, and an address in
155 : // brackets means the address inside. A host name listens on its first IPv4
156 : // address, else its first IPv6 address (the other way round with ipv6_only),
157 : // and on that one only: A failed lookup or bind fails the start.
158 : // "unix://path" binds a Unix domain socket instead and ignores port. A stale
159 : // socket file there is replaced, but any other file, or a socket that a live
160 : // server listens on, fails the start, and stop and destroy remove only the
161 : // socket file this server created. One server listens on TCP or on a Unix
162 : // socket, never both.
163 : const char *host;
164 : // Port to listen on (default 8080). 0 asks the system for an ephemeral port,
165 : // picked again at every start; chttpsvr_bound_port() reports it.
166 : uint16_t port;
167 : // Largest request body in bytes (default 4 MiB); 0 means no limit. A buffered
168 : // route above it gets 413 before the handler runs, and a streaming read fails
169 : // with ccol_msg_too_large. Either way the connection closes after the
170 : // response.
171 : size_t max_body_size;
172 : // Idle limit for a connection waiting for the headers of its next request
173 : // (default 60 s); 0 turns it off. It bounds the gap between bytes, not a peer
174 : // that sends its headers slowly for ever (max_header_read_duration_us does
175 : // that). Turn it off only when something in front of the server already
176 : // bounds idle connections.
177 : uint64_t read_timeout_us;
178 : // Keep-alive idle limit (default 60 s). 0 uses read_timeout_us, and any other
179 : // value replaces it as the idle threshold.
180 : uint64_t idle_timeout_us;
181 : // Longest gap between two batches of body bytes, buffered or streaming
182 : // (default 30 s); 0 means no limit. When it passes, a buffered route answers
183 : // 408 and chttpsvr_req_read() fails with ccol_timed_out. A 0 here or in
184 : // max_body_read_duration_us doesn't make chttpsvr_destroy() or
185 : // chttpsvr_engine_stop() wait for ever: The shutdown force-closes such a
186 : // connection once its graceful wait is over.
187 : uint64_t stream_read_timeout_us;
188 : // Total time one request body may take to arrive (default 5 minutes); 0 means
189 : // no limit. It catches a client that sends a byte just before each
190 : // stream_read_timeout_us gap runs out, and fails the same way.
191 : uint64_t max_body_read_duration_us;
192 : // Longest gap without progress while a response goes to a slow reader; 0 (the
193 : // default) uses stream_read_timeout_us. Progress is a write the kernel
194 : // accepts or a shrinking send queue, which the sweep checks about once a
195 : // second, so a steady reader never hits it and the limit is only that
196 : // precise.
197 : uint64_t response_write_timeout_us;
198 : // Total time one response may take to send (default 5 minutes); 0 means no
199 : // limit. On expiry the connection closes and the client keeps what it has
200 : // read. Rejections that the server writes itself and the interim "100
201 : // Continue" always have a 2-second ceiling of their own, whatever this says.
202 : uint64_t max_response_write_duration_us;
203 : // Total time for the TLS handshake plus the header block of one request
204 : // (default 30 s); 0 means no limit. It bounds a peer that sends its headers
205 : // one byte at a time and never finishes. The budget is per request and starts
206 : // at its first byte (or handshake step), so idle time between keep-alive
207 : // requests isn't charged. An expired connection closes with no response, up
208 : // to a second late because the sweep checks it.
209 : uint64_t max_header_read_duration_us;
210 : // Largest header block in bytes, request line included; 0 means the built-in
211 : // 64 KiB. A larger block gets 400 and a close. Each line is also limited to 8
212 : // KiB and a request to 100 header lines, chunked trailers included.
213 : size_t max_header_bytes;
214 : // Most connections open at once on this listener (default 16384); 0 means no
215 : // limit. At the limit the server stops calling accept(2), new connections
216 : // wait in the kernel backlog, and accepting resumes within about a second of
217 : // a slot freeing.
218 : size_t max_connections;
219 : // TLS configuration, or NULL for plain HTTP.
220 : const chttp_tls_config *tls;
221 : // Threads in the server's worker pool; 0 (the default) means one per CPU.
222 : int worker_thread_count;
223 : // Capacity of the worker task queue: 0 means 1024 per worker thread,
224 : // CHTTPSVR_QUEUE_UNBOUNDED means no limit, and any other value is the exact
225 : // limit. A request that finds the queue full gets 503.
226 : size_t worker_queue_capacity;
227 : // Turns SO_KEEPALIVE on for accepted TCP connections (default off), so the OS
228 : // finds a peer that became unreachable. No effect on a Unix socket.
229 : bool enable_keepalive;
230 : // Sets SO_REUSEPORT on the listener (default off), so several processes or
231 : // servers can share the host and port while the kernel spreads connections
232 : // between them. No effect on a Unix socket or with port 0.
233 : bool enable_reuseport;
234 : // Sets IPV6_V6ONLY on an IPv6 listener (default off). Off gives a dual-stack
235 : // listener for a NULL or empty host and the OS default for an explicit IPv6
236 : // address; on refuses IPv4 traffic.
237 : bool ipv6_only;
238 : // Lowest average rate, in bytes per second, at which a client must send its
239 : // body and read its response; 0 means the default of 240 and
240 : // CHTTPSVR_NO_RATE_FLOOR turns it off. It's judged over the whole phase once
241 : // min_transfer_rate_grace_us has passed. A slow body gets 408, a slow
242 : // response is cut off, and a streaming read fails with ccol_timed_out. Time
243 : // the server itself holds a request back is never charged to the client.
244 : unsigned min_transfer_rate_bps;
245 : // How long a body read or a response write runs before min_transfer_rate_bps
246 : // applies; 0 means the default of 5 s.
247 : uint64_t min_transfer_rate_grace_us;
248 : // Most memory, in bytes, that the buffered request bodies of this server hold
249 : // together, from the first byte read until the handler returns; 0 means 256
250 : // MiB and CHTTPSVR_NO_MEMORY_CAP turns it off. A body reserves its buffer as
251 : // its bytes arrive (a first buffer of at most 16 KiB, then each doubling, up
252 : // to the declared length), so a client that declares much and sends little
253 : // holds little. A request whose next buffer doesn't fit waits with no thread,
254 : // in arrival order, and gets no "100 Continue" meanwhile. When every holder
255 : // is waiting, the oldest goes ahead alone, so the limit can be passed by less
256 : // than twice max_body_size. A body that arrives with its headers, and every
257 : // streaming route, reserves nothing.
258 : size_t max_partial_body_memory;
259 : // How long a request may wait for body memory before it gets 503 with
260 : // Retry-After and a close; 0 means 30 s and CHTTPSVR_NO_DEADLINE means no
261 : // limit.
262 : uint64_t body_memory_wait_timeout_us;
263 : // Threads in the streaming pool, which the server creates on the first
264 : // streaming request; 0 means the resolved worker_thread_count and
265 : // CHTTPSVR_STREAMING_POOL_OFF runs streaming handlers on the worker pool. A
266 : // pool of their own keeps slow streaming clients off the threads of buffered
267 : // routes.
268 : int streaming_thread_count;
269 : // How many streaming requests may wait, holding no thread, for a free
270 : // streaming thread; 0 means four times the streaming thread count and
271 : // CHTTPSVR_QUEUE_UNBOUNDED means no limit. A request that finds the queue
272 : // full gets 503 and a close.
273 : size_t streaming_queue_capacity;
274 : // How long a streaming request may wait in that queue before it gets 503 and
275 : // a close; 0 means 5 s and CHTTPSVR_NO_DEADLINE means no limit.
276 : uint64_t streaming_queue_timeout_us;
277 : } chttpsvr_config;
278 :
279 : // The default configuration as a compound literal: Port 8080 on every
280 : // interface, a 4 MiB body limit, no TLS, one worker per CPU and a finite value
281 : // for every timeout and resource limit, so a server started from it is already
282 : // bounded against peers that stall or trickle. The fields from
283 : // min_transfer_rate_bps on read 0 as their default, so a configuration built
284 : // with {0} keeps those limits too.
285 : #define CHTTPSVR_CONFIG_DEFAULT \
286 : ((chttpsvr_config){ \
287 : .host = NULL, \
288 : .port = 8080, \
289 : .max_body_size = (4U * 1024U * 1024U), \
290 : .read_timeout_us = 60000000, \
291 : .idle_timeout_us = 60000000, \
292 : .stream_read_timeout_us = 30000000, \
293 : .max_body_read_duration_us = 300000000, \
294 : .response_write_timeout_us = 0, \
295 : .max_response_write_duration_us = 300000000, \
296 : .max_header_read_duration_us = 30000000, \
297 : .max_header_bytes = 0, \
298 : .max_connections = 16384, \
299 : .tls = NULL, \
300 : .worker_thread_count = 0, \
301 : .worker_queue_capacity = 0, \
302 : .enable_keepalive = false, \
303 : .enable_reuseport = false, \
304 : .ipv6_only = false, \
305 : .min_transfer_rate_bps = 240, \
306 : .min_transfer_rate_grace_us = 5000000, \
307 : .max_partial_body_memory = (256U * 1024U * 1024U), \
308 : .body_memory_wait_timeout_us = 30000000, \
309 : .streaming_thread_count = 0, \
310 : .streaming_queue_capacity = 0, \
311 : .streaming_queue_timeout_us = 5000000, \
312 : })
313 :
314 : // Installs the logger for the engine's own diagnostics (TLS handshake failures,
315 : // bind failures, idle-timeout closes), which is separate from the logger of
316 : // each server. Without one, an engine logs through a FATAL-only stderr logger
317 : // that is silent in practice. It derives a logger from cl with
318 : // component=http-server-engine and closes the one an earlier call derived; you
319 : // keep cl. The derived logger serves the running engine and every later one
320 : // until another call replaces it. CLOG_NULL releases it, which is refused while
321 : // an engine runs: Release it after chttpsvr_engine_wait() and before you
322 : // destroy the allocator of cl or close its file descriptor. Gives ccol_success,
323 : // ccol_not_permitted for that refused release, ccol_invalid_args for a closed
324 : // or stale cl (the installed logger stays), or ccol_not_enough_memory.
325 : ccol_retval chttpsvr_set_engine_logger(clog cl);
326 :
327 : // Sets the allocator for the shared reactor's own memory, so the engine can use
328 : // the same allocator as the rest of your program; NULL goes back to the
329 : // default. Each server's own memory follows chttpsvr_create_mp() instead. Call
330 : // it only while no engine exists (before the first chttpsvr_start(), or after
331 : // chttpsvr_engine_wait() returns), because a switch of allocator under live
332 : // memory corrupts the heap. Gives ccol_success, ccol_invalid_args when mp has a
333 : // NULL function pointer, or ccol_not_permitted while an engine runs.
334 : ccol_retval chttpsvr_set_engine_mem_mgmt_procs(ccol_memmgmt_procs *mp);
335 :
336 : // Sets how many threads the shared reactor of every server uses; 0 means the
337 : // default of 1. One thread polls and runs every dispatch itself; with more,
338 : // one thread polls and num_threads - 1 dispatch workers run the dispatches.
339 : // One thread is faster for reused connections, plain or TLS. Raise it for TLS
340 : // traffic where many clients connect for one request each, so their handshakes
341 : // spread over the cores. Call it only while no engine exists (before the first
342 : // chttpsvr_start(), or after chttpsvr_engine_wait() returns). Gives
343 : // ccol_success, or ccol_not_permitted while an engine runs.
344 : ccol_retval chttpsvr_set_engine_num_reactor_threads(size_t num_threads);
345 :
346 : // Blocks until the threads of the shared engine have exited, and returns at
347 : // once when no engine runs. Use it to keep main() alive until a signal stops
348 : // the engine, and after the last chttpsvr_destroy(), which only starts the
349 : // engine teardown on a reaper thread: Wait before you return from main(),
350 : // unload the library or free the engine allocator. A call from a handler or
351 : // middleware of any server is fatal, because that request would wait for a
352 : // drain that waits for it.
353 : void chttpsvr_engine_wait(void);
354 :
355 : // Asks the shared engine to stop and returns at once. It's async-signal-safe,
356 : // so a SIGTERM handler can call it, and a handler may call it to shut its own
357 : // server down. Every running server stops taking requests: Idle connections
358 : // close, later requests get 503, and responses already running carry
359 : // Connection: close. chttpsvr_engine_wait() waits for the drain, a destroy that
360 : // is draining included. A repeated or overlapping call does nothing more, a
361 : // call while no engine runs does nothing, and a call never reaches an engine
362 : // started after it. The library installs no signal handler of its own.
363 : void chttpsvr_engine_stop(void);
364 :
365 : // Creates a server that allocates through mprocs (NULL for malloc and free). It
366 : // stays idle until chttpsvr_start(), and routes and middleware can be added
367 : // before or after that. The server logs through a logger derived from cl with
368 : // component=http-server, or a FATAL-only stderr logger for CLOG_NULL, and
369 : // closes it at destroy; you keep cl. Gives the handle, or CHTTPSVR_NULL with a
370 : // static string in *err_str (when err_str isn't NULL). A closed or stale cl,
371 : // and a call after the library's exit-time cleanup has run, fail this way.
372 : chttpsvr chttpsvr_create_mp(ccol_memmgmt_procs *mprocs, clog cl,
373 : char **err_str);
374 :
375 : // Creates a server that allocates with malloc. It stays idle until
376 : // chttpsvr_start(), and routes and middleware can be added before or after
377 : // that. The server logs through a logger derived from cl with
378 : // component=http-server, or a FATAL-only stderr logger for CLOG_NULL, and
379 : // closes it at destroy; you keep cl. Gives the handle, which you free with
380 : // chttpsvr_destroy(), or CHTTPSVR_NULL with a static string in *err_str (when
381 : // err_str isn't NULL), for example for a closed or stale cl or a call after the
382 : // library's exit-time cleanup has run.
383 : static inline __attribute__((always_inline)) chttpsvr
384 : chttpsvr_create(clog cl, char **err_str) {
385 518 : return chttpsvr_create_mp(NULL, cl, err_str);
386 : }
387 :
388 : // Internal: Destroys the server; it's the body of chttpsvr_destroy(), which
389 : // also clears your handle. Use the macro instead.
390 : void chttpsvr__destroy(chttpsvr srv);
391 :
392 : // Internal: Destroys *pp and sets it to CHTTPSVR_NULL. The _scoped macros
393 : // attach it with ccol__destructor, so the server goes away at the end of its
394 : // scope.
395 : static inline __attribute__((always_inline)) void chttpsvr__destroy_cleanup(
396 : chttpsvr *pp) {
397 157 : if (pp && *pp) {
398 88 : chttpsvr__destroy(*pp);
399 88 : *pp = CHTTPSVR_NULL;
400 : }
401 157 : }
402 :
403 : // Destroys the server and sets name to CHTTPSVR_NULL. It stops the listener,
404 : // closes idle connections, answers later requests with 503, waits for the
405 : // running handlers (cutting their connections after 30 s), and frees the
406 : // server's pools, routes and engine reference. For the last server it only
407 : // starts the engine teardown on a reaper thread; call chttpsvr_engine_wait()
408 : // when that must be finished. name must be a modifiable lvalue and is evaluated
409 : // once. CHTTPSVR_NULL does nothing. A stale or forged handle, a second destroy
410 : // (sequential or concurrent) and a call from a handler or middleware of this
411 : // server are fatal errors. Each sub-router keeps about 100 bytes until the
412 : // process exits, so a pointer to it stays safe to pass.
413 : #define chttpsvr_destroy(name) \
414 : ccol__chttpsvr_destroy_impl( \
415 : name, ccol__uniq(ccol__chttpsvr_destroy_slot, __COUNTER__))
416 :
417 : // Internal: The body of chttpsvr_destroy(). It takes the address of name once
418 : // into slot, which comes from ccol__uniq() so destroy macros can nest without
419 : // -Wshadow warnings.
420 : #define ccol__chttpsvr_destroy_impl(name, slot) \
421 : do { \
422 : __typeof__(name) *slot = &(name); \
423 : chttpsvr__destroy(*slot); \
424 : *slot = CHTTPSVR_NULL; \
425 : } while (0)
426 :
427 : // Declares a server handle variable called name with no value; create the
428 : // server with chttpsvr_create() later and free it with chttpsvr_destroy().
429 : #define chttpsvr_declare(name) chttpsvr name
430 :
431 : // Declares a server handle variable called name, set to CHTTPSVR_NULL, that is
432 : // destroyed when it goes out of scope if it then holds a server. Create the
433 : // server with chttpsvr_create(). The scope-end destroy stops and drains the
434 : // server like chttpsvr_destroy(), and is a fatal error for a stale handle or
435 : // when it runs in a handler or middleware of that server.
436 : #define chttpsvr_declare_scoped(name) \
437 : chttpsvr name ccol__destructor(chttpsvr__destroy_cleanup) = CHTTPSVR_NULL
438 :
439 : // Declares a server handle variable called name and creates the server in one
440 : // step, with the default allocator and a logger derived from cl (a FATAL-only
441 : // stderr logger for CLOG_NULL; you keep cl). A program that can't run without
442 : // its server needs no error handling: A failed create stops the program with a
443 : // fatal error that names the variable and the reason. Start it with
444 : // chttpsvr_start() and free it with chttpsvr_destroy().
445 : #define chttpsvr_construct(name, cl) \
446 : chttpsvr name = CHTTPSVR_NULL; \
447 : do { \
448 : char *chttpsvr__err = NULL; \
449 : (name) = chttpsvr_create((cl), &chttpsvr__err); \
450 : if (!(name)) { \
451 : ccol__fatal_err("chttpsvr_construct('%s'): %s", #name, \
452 : chttpsvr__err ? chttpsvr__err : "unknown error"); \
453 : } \
454 : } while (0)
455 :
456 : // Declares a server handle variable called name and creates the server in one
457 : // step, with the default allocator and a logger derived from cl (a FATAL-only
458 : // stderr logger for CLOG_NULL; you keep cl). The server is stopped, drained and
459 : // destroyed when name goes out of scope. A failed create stops the program with
460 : // a fatal error that names the variable and the reason.
461 : #define chttpsvr_construct_scoped(name, cl) \
462 : chttpsvr name ccol__destructor(chttpsvr__destroy_cleanup) = CHTTPSVR_NULL; \
463 : do { \
464 : char *chttpsvr__err = NULL; \
465 : (name) = chttpsvr_create((cl), &chttpsvr__err); \
466 : if (!(name)) { \
467 : ccol__fatal_err("chttpsvr_construct_scoped('%s'): %s", #name, \
468 : chttpsvr__err ? chttpsvr__err : "unknown error"); \
469 : } \
470 : } while (0)
471 :
472 : // Binds the listener and starts serving, bringing up the shared engine when no
473 : // engine runs. A NULL cfg means CHTTPSVR_CONFIG_DEFAULT. The server creates its
474 : // worker pool here; on a restart (chttpsvr_stop(), then this) the new pools
475 : // replace the old ones at once and requests of the earlier run finish in the
476 : // background. A restart waits for a concurrent stop of the same server, and a
477 : // start retries through a concurrent engine teardown. A connection closed while
478 : // its client may be sending gets a lingering close (up to 2 s) so the client
479 : // reads the response, and no write raises SIGPIPE. Returns at once. Gives
480 : // ccol_success; ccol_invalid_args for a bad handle, a tls without both
481 : // cert_path and key_path, or a negative streaming_thread_count other than
482 : // CHTTPSVR_STREAMING_POOL_OFF; ccol_not_permitted when the server runs or the
483 : // call comes from one of its own handlers or middleware;
484 : // ccol_not_enough_memory; ccol_http_tls_cert_load_failed when the certificate,
485 : // key or CA bundle won't load; or ccol_unexpected_failure when the bind, the
486 : // registration with the reactor, or a thread or thread key creation fails (the
487 : // logs say why).
488 : ccol_retval chttpsvr_start(chttpsvr srv, const chttpsvr_config *cfg);
489 :
490 : // Closes the listener, so the server takes no new connections while the ones it
491 : // accepted keep being served; chttpsvr_destroy() is what closes those and
492 : // drains them. The engine and other servers keep running. A NULL or stale
493 : // handle does nothing. It takes internal locks, so it isn't async-signal-safe:
494 : // use chttpsvr_engine_stop() from a signal handler.
495 : void chttpsvr_stop(chttpsvr srv);
496 :
497 : // Size of a buffer, NUL byte included, that holds every address
498 : // chttpsvr_bound_address() can write.
499 : #define CHTTPSVR_BOUND_ADDRESS_SIZE 128
500 :
501 : // Tells whether the server listens, which it does from a successful
502 : // chttpsvr_start() until a stop begins; a server in the middle of a start or a
503 : // stop doesn't. The answer is a snapshot. Gives ccol_success with the answer in
504 : // *running_out, or ccol_invalid_args (and false) for a bad handle or a NULL
505 : // running_out.
506 : ccol_retval chttpsvr_is_running(chttpsvr srv, bool *running_out);
507 :
508 : // Gives the TCP port the listener really bound, which you need when cfg->port
509 : // was 0 and the system picked it. Gives ccol_success with the port in *port_out
510 : // (host byte order), ccol_invalid_args for a bad handle or a NULL port_out, or
511 : // ccol_not_permitted when the server doesn't listen or listens on a Unix
512 : // socket; *port_out is 0 on failure.
513 : ccol_retval chttpsvr_bound_port(chttpsvr srv, uint16_t *port_out);
514 :
515 : // Writes the address the listener bound into buf: The numeric address without
516 : // port or brackets for TCP, or "unix://path" for a Unix socket, so the text can
517 : // be the host of another configuration. Gives ccol_success, ccol_invalid_args
518 : // for a bad handle, a NULL buf or a buflen of 0, ccol_not_permitted when the
519 : // server doesn't listen, or ccol_msg_too_large when the text doesn't fit; buf
520 : // holds "" on failure.
521 : ccol_retval chttpsvr_bound_address(chttpsvr srv, char *buf, size_t buflen);
522 :
523 : // Registers a buffered route on the root router: The server reads the whole
524 : // body, then runs fn(req, resp, ctx) on a worker thread. method is one of the
525 : // seven methods, or CHTTP_ANY for all of them; a route registered earlier for
526 : // one method wins over a later CHTTP_ANY on the same pattern. pattern starts
527 : // with '/' and may hold {name} parameters of [A-Za-z0-9_], each name once, with
528 : // no double or trailing slash. Gives ccol_success, ccol_not_enough_memory, or
529 : // ccol_invalid_args for a bad handle, method or pattern, or a NULL fn.
530 : ccol_retval chttpsvr_register_handler(chttpsvr srv, chttp_method method,
531 : const char *pattern,
532 : chttpsvr_handler_fn fn, void *ctx);
533 :
534 : // Registers a streaming route on the root router: fn(req, resp, ctx) runs on
535 : // the streaming pool right after the headers and reads the body with
536 : // chttpsvr_req_read() as it arrives. A request that finds no free streaming
537 : // thread waits in the streaming queue, and gets 503 when the queue is full or
538 : // its wait runs out. method is one of the seven methods, or CHTTP_ANY for all
539 : // of them. pattern starts with '/' and may hold {name} parameters of
540 : // [A-Za-z0-9_], each name once, with no double or trailing slash. Gives
541 : // ccol_success, ccol_not_enough_memory, or ccol_invalid_args for a bad handle,
542 : // method or pattern, or a NULL fn.
543 : ccol_retval chttpsvr_register_streaming_handler(chttpsvr srv,
544 : chttp_method method,
545 : const char *pattern,
546 : chttpsvr_handler_fn fn,
547 : void *ctx);
548 :
549 : // Adds global middleware to the root router. It runs, in registration order,
550 : // before every sub-router middleware and every handler. It also runs for the
551 : // 404, 405 and 413 rejections of the server, so an access log or a rate limiter
552 : // sees them; such a request has no path parameters and no body, and a
553 : // middleware that answers it itself is held to the 2-second write ceiling of
554 : // rejections. A 500, 501, 503 or 505, and a rejection sent inline, run no
555 : // middleware. Gives ccol_success, ccol_not_enough_memory, ccol_invalid_args for
556 : // a bad handle or a NULL fn, or ccol_not_permitted when the chain holds 32
557 : // entries.
558 : ccol_retval chttpsvr_use(chttpsvr srv, chttpsvr_middleware_fn fn, void *ctx);
559 :
560 : // Creates a sub-router for prefix, so a group of routes can share a prefix and
561 : // middleware. It owns every path equal to prefix or continuing it with '/'
562 : // (unless a more specific mount does): Such a request reaches its routes or
563 : // gets its 404 or 405, never a root-level route, and its middleware runs after
564 : // the global middleware. prefix starts with '/', has no double slash, and loses
565 : // a trailing slash. The prefix "/" owns the exact path "/" only, so it's the
566 : // wrong place for a guard meant for every path; use chttpsvr_use() for that.
567 : // The server owns the sub-router, so don't free it. Its pointer stays safe to
568 : // pass after a restart and after the server is destroyed (calls then give
569 : // ccol_invalid_args), because about 100 bytes of it live until the process
570 : // exits. Gives NULL for a bad handle or prefix, or when memory runs out.
571 : chttpsvr_router *chttpsvr_subrouter(chttpsvr srv, const char *prefix);
572 :
573 : // Registers a buffered route on a sub-router: The server reads the whole body,
574 : // then runs fn(req, resp, ctx) on a worker thread. The route matches the
575 : // router's prefix plus pattern, so "/api/v1" plus "/users/{id}" matches
576 : // "/api/v1/users/42". method is one of the seven methods, or CHTTP_ANY for all
577 : // of them. pattern starts with '/' and may hold {name} parameters of
578 : // [A-Za-z0-9_], each name once, with no double or trailing slash. Gives
579 : // ccol_success, ccol_not_enough_memory, or ccol_invalid_args for a NULL router,
580 : // pattern or fn, a bad method or pattern, or a router whose server is
581 : // destroyed.
582 : ccol_retval chttpsvr_router_register_handler(chttpsvr_router *router,
583 : chttp_method method,
584 : const char *pattern,
585 : chttpsvr_handler_fn fn, void *ctx);
586 :
587 : // Registers a streaming route on a sub-router: fn(req, resp, ctx) runs on the
588 : // streaming pool right after the headers and reads the body with
589 : // chttpsvr_req_read() as it arrives. The route matches the router's prefix
590 : // plus pattern, so "/api" plus "/upload" matches "/api/upload". method is one
591 : // of the seven methods, or CHTTP_ANY for all of them. pattern starts with '/'
592 : // and may hold {name} parameters of [A-Za-z0-9_], each name once, with no
593 : // double or trailing slash. Gives ccol_success, ccol_not_enough_memory, or
594 : // ccol_invalid_args for a NULL router, pattern or fn, a bad method or pattern,
595 : // or a router whose server is destroyed.
596 : ccol_retval chttpsvr_router_register_streaming_handler(chttpsvr_router *router,
597 : chttp_method method,
598 : const char *pattern,
599 : chttpsvr_handler_fn fn,
600 : void *ctx);
601 :
602 : // Adds middleware to a sub-router. It runs after the global middleware and
603 : // before the sub-router's handlers, in registration order. It also runs for the
604 : // 404, 405 and 413 rejections of the router's paths; such a request has no
605 : // path parameters and no body. Gives ccol_success, ccol_not_enough_memory,
606 : // ccol_invalid_args for a NULL router or fn or a destroyed server, or
607 : // ccol_not_permitted when the chain holds 32 entries.
608 : ccol_retval chttpsvr_router_use(chttpsvr_router *router,
609 : chttpsvr_middleware_fn fn, void *ctx);
610 :
611 : // Gives the request method, always one of the seven real methods, since the
612 : // server answers an unknown one with 501. It gives CHTTP_GET for a NULL req,
613 : // because the return type has no error value.
614 : chttp_method chttpsvr_req_method(const chttpsvr_req *req);
615 :
616 : // Gives the decoded request path that the routes matched. It always begins with
617 : // '/', and an absolute-form target gives the path of its URL. A rejected
618 : // request whose percent-encoding is malformed has no decoded form, so a
619 : // middleware gets that path as it arrived. "OPTIONS *" never reaches you: The
620 : // server answers it with 200 itself. The string lives as long as the request.
621 : const char *chttpsvr_req_path(const chttpsvr_req *req);
622 :
623 : // Tells whether the client presented a TLS certificate that verified against
624 : // the server's ca_bundle_path. With client_cert_optional a client may present
625 : // none, and this is how a handler tells the two kinds apart. It's false for
626 : // plain HTTP, a server without a bundle, a client without a certificate and a
627 : // NULL req. The answer belongs to the connection, so every request on it gets
628 : // the same one.
629 : bool chttpsvr_req_peer_cert_verified(const chttpsvr_req *req);
630 :
631 : // Length in bytes of the fingerprint chttpsvr_req_peer_cert_sha256() writes.
632 : #define CHTTPSVR_PEER_CERT_SHA256_LEN 32
633 :
634 : // Gives the DER bytes of the verified client certificate, so a handler can read
635 : // any field of it or compare it with a pinned one; *len_out (when len_out isn't
636 : // NULL) gets the length. Gives NULL and 0 whenever
637 : // chttpsvr_req_peer_cert_verified() is false, and when an allocation fails. The
638 : // bytes live as long as the request; don't free them.
639 : const void *chttpsvr_req_peer_cert_der(const chttpsvr_req *req,
640 : size_t *len_out);
641 :
642 : // Writes the SHA-256 fingerprint of the verified client certificate (of its DER
643 : // form, as openssl x509 -fingerprint -sha256 prints it) into out, so a handler
644 : // can check the client against a list. Gives ccol_success, ccol_key_not_found
645 : // when no certificate verified, ccol_not_enough_memory, or ccol_invalid_args
646 : // for a NULL req or out; out is all zeroes on failure.
647 : ccol_retval chttpsvr_req_peer_cert_sha256(
648 : const chttpsvr_req *req, unsigned char out[CHTTPSVR_PEER_CERT_SHA256_LEN]);
649 :
650 : // Gives the subject of the verified client certificate as an RFC 2253 name,
651 : // such as "CN=alice,OU=staff,O=Example", with every non-printable or reserved
652 : // byte escaped; compare it as a whole string. Gives NULL when no certificate
653 : // verified or an allocation fails. The string lives as long as the request.
654 : const char *chttpsvr_req_peer_cert_subject(const chttpsvr_req *req);
655 :
656 : // Gives the value of the request header name, compared without case, or NULL
657 : // when it's absent; for a repeated header it gives the last value. Trailers of
658 : // a chunked body are never returned, so a trailer can't displace a header a
659 : // proxy set. The pointer is valid only during the handler call.
660 : const char *chttpsvr_req_header(const chttpsvr_req *req, const char *name);
661 :
662 : // Gives the body of a buffered route, with its length in *len_out (when len_out
663 : // isn't NULL). The bytes don't end with a NUL. Gives NULL for an empty body,
664 : // and NULL with a length of 0 on a streaming route, which reads with
665 : // chttpsvr_req_read(). The pointer lives as long as the request.
666 : const void *chttpsvr_req_body(const chttpsvr_req *req, size_t *len_out);
667 :
668 : // Reads up to buflen bytes of the body on a streaming route, so a handler can
669 : // process an upload as it arrives. It gives what the connection has on hand (at
670 : // most one 8 KiB socket read) and blocks the calling streaming thread only when
671 : // there's nothing, until data comes, the body ends, an error happens or a limit
672 : // passes (stream_read_timeout_us, max_body_read_duration_us,
673 : // min_transfer_rate_bps). The first call for a request with "Expect:
674 : // 100-continue" and a body sends the interim "100 Continue", so a handler that
675 : // answers without reading never invites the upload. Gives the byte count, 0 at
676 : // the end of the body or for a buflen of 0, or -1. A -1 comes from misuse (a
677 : // NULL req, a NULL buf with buflen above 0, a buffered route) or from a
678 : // transfer error; chttpsvr_req_stream_error() tells which.
679 : ssize_t chttpsvr_req_read(chttpsvr_req *req, void *buf, size_t buflen);
680 :
681 : // Tells why the last chttpsvr_req_read() returned -1; it means something only
682 : // right after that call. Gives ccol_timed_out for an expired limit or a rate
683 : // below the floor, ccol_msg_too_large past max_body_size,
684 : // ccol_not_enough_memory when the body buffer couldn't grow,
685 : // ccol_http_transfer_aborted for a closed connection or bad framing,
686 : // ccol_invalid_args for a NULL or unknown req, and ccol_success when nothing
687 : // was recorded. ccol_success is also the answer for a NULL buf and for a
688 : // buffered route, because both are programming errors that every call of the
689 : // faulty code hits.
690 : ccol_retval chttpsvr_req_stream_error(const chttpsvr_req *req);
691 :
692 : // Gives the decoded value of the path parameter name (written without braces)
693 : // of the matched route, so /users/{id} on /users/42 gives "42", or NULL when
694 : // the route has no such parameter. The string lives as long as the request.
695 : const char *chttpsvr_req_param(const chttpsvr_req *req, const char *name);
696 :
697 : // Gives every value of the query key, so ?foo=1&foo=2 gives {"1", "2"}, as a
698 : // NULL-terminated array with the count in *count_out (when count_out isn't
699 : // NULL), or NULL when the key is absent. key is compared with each decoded key,
700 : // as Go's url.Values does, and a pair with a malformed escape or an escaped NUL
701 : // is skipped. The strings live as long as the request, but the next call on the
702 : // same request reuses the array. NULL also comes from a failed allocation;
703 : // chttpsvr_req_query_oom() tells the two apart.
704 : const char **chttpsvr_req_query(chttpsvr_req *req, const char *key,
705 : size_t *count_out);
706 :
707 : // Gives the single value of the query key in *val_out, for a key that must
708 : // appear once. Gives ccol_success, ccol_key_not_found when the key is absent,
709 : // ccol_key_already_present when it repeats, ccol_not_enough_memory, or
710 : // ccol_invalid_args for a NULL req or key; *val_out is NULL on failure.
711 : ccol_retval chttpsvr_req_query_one(chttpsvr_req *req, const char *key,
712 : const char **val_out);
713 :
714 : // Gives the query string as it came, still encoded (for /search?q=a%20b&page=2
715 : // that's "q=a%20b&page=2"), or NULL when there's none.
716 : const char *chttpsvr_req_raw_query(const chttpsvr_req *req);
717 :
718 : // Tells whether parsing this request's query string, or growing a
719 : // chttpsvr_req_query() result, ran out of memory, since chttpsvr_req_query()
720 : // gives NULL both for that and for an absent key. Once set, the flag stays set
721 : // for the rest of the request. Gives false for a NULL req.
722 : bool chttpsvr_req_query_oom(const chttpsvr_req *req);
723 :
724 : // Attaches value to the request under key, so a middleware can hand what it
725 : // found (an identity, a trace id) to later middleware and the handler. Keys
726 : // compare by address, as with Go's context.WithValue, so use the address of a
727 : // static object of your module. A second call with the same key replaces the
728 : // value. The values belong to one request and are forgotten when its chain
729 : // returns; the library never frees or reads them. Call it only on the thread
730 : // that runs the chain, because it takes no lock. The first value needs no
731 : // allocation. Gives ccol_success, ccol_invalid_args for a NULL req or key, or
732 : // ccol_not_enough_memory (the earlier values stay).
733 : ccol_retval chttpsvr_req_set_context(chttpsvr_req *req, const void *key,
734 : void *value);
735 :
736 : // Gives the value that chttpsvr_req_set_context() attached under key, or NULL
737 : // when there's none or req or key is NULL. A stored NULL also gives NULL.
738 : void *chttpsvr_req_context(const chttpsvr_req *req, const void *key);
739 :
740 : // Sets the response status (200 by default). A value outside 200 to 999, a 1xx
741 : // included, goes out as 500, because a client takes a 1xx as interim and keeps
742 : // waiting. A 204, 205 or 304 drops any body written before or after. The reason
743 : // phrase comes from the IANA registry.
744 : void chttpsvr_resp_set_status(chttpsvr_resp *resp, int status_code);
745 :
746 : // Sets a response header, replacing every field of the same name (compared
747 : // without case), so the response carries exactly one; the spelling and position
748 : // of the first call stay. Fields go out in the order they were first set, and
749 : // the server adds no Content-Type of its own. name must be a non-empty RFC 7230
750 : // token and value must hold no control byte other than the tab, so reflected
751 : // data can't inject header lines. Connection is stored but never sent, because
752 : // the server writes its own. Content-Length must be digits: A response with a
753 : // body carries the real body length instead, a 304 or a HEAD without a body
754 : // carries yours, a 205 carries 0 and a 204 none. A Date you set replaces the
755 : // server's. Transfer-Encoding is refused. Gives ccol_success,
756 : // ccol_not_enough_memory, or ccol_invalid_args for a NULL argument or a refused
757 : // name or value; a failed call changes nothing.
758 : ccol_retval chttpsvr_resp_set_header(chttpsvr_resp *resp, const char *name,
759 : const char *value);
760 :
761 : // Adds one more header field after the existing ones and keeps fields of the
762 : // same name, so a response can carry two Set-Cookie lines. name must be a
763 : // non-empty RFC 7230 token and value must hold no control byte other than the
764 : // tab; Transfer-Encoding is refused. Connection, Content-Length and Date stay
765 : // single: Adding one replaces the earlier field. Gives ccol_success,
766 : // ccol_not_enough_memory, or ccol_invalid_args for a NULL argument or a refused
767 : // name or value; a failed call changes nothing.
768 : ccol_retval chttpsvr_resp_add_header(chttpsvr_resp *resp, const char *name,
769 : const char *value);
770 :
771 : // Appends len bytes of data to the response body, which the server sends after
772 : // the handler returns. A final status of 204, 205 or 304 drops the body
773 : // silently, with no error anywhere. Gives ccol_success, ccol_invalid_args for a
774 : // NULL resp or a NULL data with len above 0, or ccol_not_enough_memory.
775 : ccol_retval chttpsvr_resp_write(chttpsvr_resp *resp, const void *data,
776 : size_t len);
777 :
778 : // Appends the NUL-terminated string str, without its NUL, to the response body,
779 : // which the server sends after the handler returns. A final status of 204, 205
780 : // or 304 drops the body. Gives ccol_success, ccol_invalid_args for a NULL resp
781 : // or str, or ccol_not_enough_memory.
782 : ccol_retval chttpsvr_resp_write_str(chttpsvr_resp *resp, const char *str);
783 :
784 : // Formats fmt and its arguments with the rules of printf() and appends the
785 : // result to the response body, which the server sends after the handler
786 : // returns. A final status of 204, 205 or 304 drops the body. Gives
787 : // ccol_success, ccol_invalid_args for a NULL resp or fmt or when the formatting
788 : // fails, or ccol_not_enough_memory.
789 : ccol_retval chttpsvr_resp_printf(chttpsvr_resp *resp, const char *fmt, ...)
790 : __attribute__((format(printf, 2, 3)));
791 :
792 : // Appends len bytes of json to the body and sets Content-Type to
793 : // application/json. The body goes first, so a failed body allocation changes
794 : // nothing, while a header set that fails after it leaves the body written and
795 : // gives ccol_not_enough_memory. A NULL resp or json, or a len of 0, gives
796 : // ccol_invalid_args.
797 : ccol_retval chttpsvr_resp_write_json(chttpsvr_resp *resp, const char *json,
798 : size_t len);
799 :
800 : #pragma GCC visibility pop
|