LCOV - code coverage report
Current view: top level - src - chttpserver.c (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 92.6 % 6130 5679
Test Date: 2026-11-15 18:57:05 Functions: 99.0 % 402 398
Legend: Lines: hit not hit

            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              : // The GNU extensions give us accept4() and the other Linux socket calls.
      26              : #ifndef _GNU_SOURCE
      27              : #define _GNU_SOURCE
      28              : #endif
      29              : 
      30              : #include <arpa/inet.h>
      31              : #include <chttpserver.h>
      32              : #include <cthreadcomm.h>
      33              : #include <cthreadpool.h>
      34              : #include <cvector.h>
      35              : #include <errno.h>
      36              : #include <fcntl.h>
      37              : #include <internal/catfork.h>
      38              : #include <internal/cdeadline.h>
      39              : #include <internal/chttp1_parser.h>
      40              : #include <internal/csock.h>
      41              : #include <internal/cstrutil.h>
      42              : #include <internal/ctls.h>
      43              : #include <internal/test_helpers/chttpserver.h>
      44              : #include <internal/test_helpers/common.h>
      45              : #include <internal/test_helpers/cthreadpool.h>
      46              : #include <limits.h>
      47              : #if defined(__linux__)
      48              : #include <linux/sockios.h>
      49              : #endif
      50              : #include <internal/cascii.h>
      51              : #include <internal/clogderive.h>
      52              : #include <internal/ctlsmodel.h>
      53              : #include <netdb.h>
      54              : #include <netinet/in.h>
      55              : #include <netinet/tcp.h>
      56              : #include <signal.h>
      57              : #include <stdarg.h>
      58              : #include <stdatomic.h>
      59              : #include <stdio.h>
      60              : #include <stdlib.h>
      61              : #include <string.h>
      62              : #include <sys/ioctl.h>
      63              : #include <sys/socket.h>
      64              : #include <sys/stat.h>
      65              : #include <sys/un.h>
      66              : #include <time.h>
      67              : #include <unistd.h>
      68              : 
      69              : typedef struct chttpsvr_mw_node chttpsvr_mw_node;
      70              : 
      71              : // One middleware entry of a router's singly linked list. next is a plain
      72              : // pointer: Readers walk the list under the read lock of routes_lock and writers
      73              : // append under the write lock, so the lock orders the two sides.
      74              : struct chttpsvr_mw_node {
      75              :   chttpsvr_middleware_fn fn;
      76              :   void *ctx;
      77              :   chttpsvr_mw_node *next;
      78              : };
      79              : 
      80              : // A compiled route: The pattern split into segments, the names of its {name}
      81              : // segments, and the handler to call.
      82              : typedef struct chttpsvr_route {
      83              :   chttp_method method;
      84              :   char **segs;
      85              :   int seg_count;
      86              :   char **param_names;
      87              :   int param_count;
      88              :   chttpsvr_handler_fn fn;
      89              :   void *ctx;
      90              :   bool is_streaming;
      91              : } chttpsvr_route;
      92              : 
      93              : // A sub-router, and the root router of a server (prefix ""). The struct itself,
      94              : // the "shell", is never freed while a caller can hold a pointer to it, because
      95              : // chttpsvr_router_register_handler, _on_stream and _use read owner before any
      96              : // resolve or pin can protect them. destroy_router frees only the contents
      97              : // (routes, mw nodes, prefix) and stores CHTTPSVR_NULL in owner. The shell of a
      98              : // root router goes away with its server, and after the registry's exit-time
      99              : // destructor has run every shell of a destroyed server is freed too.
     100              : struct chttpsvr_router {
     101              :   char *prefix;
     102              :   size_t prefix_len;
     103              :   // How many '/'-separated segments the prefix has (0 for the root and for
     104              :   // "/"). find_route orders the sub-routers by it, and it bounds the shared
     105              :   // decode cache through max_prefix_seg_count of the server.
     106              :   int prefix_seg_count;
     107              :   chttpsvr_mw_node *mw_head;
     108              :   chttpsvr_mw_node *mw_tail;
     109              :   int mw_count;
     110              :   // Each route is its own allocation, so a route pointer stays valid when the
     111              :   // array grows.
     112              :   chttpsvr_route **routes;
     113              :   size_t route_count;
     114              :   size_t route_cap;
     115              :   // The largest seg_count of this router's routes. Routes are only ever added,
     116              :   // so a running maximum is always right. It bounds how many segments of a
     117              :   // request path, which the client controls, the decode cache of find_route
     118              :   // splits.
     119              :   int max_route_seg_count;
     120              :   // The server's allocator serves only the contents of the router, never the
     121              :   // shell. The public router calls must resolve owner before they read srv.
     122              :   struct chttpserver *srv;
     123              :   ccol_memmgmt_procs *m_procs;
     124              :   // The handle of the owning server, or CHTTPSVR_NULL once that server is gone.
     125              :   // It's atomic because destroy_router writes it with no lock a reader holds.
     126              :   // shell_idx is the shell's position in the shell registry (SIZE_MAX when the
     127              :   // registry doesn't hold it), guarded by the registry mutex.
     128              :   _Atomic chttpsvr owner;
     129              :   size_t shell_idx;
     130              : };
     131              : 
     132              : // One response header in the flat headers array.
     133              : typedef struct {
     134              :   char *name;
     135              :   char *value;
     136              : } resp_header;
     137              : 
     138              : // The response a handler builds. The headers live in a flat array that grows to
     139              : // 2x+8, so a duplicate scan stays cache friendly and a header costs no node
     140              : // allocation.
     141              : struct chttpsvr_resp {
     142              :   int status_code;
     143              :   resp_header *headers;
     144              :   size_t header_count;
     145              :   size_t header_cap;
     146              :   char *body;
     147              :   size_t body_len;
     148              :   size_t body_cap;
     149              :   ccol_memmgmt_procs *m_procs;
     150              : };
     151              : 
     152              : // The query parameters, parsed on first use. Keys and values are URL-decoded
     153              : // copies that the struct owns.
     154              : typedef struct chttpsvr_qparams {
     155              :   char **keys;
     156              :   char **values;
     157              :   size_t count;
     158              :   size_t cap;
     159              :   ccol_memmgmt_procs *m_procs;
     160              : } chttpsvr_qparams;
     161              : 
     162              : // How many middleware steps one request may go through, global and router steps
     163              : // together. The per-request snapshot in dispatch_ctx is a fixed array of this
     164              : // size, so a request costs no allocation for it; a request that needs more gets
     165              : // a 500.
     166              : #define CHTTPSVR_MAX_MW 32
     167              : 
     168              : // The Retry-After value of every 503 the server sends on its own (full pools,
     169              : // streaming queue timeout, body memory wait timeout). Five seconds covers
     170              : // several sweep ticks, so a client that honours it doesn't walk straight back
     171              : // into the same saturation.
     172              : #define CHTTPSVR_RETRY_AFTER_SECONDS "5"
     173              : 
     174              : // Defaults of the slow-client settings of chttpsvr_config. 240 bytes a second
     175              : // after a five-second grace is the minimum data rate Kestrel and IIS use.
     176              : #define CHTTPSVR_DEFAULT_MIN_RATE_BPS 240u
     177              : #define CHTTPSVR_DEFAULT_RATE_GRACE_MS 5000u
     178              : #define CHTTPSVR_DEFAULT_PARTIAL_BODY_MEMORY ((size_t)256 * 1024 * 1024)
     179              : #define CHTTPSVR_DEFAULT_MEMORY_WAIT_MS 30000u
     180              : #define CHTTPSVR_DEFAULT_STREAM_QUEUE_TIMEOUT_MS 5000u
     181              : 
     182              : // A hard cap, in ms, on the total time of a write the library makes itself: A
     183              : // rejection response or the "100 Continue" interim line. It applies whatever
     184              : // max_response_write_duration_ms says, because that knob can be 0 and a peer
     185              : // reading one byte at a time could otherwise keep such a write, its descriptor
     186              : // and its parked state alive for ever. On a streaming route it also bounds the
     187              : // wait for the interim line inside chttpsvr_req_read().
     188              : #define CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS 2000
     189              : 
     190              : #ifdef RUNNING_UNIT_TESTS
     191              : // Test override of the internal write ceiling, so a client that reads a large
     192              : // rejection slowly (under valgrind, say) gets all of it. 0 means the default.
     193              : static _Atomic unsigned g_internal_write_ceiling_ms_for_tests;
     194              : // Sets the test override of the internal write ceiling to ms (0 goes back to
     195              : // the default). Tests that check what a parked rejection does, not how long it
     196              : // may last, need a higher ceiling so a slow reader gets the whole response. It
     197              : // stores into g_internal_write_ceiling_ms_for_tests.
     198            2 : void chttpsvr__set_internal_write_ceiling_ms_for_tests(unsigned ms) {
     199            2 :   atomic_store(&g_internal_write_ceiling_ms_for_tests, ms);
     200            2 : }
     201              : // Returns the internal write ceiling in ms. The rejection and interim-line
     202              : // writes take their total deadline from it, so tests can raise it. It reads
     203              : // g_internal_write_ceiling_ms_for_tests and returns
     204              : // CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS when that is 0.
     205          635 : static inline unsigned internal_write_ceiling_ms(void) {
     206          635 :   unsigned ms = atomic_load(&g_internal_write_ceiling_ms_for_tests);
     207          316 :   return ms ? ms : CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS;
     208              : }
     209              : #else
     210              : // Without the test hooks this takes no arguments and evaluates to
     211              : // CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS, so the callers of
     212              : // internal_write_ceiling_ms() build the same way in both configurations. It
     213              : // reads and changes no state.
     214              : #define internal_write_ceiling_ms() CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS
     215              : #endif
     216              : 
     217              : // The fewest threads reject_pool gets. chttpsvr_start sizes it as the larger of
     218              : // this and half of worker_pool's thread count, because every rejection (404,
     219              : // 405, 500, a 503 for a full pool) goes through it and a burst of unmatched
     220              : // routes needs real concurrency to drain.
     221              : #define CHTTPSVR_REJECT_POOL_MIN_THREADS 2
     222              : 
     223              : // The queue capacity of reject_pool. A bound keeps an endless flood of rejected
     224              : // connections from growing our own memory without limit. When the queue is
     225              : // full, conn_reject_via_pool closes the connection on the calling thread.
     226              : #define CHTTPSVR_REJECT_POOL_QUEUE_CAP 1024
     227              : 
     228              : // One middleware step of the per-request snapshot.
     229              : typedef struct {
     230              :   chttpsvr_middleware_fn fn;
     231              :   void *ctx;
     232              : } mw_entry;
     233              : 
     234              : // Middleware dispatch state. It lives inside chttpsvr_conn, so it costs no
     235              : // allocation and is reset for each request like the other scratch fields. The
     236              : // snapshot of fn and ctx pairs is copied under routes_lock.
     237              : typedef struct dispatch_ctx {
     238              :   struct chttpserver *srv;
     239              :   chttpsvr_router *router;
     240              :   chttpsvr_route *route;
     241              :   mw_entry mw_snap[CHTTPSVR_MAX_MW];
     242              :   int mw_count;
     243              :   int mw_idx;
     244              : } dispatch_ctx;
     245              : 
     246              : // A small growable buffer. A buffered route collects the whole body in it. A
     247              : // streaming route keeps in it the body bytes chttpsvr_req_read hasn't handed
     248              : // out yet; pos is how many of the len bytes it already gave.
     249              : typedef struct {
     250              :   char *buf;
     251              :   size_t cap;
     252              :   size_t len;
     253              :   size_t pos;
     254              : } growbuf;
     255              : 
     256              : // Who owns a connection and what it waits for. In CONN_ST_DIVERTED a worker
     257              : // owns the fd and the reactor registration is paused, never removed, so the
     258              : // next request can resume it cheaply.
     259              : typedef enum {
     260              :   CONN_ST_TLS_HANDSHAKE,
     261              :   CONN_ST_READING_HEADERS,
     262              :   CONN_ST_DIVERTED,
     263              :   CONN_ST_CLOSING
     264              : } conn_state;
     265              : 
     266              : // One accepted connection. It lives across all the keep-alive requests of the
     267              : // connection, and conn_reset_for_request() clears the per-request scratch
     268              : // fields before each request. Either the reactor registration or a worker task
     269              : // owns it, never both at once.
     270              : typedef struct chttpsvr_conn {
     271              :   int fd;
     272              :   struct chttpserver *srv;
     273              :   ceventloop_reg reg;
     274              :   ctls_conn *tls;
     275              :   conn_state state;
     276              :   chttp1_parser parser;
     277              : 
     278              :   // Per-request scratch fields. path is the raw, percent-encoded path: Matching
     279              :   // splits on a literal '/' and decodes each segment on its own, so a %2F
     280              :   // inside a {param} stays one segment and a bad %XX in one segment is a 404,
     281              :   // not a 400. decoded_path is filled once a route matched and is what
     282              :   // chttpsvr_req_path() returns.
     283              :   chttp_method method;
     284              :   char *path;
     285              :   char *decoded_path;
     286              :   char *raw_query;
     287              :   char **hdr_names, **hdr_values;
     288              :   size_t hdr_count, hdr_cap;
     289              :   chttpsvr_router *matched_router;
     290              :   chttpsvr_route *matched_route;
     291              :   char **matched_param_values;
     292              :   dispatch_ctx dispatch;
     293              :   chttpsvr_resp resp;
     294              :   // allowed_methods feeds the Allow header of a 405. options_star marks an
     295              :   // "OPTIONS *" request, which the server answers itself.
     296              :   bool req_rejected;
     297              :   int reject_status;
     298              :   uint8_t allowed_methods;
     299              :   bool options_star;
     300              :   // interim_continue_sent keeps the "100 Continue" line from going out twice.
     301              :   // interim_write_failed means part of it went out, so anything written after
     302              :   // it would break the client's framing; the connection is closed instead.
     303              :   bool expects_continue;
     304              :   bool interim_continue_sent;
     305              :   bool interim_write_failed;
     306              :   // The body and why reading it stopped. body_alloc_failed is a real allocation
     307              :   // failure (ccol_not_enough_memory for a streaming route), transfer_aborted an
     308              :   // EOF or I/O error seen by chttpsvr_req_read(), and body_malformed a framing
     309              :   // error or a short body on a buffered route, which gets a 400 and not a 500.
     310              :   // chttpsvr_req_stream_error() checks body_too_large and body_alloc_failed
     311              :   // first.
     312              :   growbuf body;
     313              :   size_t body_bytes_seen;
     314              :   bool body_too_large;
     315              :   bool body_alloc_failed;
     316              :   bool transfer_aborted;
     317              :   bool body_malformed;
     318              : 
     319              :   // Bytes past the headers in the reactor's read buffer. That buffer is on the
     320              :   // reactor thread's stack, so conn_start_diverted copies them out, and the
     321              :   // worker frees them once its stream has taken them.
     322              :   char *carry_over;
     323              :   size_t carry_over_len;
     324              : 
     325              :   // Deadline of max_body_read_duration_ms.
     326              :   struct timespec read_deadline;
     327              :   bool read_deadline_set;
     328              :   bool deadline_exceeded;
     329              : 
     330              :   // Deadline of max_response_write_duration_ms, read by the real response, a
     331              :   // rejection and the interim line (the last two are also capped by the
     332              :   // internal write ceiling).
     333              :   struct timespec write_deadline;
     334              :   bool write_deadline_set;
     335              : 
     336              :   // Idle list links for the idle sweep; srv->idle_mutex guards them.
     337              :   struct timespec last_activity;
     338              :   struct chttpsvr_conn *idle_prev, *idle_next;
     339              :   bool in_idle_list;
     340              : 
     341              :   // Diverted list links, guarded by srv->diverted_mutex. A teardown finds the
     342              :   // connection of a stuck worker here and forces a shutdown(2) on it.
     343              :   struct chttpsvr_conn *diverted_prev, *diverted_next;
     344              :   bool in_diverted_list;
     345              : 
     346              :   // 1 until conn_close, plus 1 for every registration created for this
     347              :   // connection until its on_removed fires. A connection can go through several
     348              :   // registrations (a failed pause removes one and a later wait adds another),
     349              :   // so conn_free runs only when every one of them, and the close, has dropped
     350              :   // its reference.
     351              :   _Atomic int lifetime_refs;
     352              : 
     353              :   ccol_memmgmt_procs *m_procs;
     354              : 
     355              :   // Start of the reactor-owned phase of the current request (handshake or first
     356              :   // header byte), for max_header_read_duration_ms. Written only while the
     357              :   // connection is out of the idle list, read by the sweep under
     358              :   // srv->idle_mutex.
     359              :   struct timespec header_phase_start;
     360              :   bool header_phase_active;
     361              : 
     362              :   // Slow-client state; for a buffered route a worker never waits on the socket.
     363              :   // divert_gate is 0 for an ordinary divert, SIZE_MAX for a streaming route,
     364              :   // and otherwise the Content-Length of a buffered body that has to reserve
     365              :   // memory.
     366              :   size_t divert_gate;
     367              : 
     368              :   // The CONN_PARK_* wait the connection is in while no thread owns it, written
     369              :   // before it's published to a list and read by the thread that claims it back.
     370              :   // park_pending is the wait a worker is about to enter. reg_dir is the
     371              :   // direction reg was last armed for, so conn_reg_modify skips a call that
     372              :   // changes nothing.
     373              :   uint8_t park;
     374              :   uint8_t park_pending;
     375              :   uint8_t reg_dir;
     376              : 
     377              :   // Rate floor and per-gap limit of a parked transfer, on slow_clock.
     378              :   // rate_paused_ms is time the server itself held the request back. rate_queued
     379              :   // is the unread byte count the sweep last saw while the receive low-water
     380              :   // mark was above 1. rcvlowat is the current SO_RCVLOWAT and rcvlowat_cap the
     381              :   // highest the buffer allows (read on the first park).
     382              :   bool rate_active;
     383              :   struct timespec rate_start;
     384              :   long long rate_paused_ms;
     385              :   uint64_t rate_bytes;
     386              :   struct timespec last_progress;
     387              :   size_t rate_queued;
     388              :   int rcvlowat;
     389              :   int rcvlowat_cap;
     390              : 
     391              :   // Partial-body memory. Once the connection holds a charge or waits,
     392              :   // srv->wait_mutex guards this group. mem_charged lasts until conn_drop_body
     393              :   // frees the body; mem_exempt means it went past the limit under the progress
     394              :   // rule; mem_need is what a waiter asks for.
     395              :   size_t mem_charged;
     396              :   size_t mem_need;
     397              :   bool mem_exempt;
     398              :   bool in_mem_wait;
     399              :   struct timespec mem_wait_start;
     400              :   struct chttpsvr_conn *mem_prev, *mem_next;
     401              : 
     402              :   // When a parked connection went to the worker pool, on CLOCK_MONOTONIC and
     403              :   // slow_clock. task_resume judges the limits at this instant, so time spent in
     404              :   // the pool's queue is charged to the server.
     405              :   struct timespec claim_mono;
     406              :   struct timespec claim_slow;
     407              : 
     408              :   // Streaming queue links and deadline; srv->wait_mutex guards them.
     409              :   bool in_stream_queue;
     410              :   bool sq_has_deadline;
     411              :   struct timespec sq_deadline;
     412              :   struct chttpsvr_conn *sq_prev, *sq_next;
     413              : 
     414              :   // A response whose write stopped on a full socket. wp_head holds the unsent
     415              :   // part of the header block and wp_body_pos how much body went out.
     416              :   // wp_wants_read means TLS needs to read first, wp_reject marks a rejection
     417              :   // (it ends in a close), and wp_interim marks the interim line of a buffered
     418              :   // route. wp_outq is the smallest SIOCOUTQ seen (SIZE_MAX if unknown); a
     419              :   // shrinking send queue counts as progress.
     420              :   bool wp_active;
     421              :   bool wp_keep_alive;
     422              :   bool wp_no_body;
     423              :   bool wp_wants_read;
     424              :   bool wp_reject;
     425              :   bool wp_interim;
     426              :   char *wp_head;
     427              :   size_t wp_head_len;
     428              :   size_t wp_head_pos;
     429              :   size_t wp_body_pos;
     430              :   size_t wp_outq;
     431              : 
     432              :   // Parked list links, guarded by srv->idle_mutex.
     433              :   struct chttpsvr_conn *parked_prev, *parked_next;
     434              :   bool in_parked_list;
     435              : 
     436              :   // End of a lingering close, on CLOCK_MONOTONIC.
     437              :   struct timespec linger_deadline;
     438              : } chttpsvr_conn;
     439              : 
     440              : // The waits of chttpsvr_conn.park. BODY, WRITE and LINGER sit on the parked
     441              : // list with the registration armed. The two memory waits sit on the memory-wait
     442              : // list and STREAM on the streaming queue, all three with the registration
     443              : // paused.
     444              : enum {
     445              :   CONN_PARK_NONE = 0,
     446              :   CONN_PARK_BODY = 1,
     447              :   CONN_PARK_WRITE = 2,
     448              :   CONN_PARK_MEM_START = 3,
     449              :   CONN_PARK_MEM_BODY = 4,
     450              :   CONN_PARK_STREAM = 5,
     451              :   CONN_PARK_LINGER = 6
     452              : };
     453              : 
     454              : // One chttpsvr_req_set_context() value. A pair holding a value never has a NULL
     455              : // key.
     456              : typedef struct {
     457              :   const void *key;
     458              :   void *value;
     459              : } chttpsvr_ctx_pair;
     460              : 
     461              : // The context values after the first one, in a block that doubles as it grows.
     462              : typedef struct {
     463              :   size_t count;
     464              :   size_t cap;
     465              :   chttpsvr_ctx_pair pairs[];
     466              : } chttpsvr_ctx_more;
     467              : 
     468              : // What a handler or middleware gets: A view over the connection plus the
     469              : // worker's own chttp1_stream, which exists only while one worker drives one
     470              : // request. The first context value is stored inline (key NULL while there is
     471              : // none); the rest go into ctx_more, which destroy_req_scratch frees.
     472              : struct chttpsvr_req {
     473              :   chttpsvr_conn *conn;
     474              :   chttp1_stream *stream;
     475              :   const char **param_names;
     476              :   chttpsvr_qparams *qparams;
     477              :   const char **qresult;
     478              :   size_t qresult_cap;
     479              :   ccol_memmgmt_procs *m_procs;
     480              :   chttpsvr_ctx_pair ctx_first;
     481              :   chttpsvr_ctx_more *ctx_more;
     482              :   bool qparams_attempted;
     483              :   bool qparams_parse_oom;
     484              :   bool qresult_oom;
     485              : };
     486              : 
     487              : // One slot of the handle table. A chttpsvr handle holds the slot index in its
     488              : // top 32 bits and the generation in the bottom 32. The generation goes up on
     489              : // every acquire, so a stale handle never matches a later server in the same
     490              : // slot and a double destroy is a fatal error instead of a use-after-free.
     491              : typedef struct {
     492              :   struct chttpserver *ptr;
     493              :   uint32_t generation;
     494              :   bool in_use;
     495              : } chttpsvr_slot;
     496              : 
     497              : // The handle slot table, set up once by chttpsvr_slot_table_init_globals. slots
     498              : // only grows, free_indices is a LIFO free list, and release_deferred says the
     499              : // exit-time destructor found a live server and left the release to the destroy
     500              : // of the last one.
     501              : static struct {
     502              :   ccol__mutex mutex;
     503              :   ccol__once_flag once;
     504              :   cvec slots;
     505              :   bool release_deferred;
     506              :   cvec free_indices;
     507              : } chttpsvr_slot_table = {0};
     508              : 
     509              : // Set when a thread enters chttpsvr_slot_table_init_globals. The exit-time
     510              : // destructor uses it to skip a process that never touched this module, because
     511              : // the init also builds the tables of clogger and cthreadpool, whose destructors
     512              : // may have run already.
     513              : static atomic_bool chttpsvr_slot_table_entered = false;
     514              : 
     515              : #if CCOL_FORK_SAFETY_REQUIRED
     516              : static void chttpsvr_atfork_prepare(void);
     517              : static void chttpsvr_atfork_release(void);
     518              : static void chttpsvr_atfork_child_release(void);
     519              : #endif
     520              : 
     521              : // Creates the slot table and registers the fork handlers. It runs once, through
     522              : // chttpsvr_slot_table.once, before any path creates or resolves a server,
     523              : // because every handle lookup needs the table. It sets
     524              : // chttpsvr_slot_table_entered, initializes the table's mutex and vectors, and
     525              : // ends the process if any of that fails. The handlers of cthreadcomm,
     526              : // cthreadpool and clogger are forced to register first: Prepare handlers run in
     527              : // reverse order, so ours runs first and takes our locks before theirs, which is
     528              : // the order every ordinary call nests them in (engine_acquire holds
     529              : // srv_engine_bundler.mutex while it creates the event loop and the logger).
     530              : // Left to the order of first use, the two orders can disagree and fork time
     531              : // sees a lock-order cycle.
     532            6 : static void chttpsvr_slot_table_init_globals(void) {
     533            6 :   atomic_store(&chttpsvr_slot_table_entered, true);
     534            6 :   if (ccol__mutex_init(chttpsvr_slot_table.mutex) != 0)
     535            0 :     ccol__fatal_err("chttpsvr slot table: failed to initialize mutex");
     536            6 :   chttpsvr_slot_table.slots = cvector_create(sizeof(chttpsvr_slot), NULL);
     537            6 :   if (!chttpsvr_slot_table.slots)
     538            0 :     ccol__fatal_err("chttpsvr slot table: failed to allocate slots vector");
     539            6 :   chttpsvr_slot_table.free_indices = cvector_create(sizeof(uint32_t), NULL);
     540            6 :   if (!chttpsvr_slot_table.free_indices)
     541            0 :     ccol__fatal_err(
     542              :         "chttpsvr slot table: failed to allocate free-index vector");
     543              : #if CCOL_FORK_SAFETY_REQUIRED
     544            6 :   cthreadcomm__ensure_atfork_registered_before_caller();
     545            6 :   cthrpool__ensure_atfork_registered_before_caller();
     546            6 :   clog__ensure_atfork_registered_before_caller();
     547            6 :   ccol__at_fork(chttpsvr_atfork_prepare, chttpsvr_atfork_release,
     548              :                 chttpsvr_atfork_child_release);
     549              : #endif
     550            6 : }
     551              : 
     552              : #if defined(CCOL__ATFORK_AT_LOAD)
     553              : // Runs the slot table init, and so the fork handler registration, when the
     554              : // library loads. On systems that set CCOL__ATFORK_AT_LOAD a lazy
     555              : // pthread_atfork() can hang in a forked child, so the handlers must be
     556              : // registered before any thread starts. It goes through
     557              : // chttpsvr_slot_table.once, so a later lazy call does nothing.
     558              : __attribute__((constructor)) static void chttpsvr_atfork_at_load(void) {
     559              :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
     560              : }
     561              : #endif
     562              : 
     563              : // Start/stop state of a server; srv->mutex guards it. STARTING spans a whole
     564              : // chttpsvr_start() so a second concurrent start can't create pools and swap the
     565              : // TLS context under the first. STOPPING spans the removal and close of the old
     566              : // listener, so a start can't bind the same port while the old fd is open. Every
     567              : // reader uses a switch with no default, so -Wswitch catches a new value.
     568              : typedef enum {
     569              :   CHTTPSVR_LC_IDLE = 0,
     570              :   CHTTPSVR_LC_STARTING = 1,
     571              :   CHTTPSVR_LC_RUNNING = 2,
     572              :   CHTTPSVR_LC_STOPPING = 3,
     573              : } chttpsvr_lifecycle;
     574              : 
     575              : // The one-shot quiesce latch of quiesce_server_once(). It's separate from the
     576              : // lifecycle so the claim of a teardown doesn't depend on start/stop. A loser
     577              : // waits for QUIESCED, not QUIESCING, because chttpsvr__destroy frees the server
     578              : // right after the call returns. Only a later chttpsvr_start() resets it.
     579              : typedef enum {
     580              :   CHTTPSVR_QS_NOT_QUIESCED = 0,
     581              :   CHTTPSVR_QS_QUIESCING = 1,
     582              :   CHTTPSVR_QS_QUIESCED = 2,
     583              : } chttpsvr_quiesce_state;
     584              : 
     585              : // What a unix:// listener needs to remove its socket file. Every lookup goes
     586              : // through dir_fd, so a later chdir() can't move the cleanup to another file,
     587              : // and the name is unlinked only while dev and ino still name the socket we
     588              : // bound.
     589              : typedef struct {
     590              :   char *path;
     591              :   const char *base;
     592              :   int dir_fd;
     593              :   dev_t dev;
     594              :   ino_t ino;
     595              : } chttpsvr_unix_bind;
     596              : 
     597              : // The server. Lock order: srv->mutex before wait_mutex; idle_mutex,
     598              : // diverted_mutex and wait_mutex are each held only briefly and never across a
     599              : // dispatch.
     600              : struct chttpserver {
     601              :   // routers[0] is the root and the rest are the sub-routers, sorted by
     602              :   // prefix_seg_count from largest to smallest; routes_lock guards the array.
     603              :   // root_router is routers[0] copied at create time, read without the lock.
     604              :   // max_prefix_seg_count bounds the shared decode cache of find_route, so the
     605              :   // operator and not the client decides how much of a path gets decoded.
     606              :   chttpsvr_router **routers;
     607              :   chttpsvr_router *root_router;
     608              :   size_t router_count;
     609              :   size_t router_cap;
     610              :   int max_prefix_seg_count;
     611              :   cthrpool worker_pool;
     612              :   // Runs every rejection (middleware plus the courtesy write and close), so
     613              :   // that work stays off the reactor and doesn't compete with the full worker
     614              :   // pool that caused a 503.
     615              :   cthrpool reject_pool;
     616              :   ctls_ctx *tls_ctx;
     617              :   // in_flight_requests counts handlers that run; requests_done_cv wakes the
     618              :   // drain.
     619              :   ccol__mutex mutex;
     620              :   ccol__cond_var requests_done_cv;
     621              :   int in_flight_requests;
     622              :   // Three pin counters, all broadcast on resolve_cv, which chttpsvr__destroy
     623              :   // waits on before it frees the server. pending_resolve_count is held by every
     624              :   // public call for its whole body; the decrement and the broadcast are both
     625              :   // done under mutex. servers_bundler_pins is held by
     626              :   // engine_force_stop_quiesce_all and listener_dispatch_pins by one listener
     627              :   // dispatch; each has its own counter because quiesce_server_once and
     628              :   // chttpsvr_stop_internal wait on them from inside a call that holds a
     629              :   // pending_resolve_count pin. chttpsvr_stop_internal waits for
     630              :   // listener_dispatch_pins before it closes the listener fd.
     631              :   _Atomic size_t pending_resolve_count;
     632              :   _Atomic size_t servers_bundler_pins;
     633              :   _Atomic size_t listener_dispatch_pins;
     634              :   ccol__cond_var resolve_cv;
     635              :   ccol__rw_lock routes_lock;
     636              :   clog cl;
     637              : 
     638              :   // Read by the reactor on every accept without srv->mutex, hence atomic, and
     639              :   // set before the listener is registered. listen_fd is -1 while stopped.
     640              :   _Atomic int listen_fd;
     641              :   _Atomic bool is_unix_socket;
     642              :   // The unix socket file (path NULL for TCP), and the port and address
     643              :   // getsockname() gave at bind time. srv->mutex guards all of them.
     644              :   chttpsvr_unix_bind unix_bind;
     645              :   uint16_t bound_port;
     646              :   char bound_host[INET6_ADDRSTRLEN];
     647              :   ceventloop_reg listen_reg;
     648              :   // lifecycle, contributed_to_engine and engine_gen (the engine generation of
     649              :   // our reference) are guarded by srv->mutex.
     650              :   chttpsvr_lifecycle lifecycle;
     651              :   bool contributed_to_engine;
     652              :   uintptr_t engine_gen;
     653              :   // quiesce_done_cv is broadcast when quiesce_state reaches QUIESCED.
     654              :   // quiesce_waiters counts threads waiting for that; the winner waits for it to
     655              :   // reach 0 before it returns, because its caller destroys the mutex and the
     656              :   // condition variable right after, while a woken loser may still be
     657              :   // reacquiring the mutex.
     658              :   chttpsvr_quiesce_state quiesce_state;
     659              :   ccol__cond_var quiesce_done_cv;
     660              :   size_t quiesce_waiters;
     661              :   // True from the start of a teardown until a restart. Responses then close
     662              :   // their connections and new requests get a 503, so the drain waits only for
     663              :   // running handlers. A plain bool used through __atomic builtins, so the
     664              :   // response path pays a plain load.
     665              :   bool draining;
     666              : 
     667              :   // Settings that chttpsvr_start writes on every restart while connections that
     668              :   // survived the stop may read them, hence atomic. max_header_read_duration_ms
     669              :   // bounds the handshake plus the header read (0 is off).
     670              :   _Atomic unsigned stream_read_timeout_ms;
     671              :   _Atomic unsigned max_body_read_duration_ms;
     672              :   _Atomic unsigned response_write_timeout_ms;
     673              :   _Atomic unsigned max_response_write_duration_ms;
     674              :   _Atomic unsigned idle_timeout_ms;
     675              :   _Atomic unsigned max_header_read_duration_ms;
     676              :   _Atomic size_t max_body_size;
     677              :   _Atomic size_t max_header_bytes;
     678              :   _Atomic size_t max_connections;
     679              :   // Read only by the listener callback, which never runs while chttpsvr_start
     680              :   // writes it, so a plain bool is enough.
     681              :   bool enable_keepalive;
     682              :   _Atomic size_t current_connections;
     683              : 
     684              :   // Set when the listener pauses after a resource error of accept4() or a
     685              :   // failed allocation, and consumed by the sweep, which resumes it. Retrying
     686              :   // inline would block the shared reactor thread for as long as the pressure
     687              :   // lasts.
     688              :   _Atomic bool listener_paused_for_resource_pressure;
     689              : 
     690              :   // Rate limit of the unexpected accept4() failure log. Plain fields, since one
     691              :   // listener's dispatches never overlap.
     692              :   struct timespec last_accept_err_log;
     693              :   bool last_accept_err_log_set;
     694              : 
     695              :   // idle_mutex guards the idle list (reactor-owned connections waiting for
     696              :   // their next request) and the parked list (connections waiting with no thread
     697              :   // for body bytes or write room). Both are claimed through
     698              :   // idle_list_try_claim; the separate parked list lets the sweep skip idle
     699              :   // keep-alive connections.
     700              :   ccol__mutex idle_mutex;
     701              :   chttpsvr_conn *idle_head, *idle_tail;
     702              :   chttpsvr_conn *parked_head, *parked_tail;
     703              : 
     704              :   // Every connection a worker owns. wait_in_flight_bounded forces a shutdown(2)
     705              :   // on these after its graceful wait, so a peer that stalls under an infinite
     706              :   // timeout can't hang a destroy, a restart or chttpsvr_engine_wait().
     707              :   ccol__mutex diverted_mutex;
     708              :   chttpsvr_conn *diverted_head, *diverted_tail;
     709              : 
     710              :   // Our slot index, for chttpsvr_finish_destroy when it runs from on_removed
     711              :   // with no handle at hand.
     712              :   uint32_t self_slot_idx;
     713              : 
     714              :   // Works like lifetime_refs of chttpsvr_conn: 1 until chttpsvr__destroy, plus
     715              :   // 1 for every connection registration and listener registration until its
     716              :   // on_removed fires. chttpsvr_finish_destroy frees the server at 0. The free
     717              :   // is deferred, never waited for, because an on_removed can fire on the
     718              :   // engine's reaper long after chttpsvr__destroy returns, and blocking there
     719              :   // would deadlock against a concurrent reap.
     720              :   _Atomic int lifetime_refs;
     721              : 
     722              :   ccol_memmgmt_procs *m_procs;
     723              : 
     724              :   // Slow-client settings resolved by chttpsvr_start, atomic for the same
     725              :   // restart reason. UINT_MAX means the floor or the wait is off, SIZE_MAX no
     726              :   // memory limit or an unlimited queue, and stream_threads -1 means streaming
     727              :   // handlers share the worker pool.
     728              :   _Atomic unsigned min_rate_bps;
     729              :   _Atomic unsigned rate_grace_ms;
     730              :   _Atomic size_t mem_cap;
     731              :   _Atomic unsigned mem_wait_ms;
     732              :   _Atomic int stream_threads;
     733              :   _Atomic size_t stream_qcap;
     734              :   _Atomic unsigned stream_qtimeout_ms;
     735              : 
     736              :   // The streaming pool, created by the first streaming request and guarded by
     737              :   // srv->mutex. stream_gen changes, under wait_mutex, each time the pool goes
     738              :   // out of service, so a task of a retired pool stops taking requests.
     739              :   cthrpool stream_pool;
     740              :   _Atomic uint64_t stream_gen;
     741              : 
     742              :   // Pools a restart retired while old requests may run on them. Each drains on
     743              :   // its own thread; srv->mutex guards the list and a teardown waits for all of
     744              :   // them.
     745              :   struct chttpsvr_retired_pools *retired_pools;
     746              : 
     747              :   // wait_mutex guards the memory accounting, the memory-wait list and the
     748              :   // streaming queue. It's taken only when a body reserves memory or a request
     749              :   // enters or leaves the streaming queue, and never held across I/O, a dispatch
     750              :   // or another lock of this server. mem_exempt_active means one connection went
     751              :   // past the limit (see mem_admit); mem_admitting and mem_admit_again serialize
     752              :   // mem_admit without recursion.
     753              :   ccol__mutex wait_mutex;
     754              :   size_t mem_in_use;
     755              :   size_t mem_holders;
     756              :   size_t mem_blocked;
     757              :   bool mem_exempt_active;
     758              :   bool mem_admission_closed;
     759              :   bool mem_admitting;
     760              :   bool mem_admit_again;
     761              :   chttpsvr_conn *mem_head, *mem_tail;
     762              :   size_t mem_waiting;
     763              : 
     764              :   // The streaming queue, oldest first. sq_tokens counts the current run's tasks
     765              :   // draining it (at most the pool's thread count) and sq_unclaimed those that
     766              :   // haven't taken a request yet, so no extra task starts for a request one is
     767              :   // already coming for.
     768              :   chttpsvr_conn *sq_head, *sq_tail;
     769              :   size_t sq_len;
     770              :   size_t sq_tokens;
     771              :   size_t sq_unclaimed;
     772              : };
     773              : 
     774              : // Tells whether srv is in the draining phase of a teardown, so the response
     775              : // paths stop keeping connections alive. Reads srv->draining with a relaxed
     776              : // atomic load.
     777         2806 : static inline bool srv_draining(const struct chttpserver *srv) {
     778         2806 :   return __atomic_load_n(&srv->draining, __ATOMIC_RELAXED);
     779              : }
     780              : 
     781              : // Puts srv into the draining phase when a teardown starts, so no new handler
     782              : // starts and no connection is kept alive. Sets srv->draining with a relaxed
     783              : // atomic store.
     784          588 : static void srv_begin_draining(struct chttpserver *srv) {
     785          588 :   __atomic_store_n(&srv->draining, true, __ATOMIC_RELAXED);
     786              : }
     787              : 
     788              : // Resolves h to its server and pins it, so a public call can use the server
     789              : // without a concurrent destroy freeing it. Returns NULL for 0, for garbage, for
     790              : // a free or reused slot, and for every handle once the table was released at
     791              : // unload. On success the caller must call chttpsvr_resolve_unpin() once before
     792              : // each return of its own short function.
     793              : // It reads the slot table under chttpsvr_slot_table.mutex and increments
     794              : // raw->pending_resolve_count without taking raw->mutex. That's safe because the
     795              : // slot-release step of chttpsvr__destroy needs the table mutex too, so raw
     796              : // can't be freed while we hold it.
     797        54177 : static struct chttpserver *chttpsvr_resolve(chttpsvr h) {
     798        54177 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
     799        54177 :   if (h == 0) return NULL;
     800        54170 :   uint32_t idx = (uint32_t)(h >> 32);
     801        54170 :   uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
     802        54170 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
     803        54170 :   struct chttpserver *raw = NULL;
     804       108338 :   if (chttpsvr_slot_table.slots &&
     805        54168 :       idx < cvector_size(chttpsvr_slot_table.slots)) {
     806        54168 :     chttpsvr_slot *slot =
     807        54168 :         (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx);
     808        54168 :     if (slot->in_use && slot->generation == gen) raw = slot->ptr;
     809              :   }
     810        54164 :   if (raw) atomic_fetch_add(&raw->pending_resolve_count, 1);
     811        54170 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
     812        54170 :   return raw;
     813              : }
     814              : 
     815              : // Drops the pin chttpsvr_resolve took, and wakes a destroy that waits for the
     816              : // pins. The decrement and the broadcast on raw->resolve_cv both happen under
     817              : // raw->mutex; a bare atomic decrement outside the lock lets the destroy free
     818              : // raw before the broadcast touches it.
     819        54164 : static void chttpsvr_resolve_unpin(struct chttpserver *raw) {
     820        54164 :   ccol__mutex_lock(raw->mutex);
     821        54164 :   atomic_fetch_sub(&raw->pending_resolve_count, 1);
     822        54164 :   ccol__cond_var_broadcast(raw->resolve_cv);
     823        54164 :   ccol__mutex_unlock(raw->mutex);
     824        54164 : }
     825              : 
     826              : // Gives srv a slot in the handle table and returns the handle built from it, so
     827              : // chttpsvr_create_mp can publish the fully built server. Returns 0 when memory
     828              : // runs out or the table was released at unload. Under chttpsvr_slot_table.mutex
     829              : // it reuses a free index or appends a slot, bumps the generation (skipping 0 on
     830              : // wraparound, so a live server never gets a handle equal to CHTTPSVR_NULL),
     831              : // marks the slot in use and stores the index in srv->self_slot_idx.
     832          561 : static chttpsvr chttpsvr_handle_slot_acquire(struct chttpserver *srv) {
     833          561 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
     834          561 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
     835          561 :   if (!chttpsvr_slot_table.slots) {
     836            0 :     ccol__mutex_unlock(chttpsvr_slot_table.mutex);
     837            0 :     return 0;
     838              :   }
     839          561 :   uint32_t idx;
     840          561 :   chttpsvr_slot *slot;
     841          561 :   if (cvector_size(chttpsvr_slot_table.free_indices) > 0) {
     842          547 :     cvector_pop_back(chttpsvr_slot_table.free_indices, &idx);
     843          547 :     slot = (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx);
     844              :   } else {
     845           14 :     chttpsvr_slot fresh = {0};
     846           14 :     if (cvector_push_back(chttpsvr_slot_table.slots, &fresh) != ccol_success) {
     847            0 :       ccol__mutex_unlock(chttpsvr_slot_table.mutex);
     848            0 :       return 0;
     849              :     }
     850           14 :     idx = (uint32_t)cvector_size(chttpsvr_slot_table.slots) - 1;
     851           14 :     slot = (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx);
     852              :   }
     853          561 :   slot->generation++;
     854          561 :   if (slot->generation == 0) slot->generation++;
     855          561 :   slot->ptr = srv;
     856          561 :   slot->in_use = true;
     857          561 :   srv->self_slot_idx = idx;
     858          561 :   chttpsvr h = ((chttpsvr)idx << 32) | (chttpsvr)slot->generation;
     859          561 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
     860          561 :   return h;
     861              : }
     862              : 
     863              : // Tells whether the exit-time destructor has released the slot table, so a late
     864              : // create can fail cleanly; reads it under the table mutex.
     865          567 : static bool chttpsvr_slot_table_released(void) {
     866          567 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
     867          567 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
     868          567 :   bool released = chttpsvr_slot_table.slots == NULL;
     869          567 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
     870          567 :   return released;
     871              : }
     872              : 
     873              : // A process-wide thread-local key that records which server, if any, the
     874              : // calling thread runs worker_pool or reject_pool tasks for. task_worker and
     875              : // reject_task set it once and nothing clears it, because cthrpool threads
     876              : // belong to one pool for their whole life and a restart builds new pools with
     877              : // new threads.
     878              : // It lets chttpsvr_destroy(), chttpsvr_start() and chttpsvr_engine_wait()
     879              : // refuse a call from a handler or middleware of the server (or engine) that
     880              : // would have to wait for that same handler. Without it such a call waits about
     881              : // a minute for in_flight_requests to reach 0 and then aborts inside
     882              : // cthreadpool.c, or deadlocks for ever if an engine stop races in.
     883              : // Creating the key can fail when the process holds PTHREAD_KEYS_MAX keys, and
     884              : // key 0 then belongs to some other component. ready records that creation
     885              : // worked, and nothing touches key without it. chttpsvr_start refuses to start a
     886              : // server without the key; the module destructor deletes it once no server is
     887              : // left (see cleanup_chttpsvr_slot_table).
     888              : static struct {
     889              :   ccol__thread_ls_key key;
     890              :   ccol__once_flag once;
     891              :   // Serializes creating and deleting key.
     892              :   ccol__mutex mutex;
     893              :   _Atomic bool ready;
     894              : } chttpsvr_worker_key_bundle = {0};
     895              : 
     896              : // Initializes the key bundle's mutex once; the worker key functions need it
     897              : // before they create or delete the key.
     898            6 : static void chttpsvr_worker_key_init_globals(void) {
     899            6 :   if (ccol__mutex_init(chttpsvr_worker_key_bundle.mutex) != 0)
     900            0 :     ccol__fatal_err("chttpsvr worker key: failed to initialize mutex");
     901            6 : }
     902              : 
     903              : // Creates the worker key if it doesn't exist yet and tells whether it exists.
     904              : // chttpsvr_start calls it and refuses to start a server without the key, so no
     905              : // worker thread ever runs unmarked. It creates the key under the bundle mutex
     906              : // and publishes ready with a release store; a failed creation is retried by the
     907              : // next start.
     908          334 : static bool chttpsvr_worker_key_ensure(void) {
     909          334 :   if (atomic_load_explicit(&chttpsvr_worker_key_bundle.ready,
     910              :                            memory_order_acquire))
     911              :     return true;
     912            7 :   ccol__call_once(chttpsvr_worker_key_bundle.once,
     913              :                   chttpsvr_worker_key_init_globals);
     914            7 :   ccol__mutex_lock(chttpsvr_worker_key_bundle.mutex);
     915           14 :   if (!atomic_load(&chttpsvr_worker_key_bundle.ready) &&
     916            7 :       ccol__thread_ls_key_create(chttpsvr_worker_key_bundle.key, NULL) == 0)
     917            6 :     atomic_store_explicit(&chttpsvr_worker_key_bundle.ready, true,
     918              :                           memory_order_release);
     919            7 :   bool ready = atomic_load(&chttpsvr_worker_key_bundle.ready);
     920            7 :   ccol__mutex_unlock(chttpsvr_worker_key_bundle.mutex);
     921            7 :   return ready;
     922              : }
     923              : 
     924              : // Tells whether the worker key exists, so the mark and self-call checks never
     925              : // touch a key of another component. A thread can only mark itself when it does,
     926              : // so every reader takes a missing key as "not a worker".
     927         2759 : static inline bool chttpsvr_worker_key_ready(void) {
     928         2759 :   return atomic_load_explicit(&chttpsvr_worker_key_bundle.ready,
     929              :                               memory_order_acquire);
     930              : }
     931              : 
     932              : // Marks the calling thread as a permanent worker of srv's pools, which the
     933              : // self-call checks read later. task_worker and reject_task call it once at
     934              : // their top; it sets the thread-local worker key.
     935         1809 : static void chttpsvr_mark_worker_thread(struct chttpserver *srv) {
     936         1809 :   if (!chttpsvr_worker_key_ready()) return;
     937         1809 :   ccol__thread_ls_set(chttpsvr_worker_key_bundle.key, (void *)srv);
     938              : }
     939              : 
     940              : // Tells whether the calling thread is a worker of srv's worker_pool or
     941              : // reject_pool, so chttpsvr_destroy() and chttpsvr_start() can refuse a call
     942              : // from a handler, middleware or reject task of srv that would wait for itself.
     943              : // Reads the thread-local worker key.
     944          892 : static bool chttpsvr_is_self_call(struct chttpserver *srv) {
     945          892 :   if (!chttpsvr_worker_key_ready()) return false;
     946          892 :   return ccol__thread_ls_get(chttpsvr_worker_key_bundle.key) == (void *)srv;
     947              : }
     948              : 
     949              : // Tells whether the calling thread is a worker of any server, so
     950              : // chttpsvr_engine_wait() can refuse a call from a handler. An engine stop
     951              : // drains the worker pool of every registered server with no timeout, so a
     952              : // handler of any server that waits for the engine would wait for itself and
     953              : // deadlock the whole engine. Reads the thread-local worker key.
     954           58 : static bool chttpsvr_is_any_worker_call(void) {
     955           58 :   if (!chttpsvr_worker_key_ready()) return false;
     956           57 :   return ccol__thread_ls_get(chttpsvr_worker_key_bundle.key) != NULL;
     957              : }
     958              : 
     959              : // The one ceventloop reactor of the process, shared by every server, with its
     960              : // refcount, reaper thread and settings. chttpclient has a reactor of its own,
     961              : // so nothing here coordinates with the client. mutex guards every field unless
     962              : // a member comment says otherwise.
     963              : static struct {
     964              :   // Written only under mutex, by engine_acquire and the reaper. Many places
     965              :   // read it with no lock; that's safe because such a reader always runs while
     966              :   // it (or its server) holds a live engine reference, which keeps the value
     967              :   // fixed between creation and reap, and thread create, join and the handle
     968              :   // pins order the writes against the readers. A reader that holds no engine
     969              :   // reference would need this field to be _Atomic.
     970              :   ceventloop reactor;
     971              :   size_t reactor_refs;
     972              :   ccol__mutex mutex;
     973              :   ccol__cond_var stopped_cv;
     974              :   ccol__once_flag once;
     975              :   // True while a reap is tearing the reactor down. reaper_thread is the reaper
     976              :   // spawn_reaper recorded, joinable until somebody joins it.
     977              :   bool stopping;
     978              :   ccol__thread_id reaper_thread;
     979              :   bool reaper_joinable;
     980              :   // The engine allocator: mprocs points at mprocs_storage, or is NULL for the
     981              :   // default. Like num_reactor_threads it's built into the reactor at creation,
     982              :   // so it can change only before the first start or after a full stop.
     983              :   ccol_memmgmt_procs mprocs_storage;
     984              :   ccol_memmgmt_procs *mprocs;
     985              :   // 0 picks the default of one reactor thread, which runs every callback inline
     986              :   // and is the faster choice for ordinary traffic. A positive value pins the
     987              :   // reactor to that many threads.
     988              :   size_t num_reactor_threads;
     989              :   // The thread count the last reactor was created with, for the tests.
     990              :   size_t last_resolved_num_reactor_threads;
     991              :   // The engine logger for the reactor thread's diagnostics. It's user_log when
     992              :   // the caller installed one, else a CLOG_FATAL fallback on fd 2 that
     993              :   // engine_acquire creates and the reaper closes. It's never CLOG_NULL while a
     994              :   // reactor exists, because clog has no guard for a NULL handle; engine_acquire
     995              :   // destroys the reactor again when the fallback can't be allocated.
     996              :   clog log;
     997              :   // The logger chttpsvr_set_engine_logger() derived, or CLOG_NULL. It outlives
     998              :   // every engine: Each start logs through it and each reaper leaves it open.
     999              :   // Only a later chttpsvr_set_engine_logger(), process exit or unload closes
    1000              :   // it.
    1001              :   clog user_log;
    1002              :   // Set when the exit-time destructor couldn't close user_log because an engine
    1003              :   // still ran; that engine's reaper closes it.
    1004              :   bool close_user_log_at_stop;
    1005              :   // Generation of the running reactor, or 0 when none runs. A server tags its
    1006              :   // engine reference with it so a late release never touches a newer engine's
    1007              :   // refcount. chttpsvr_engine_stop() reads it with one lock-free load, which is
    1008              :   // async-signal-safe. Written under mutex; gen_counter hands out the values.
    1009              :   _Atomic uintptr_t generation;
    1010              :   uintptr_t gen_counter;
    1011              :   // The process that created the current or last reactor. A fork() child
    1012              :   // inherits the reactor but none of its threads; see
    1013              :   // engine_forget_inherited_locked.
    1014              :   pid_t reactor_pid;
    1015              : } srv_engine_bundler = {0};
    1016              : 
    1017              : // The one idle-timeout sweep thread of the process. It walks the idle and
    1018              : // parked lists of every started server. servers_bundler.mutex guards running
    1019              : // and pid.
    1020              : static struct {
    1021              :   ccol__thread_id thread;
    1022              :   bool running;
    1023              :   // The process that started the thread. A fork() child that finds running set
    1024              :   // by another process has no thread to join (see
    1025              :   // idle_sweep_forget_inherited_locked).
    1026              :   pid_t pid;
    1027              :   // Atomic because idle_sweep_fn reads it in its loop with no lock. A plain
    1028              :   // bool is a data race, and the compiler could cache the read so the thread
    1029              :   // never stops and the join hangs.
    1030              :   _Atomic bool stop_flag;
    1031              :   // The sweep waits for its next tick on wake_cv (CLOCK_MONOTONIC). A stop sets
    1032              :   // stop_flag under wake_mu and signals wake_cv, so the join doesn't sit out
    1033              :   // the rest of a tick. wake_mu is a leaf lock.
    1034              :   ccol__mutex wake_mu;
    1035              :   ccol__cond_var wake_cv;
    1036              : } idle_sweep_bundler = {0};
    1037              : 
    1038              : // The registry of started servers, a plain realloc'ed array. The sweep walks it
    1039              : // and an engine stop quiesces every server in it.
    1040              : static struct {
    1041              :   ccol__mutex mutex;
    1042              :   struct chttpserver **servers;
    1043              :   size_t count;
    1044              :   size_t capacity;
    1045              : } servers_bundler = {0};
    1046              : 
    1047              : static void idle_sweep_stop_if_running(void);
    1048              : static void engine_request_reaper_join(void);
    1049              : static void quiesce_server_once(struct chttpserver *srv);
    1050              : static bool engine_release_begin(uintptr_t gen);
    1051              : static void close_idle_connections(struct chttpserver *srv,
    1052              :                                    bool include_parked);
    1053              : static void spawn_reaper(void);
    1054              : static void chttpsvr_stop_internal(struct chttpserver *raw);
    1055              : static void engine_globals_init(void);
    1056              : #ifdef RUNNING_UNIT_TESTS
    1057              : static void reaper_race_hook_wait_if_armed(void);
    1058              : static void listener_dispatch_race_hook_wait_if_armed(bool at_entry);
    1059              : static void quiesce_teardown_race_hook_wait_if_armed(void);
    1060              : #endif
    1061              : 
    1062              : // Quiesces every server still in servers_bundler: Stop listening, drain, close
    1063              : // connections, destroy the pools and drop the engine reference. The engine
    1064              : // reaper calls it before it destroys the reactor, because after a
    1065              : // chttpsvr_engine_stop() the servers may be fully live, and the reactor and the
    1066              : // array would otherwise be freed under registrations that point into them. On
    1067              : // the graceful path the list usually holds only servers whose quiesce runs on
    1068              : // another thread (we wait for each as a loser) or that a concurrent start
    1069              : // registered.
    1070              : // It first sets srv->draining on every server and closes their idle
    1071              : // connections, so none keeps serving keep-alive clients while the drains ahead
    1072              : // of it run; that pass walks the array from the end, because an unregister
    1073              : // moves the last element into the freed slot. The main loop reads servers[0]
    1074              : // again on every pass, since quiesce_server_once unregisters the server, and
    1075              : // ends when servers_bundler.count is 0.
    1076              : // Each server is pinned through srv->servers_bundler_pins, taken under
    1077              : // servers_bundler.mutex and dropped under srv->mutex with a broadcast, because
    1078              : // a concurrent chttpsvr_destroy() could free it during the long quiesce.
    1079              : // pending_resolve_count would self-deadlock, since quiesce_server_once waits
    1080              : // for it to reach 0. Seeing the same server twice in a row means a concurrent
    1081              : // restart registered it again, so we nap 1 ms instead of spinning.
    1082           62 : static void engine_force_stop_quiesce_all(void) {
    1083           62 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1084           62 :   ccol__mutex_lock(servers_bundler.mutex);
    1085           87 :   for (size_t i = 0; i < servers_bundler.count; i++)
    1086           25 :     srv_begin_draining(servers_bundler.servers[i]);
    1087           62 :   size_t idle_pos = servers_bundler.count;
    1088           62 :   ccol__mutex_unlock(servers_bundler.mutex);
    1089           25 :   for (;;) {
    1090           87 :     ccol__mutex_lock(servers_bundler.mutex);
    1091           87 :     if (idle_pos > servers_bundler.count) idle_pos = servers_bundler.count;
    1092           87 :     if (idle_pos == 0) {
    1093           62 :       ccol__mutex_unlock(servers_bundler.mutex);
    1094           62 :       break;
    1095              :     }
    1096           25 :     struct chttpserver *srv = servers_bundler.servers[--idle_pos];
    1097           25 :     atomic_fetch_add(&srv->servers_bundler_pins, 1);
    1098           25 :     ccol__mutex_unlock(servers_bundler.mutex);
    1099           25 :     close_idle_connections(srv, false);
    1100           25 :     ccol__mutex_lock(srv->mutex);
    1101           25 :     atomic_fetch_sub(&srv->servers_bundler_pins, 1);
    1102           25 :     ccol__cond_var_broadcast(srv->resolve_cv);
    1103           25 :     ccol__mutex_unlock(srv->mutex);
    1104              :   }
    1105           62 :   struct chttpserver *prev_unremoved = NULL;
    1106           25 :   for (;;) {
    1107           87 :     ccol__mutex_lock(servers_bundler.mutex);
    1108           87 :     if (servers_bundler.count == 0) {
    1109           62 :       ccol__mutex_unlock(servers_bundler.mutex);
    1110           62 :       return;
    1111              :     }
    1112           25 :     struct chttpserver *srv = servers_bundler.servers[0];
    1113           25 :     atomic_fetch_add(&srv->servers_bundler_pins, 1);
    1114           25 :     ccol__mutex_unlock(servers_bundler.mutex);
    1115              : 
    1116              : #ifdef RUNNING_UNIT_TESTS
    1117           25 :     reaper_race_hook_wait_if_armed();
    1118              : #endif
    1119              : 
    1120           25 :     if (srv == prev_unremoved) {
    1121            0 :       struct timespec ts = {0, 1000000L};
    1122            0 :       nanosleep(&ts, NULL);
    1123              :     }
    1124           25 :     prev_unremoved = srv;
    1125           25 :     quiesce_server_once(srv);
    1126           25 :     ccol__mutex_lock(srv->mutex);
    1127           25 :     atomic_fetch_sub(&srv->servers_bundler_pins, 1);
    1128           25 :     ccol__cond_var_broadcast(srv->resolve_cv);
    1129           25 :     ccol__mutex_unlock(srv->mutex);
    1130              :   }
    1131              : }
    1132              : 
    1133              : // Creates idle_sweep_bundler.wake_cv on CLOCK_MONOTONIC, the clock the sweep
    1134              : // computes its deadlines with, so a stop can wake the sweep early. Returns 0 on
    1135              : // success.
    1136            6 : static int idle_sweep_init_wake_cv(void) {
    1137            6 :   ccol__cond_var_attr cv_attr;
    1138            6 :   if (ccol__cond_var_attr_init(cv_attr) != 0) return 1;
    1139            6 :   int rc = ccol__cond_var_attr_setclock(cv_attr, CLOCK_MONOTONIC);
    1140            6 :   if (rc == 0) rc = ccol__cond_var_init_ca(idle_sweep_bundler.wake_cv, cv_attr);
    1141            6 :   ccol__cond_var_attr_destroy(cv_attr);
    1142            6 :   return rc;
    1143              : }
    1144              : 
    1145              : // Initializes the engine, registry and sweep locks once, before any engine
    1146              : // function uses them; a failure is fatal. We leave SIGPIPE alone: Every plain
    1147              : // write sends with MSG_NOSIGNAL through chttp1_stream, and every TLS write goes
    1148              : // through the ctls socket BIO, which does the same.
    1149            6 : static void engine_globals_init(void) {
    1150            6 :   if (ccol__mutex_init(srv_engine_bundler.mutex) != 0)
    1151            0 :     ccol__fatal_err("chttpserver engine: failed to initialize mutex");
    1152            6 :   if (ccol__cond_var_init(srv_engine_bundler.stopped_cv) != 0)
    1153            0 :     ccol__fatal_err(
    1154              :         "chttpserver engine: failed to initialize condition variable");
    1155            6 :   if (ccol__mutex_init(servers_bundler.mutex) != 0)
    1156            0 :     ccol__fatal_err(
    1157              :         "chttpserver engine: failed to initialize servers_bundler mutex");
    1158            6 :   if (ccol__mutex_init(idle_sweep_bundler.wake_mu) != 0)
    1159            0 :     ccol__fatal_err("chttpserver engine: failed to initialize the sweep mutex");
    1160            6 :   if (idle_sweep_init_wake_cv() != 0)
    1161            0 :     ccol__fatal_err(
    1162              :         "chttpserver engine: failed to initialize the sweep condition "
    1163              :         "variable");
    1164            6 : }
    1165              : 
    1166              : // Logs a record through the engine logger with level_call (clog_info,
    1167              : // clog_error, ...) and the format and arguments that follow, so any engine code
    1168              : // can log without racing a logger swap. It's a statement and evaluates to
    1169              : // nothing. It reads srv_engine_bundler.log under srv_engine_bundler.mutex and
    1170              : // logs inside that critical section; copying the handle out and logging later
    1171              : // is a use-after-free, because chttpsvr_set_engine_logger() swaps the logger
    1172              : // under the mutex and closes the old one after unlocking. It does nothing while
    1173              : // log is CLOG_NULL. It's a macro so the record names the real call site.
    1174              : #define SRV_ENGINE_LOG(level_call, ...)                            \
    1175              :   do {                                                             \
    1176              :     ccol__call_once(srv_engine_bundler.once, engine_globals_init); \
    1177              :     ccol__mutex_lock(srv_engine_bundler.mutex);                    \
    1178              :     if (srv_engine_bundler.log)                                    \
    1179              :       level_call(srv_engine_bundler.log, __VA_ARGS__);             \
    1180              :     ccol__mutex_unlock(srv_engine_bundler.mutex);                  \
    1181              :   } while (0)
    1182              : 
    1183              : // Joins the recorded reaper thread if it's still joinable, so its stack isn't
    1184              : // kept for the life of the process, and clears reaper_joinable. The caller
    1185              : // holds srv_engine_bundler.mutex and must know the reaper already cleared
    1186              : // stopping, so it won't wait on this mutex.
    1187          413 : static void join_reaper_if_needed_locked(void) {
    1188          413 :   if (srv_engine_bundler.reaper_joinable) {
    1189           61 :     ccol__thread_join(srv_engine_bundler.reaper_thread);
    1190           61 :     srv_engine_bundler.reaper_joinable = false;
    1191              :   }
    1192              : }
    1193              : 
    1194              : // Tears down the shared engine; spawn_reaper runs it when the last reference
    1195              : // goes or chttpsvr_engine_stop() asks. It quiesces every registered server
    1196              : // first (a forced stop can find them live), then stops the sweep thread, which
    1197              : // calls into the reactor, and only then destroys the reactor. The servers array
    1198              : // is freed only when empty, because a start that registers during the teardown
    1199              : // belongs to the next engine.
    1200              : // Under srv_engine_bundler.mutex it clears reactor, generation and stopping,
    1201              : // closes user_log when the exit destructor asked for it, and wakes
    1202              : // chttpsvr_engine_wait(). The user_log's last record is logged inside the lock,
    1203              : // since a concurrent chttpsvr_set_engine_logger() may close that logger right
    1204              : // after; the fallback logger is taken out of log first, so its record and close
    1205              : // happen after the unlock and a slow sink never holds the mutex.
    1206              : // The last statement asks the stop watcher to join this thread, so an
    1207              : // application that only destroys its last server doesn't leave it unjoined. It
    1208              : // must come last and take no lock, because the watcher may join at once.
    1209           62 : static void *engine_reaper_fn(void *arg) {
    1210           62 :   (void)arg;
    1211           62 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1212           62 :   ceventloop loop_to_destroy;
    1213           62 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1214           62 :   loop_to_destroy = srv_engine_bundler.reactor;
    1215           62 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1216           62 :   engine_force_stop_quiesce_all();
    1217           62 :   idle_sweep_stop_if_running();
    1218           62 :   if (loop_to_destroy) ceventloop_destroy(loop_to_destroy);
    1219              : 
    1220           62 :   ccol__mutex_lock(servers_bundler.mutex);
    1221           62 :   if (servers_bundler.count == 0) {
    1222           62 :     free(servers_bundler.servers);
    1223           62 :     servers_bundler.servers = NULL;
    1224           62 :     servers_bundler.capacity = 0;
    1225              :   }
    1226           62 :   ccol__mutex_unlock(servers_bundler.mutex);
    1227              : 
    1228           62 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1229           62 :   srv_engine_bundler.reactor = CEVENTLOOP_NULL;
    1230           62 :   atomic_store(&srv_engine_bundler.generation, (uintptr_t)0);
    1231           62 :   srv_engine_bundler.stopping = false;
    1232           62 :   clog old_logger = srv_engine_bundler.log;
    1233           62 :   srv_engine_bundler.log = CLOG_NULL;
    1234           62 :   if (old_logger && old_logger == srv_engine_bundler.user_log) {
    1235            6 :     clog_info(old_logger, "The http server reactor engine has been destroyed");
    1236            6 :     old_logger = CLOG_NULL;
    1237              :   }
    1238           62 :   clog closing_user_log = CLOG_NULL;
    1239           62 :   if (srv_engine_bundler.close_user_log_at_stop) {
    1240            1 :     closing_user_log = srv_engine_bundler.user_log;
    1241            1 :     srv_engine_bundler.user_log = CLOG_NULL;
    1242            1 :     srv_engine_bundler.close_user_log_at_stop = false;
    1243              :   }
    1244           62 :   ccol__cond_var_broadcast(srv_engine_bundler.stopped_cv);
    1245           62 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1246           62 :   if (closing_user_log) clog_close(closing_user_log);
    1247              : 
    1248           62 :   if (old_logger) {
    1249           56 :     clog_info(old_logger, "The http server reactor engine has been destroyed");
    1250           56 :     clog_close(old_logger);
    1251              :   }
    1252           62 :   engine_request_reaper_join();
    1253           62 :   return NULL;
    1254              : }
    1255              : 
    1256              : #ifdef RUNNING_UNIT_TESTS
    1257              : // Test hook: A delay in ms between creating the reaper and recording its
    1258              : // thread, so the reaper can run to its end inside that window.
    1259              : static _Atomic unsigned g_spawn_reaper_delay_ms_for_tests = 0;
    1260            2 : void chttpsvr__set_spawn_reaper_delay_for_tests(unsigned ms) {
    1261            2 :   atomic_store(&g_spawn_reaper_delay_ms_for_tests, ms);
    1262            2 : }
    1263              : #endif
    1264              : 
    1265              : #ifdef RUNNING_UNIT_TESTS
    1266              : // Test hook: While set, creating the reaper thread fails and spawn_reaper runs
    1267              : // the reaper inline.
    1268              : static _Atomic bool g_force_reaper_thread_create_fail_for_tests = false;
    1269            2 : void chttpsvr__force_reaper_thread_create_fail_for_tests(bool force) {
    1270            2 :   atomic_store(&g_force_reaper_thread_create_fail_for_tests, force);
    1271            2 : }
    1272              : #endif
    1273              : 
    1274              : // Starts the engine reaper on its own thread, so chttpsvr_destroy() and the
    1275              : // stop watcher return without waiting for the teardown. It creates the thread
    1276              : // and records it in reaper_thread and reaper_joinable under
    1277              : // srv_engine_bundler.mutex, which the reaper needs before it ends, so the
    1278              : // reaper can't ask for its join, and no second reaper can start, before it's
    1279              : // recorded.
    1280              : // When the thread can't be created the reaper runs inline. It then waits for
    1281              : // every quiesce in progress, so the caller must not be quiescing a registered
    1282              : // server; quiesce_server_once spawns only after it unregisters.
    1283           62 : static void spawn_reaper(void) {
    1284           62 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1285           62 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1286           62 :   ccol__thread_id reaper;
    1287           62 :   bool reaper_create_fails = false;
    1288              : #ifdef RUNNING_UNIT_TESTS
    1289           62 :   reaper_create_fails =
    1290           62 :       atomic_load(&g_force_reaper_thread_create_fail_for_tests);
    1291              : #endif
    1292          123 :   if (reaper_create_fails ||
    1293           61 :       ccol__thread_create(reaper, engine_reaper_fn, NULL) != 0) {
    1294            1 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
    1295            1 :     engine_reaper_fn(NULL);
    1296            1 :     return;
    1297              :   }
    1298              : #ifdef RUNNING_UNIT_TESTS
    1299           61 :   unsigned delay_ms = atomic_load(&g_spawn_reaper_delay_ms_for_tests);
    1300           61 :   if (delay_ms) {
    1301            1 :     struct timespec nap = {(time_t)(delay_ms / 1000),
    1302            1 :                            (long)(delay_ms % 1000) * 1000000L};
    1303            1 :     nanosleep(&nap, NULL);
    1304              :   }
    1305              : #endif
    1306           61 :   srv_engine_bundler.reaper_thread = reaper;
    1307           61 :   srv_engine_bundler.reaper_joinable = true;
    1308           61 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1309              : }
    1310              : 
    1311              : static bool engine_stop_watcher_ensure_started_locked(void);
    1312              : static void engine_forget_inherited_locked(void);
    1313              : 
    1314              : // Takes a reference on the shared engine for chttpsvr_start, creating the
    1315              : // reactor and its logger when none runs. Returns ccol_success with the engine
    1316              : // generation in *out_gen, ccol_not_enough_memory, or ccol_unexpected_failure
    1317              : // when the stop watcher can't start (that engine would ignore
    1318              : // chttpsvr_engine_stop()).
    1319              : // *out_currently_stopping is always set. It's true only when stopping shows a
    1320              : // reap in progress; then we return at once without a reference and the return
    1321              : // value means nothing. We can't wait for the reap, because the calling
    1322              : // chttpsvr_start() holds its resolve pin and the reap's quiesce of that server
    1323              : // waits for that pin. The caller drops the pin and retries.
    1324              : // Under srv_engine_bundler.mutex it forgets an engine inherited across fork(),
    1325              : // starts the watcher, joins a finished reaper, and on creation sets reactor,
    1326              : // reactor_pid, log and a new generation; it always increments reactor_refs on
    1327              : // success. A logger that can't be allocated makes us destroy the new reactor
    1328              : // synchronously under the mutex, which is safe because nothing the join waits
    1329              : // for takes this mutex. The "created" record is logged under the lock, because
    1330              : // a concurrent chttpsvr_set_engine_logger() could close the logger right after
    1331              : // the unlock.
    1332          298 : static ccol_retval engine_acquire(bool *out_currently_stopping,
    1333              :                                   uintptr_t *out_gen) {
    1334          298 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1335          298 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1336          298 :   engine_forget_inherited_locked();
    1337          298 :   *out_currently_stopping = false;
    1338          298 :   if (!engine_stop_watcher_ensure_started_locked()) {
    1339            1 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
    1340            1 :     return ccol_unexpected_failure;
    1341              :   }
    1342          297 :   if (srv_engine_bundler.stopping) {
    1343            2 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
    1344            2 :     *out_currently_stopping = true;
    1345            2 :     return ccol_unexpected_failure;
    1346              :   }
    1347          295 :   join_reaper_if_needed_locked();
    1348              : 
    1349          295 :   if (!srv_engine_bundler.reactor) {
    1350           62 :     size_t nthreads = srv_engine_bundler.num_reactor_threads;
    1351           62 :     if (nthreads == 0) nthreads = 1;
    1352           62 :     srv_engine_bundler.last_resolved_num_reactor_threads = nthreads;
    1353           62 :     char *err = NULL;
    1354          124 :     srv_engine_bundler.reactor =
    1355           62 :         ceventloop_create_mp(256, 4, nthreads, srv_engine_bundler.mprocs, &err);
    1356           62 :     if (!srv_engine_bundler.reactor) {
    1357            0 :       ccol__mutex_unlock(srv_engine_bundler.mutex);
    1358            0 :       return ccol_not_enough_memory;
    1359              :     }
    1360           62 :     srv_engine_bundler.reactor_pid = getpid();
    1361              : 
    1362           62 :     if (!srv_engine_bundler.log && srv_engine_bundler.user_log)
    1363            6 :       srv_engine_bundler.log = srv_engine_bundler.user_log;
    1364           62 :     if (!srv_engine_bundler.log) {
    1365           56 :       srv_engine_bundler.log = clog_create_from_fd_mp(
    1366              :           2, CLOG_FATAL, NULL, srv_engine_bundler.mprocs);
    1367           56 :       if (!srv_engine_bundler.log) {
    1368            0 :         ceventloop_destroy(srv_engine_bundler.reactor);
    1369            0 :         srv_engine_bundler.reactor = CEVENTLOOP_NULL;
    1370            0 :         ccol__mutex_unlock(srv_engine_bundler.mutex);
    1371            0 :         return ccol_not_enough_memory;
    1372              :       }
    1373           56 :       clog_set_field(srv_engine_bundler.log, "component", "http-server-engine");
    1374              :     }
    1375              : 
    1376           62 :     clog_info(srv_engine_bundler.log,
    1377              :               "New http server reactor engine has been created");
    1378           62 :     if (++srv_engine_bundler.gen_counter == 0) srv_engine_bundler.gen_counter++;
    1379           62 :     atomic_store(&srv_engine_bundler.generation,
    1380              :                  srv_engine_bundler.gen_counter);
    1381              :   }
    1382          295 :   srv_engine_bundler.reactor_refs++;
    1383          295 :   *out_gen = atomic_load(&srv_engine_bundler.generation);
    1384          295 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1385          295 :   return ccol_success;
    1386              : }
    1387              : 
    1388              : // Drops an engine reference of generation gen, the first half of
    1389              : // engine_release; quiesce_server_once calls it directly so it can spawn the
    1390              : // reaper only after it unregisters. Returns true when this was the last
    1391              : // reference, and then the caller must call spawn_reaper().
    1392              : // Under srv_engine_bundler.mutex it decrements reactor_refs and, on the last
    1393              : // one, sets stopping. A gen that isn't the running generation is ignored, so a
    1394              : // late release can't take a newer engine's refcount. With stopping already set
    1395              : // (a forced stop's quiesce pass) it never reports the last reference, so no
    1396              : // second reaper starts.
    1397          295 : static bool engine_release_begin(uintptr_t gen) {
    1398          295 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1399          295 :   bool should_reap = false;
    1400          295 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1401          295 :   if (gen == 0 || gen != atomic_load(&srv_engine_bundler.generation)) {
    1402            0 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
    1403            0 :     return false;
    1404              :   }
    1405          295 :   if (srv_engine_bundler.reactor_refs > 0) srv_engine_bundler.reactor_refs--;
    1406          295 :   if (srv_engine_bundler.reactor_refs == 0 && srv_engine_bundler.reactor &&
    1407           64 :       !srv_engine_bundler.stopping) {
    1408           41 :     srv_engine_bundler.stopping = true;
    1409           41 :     should_reap = true;
    1410              :   }
    1411          295 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1412          295 :   return should_reap;
    1413              : }
    1414              : 
    1415              : // Drops an engine reference of a server that stops or fails to start, and
    1416              : // starts the reaper when it was the last.
    1417           11 : static void engine_release(uintptr_t gen) {
    1418           11 :   if (engine_release_begin(gen)) spawn_reaper();
    1419              : }
    1420              : 
    1421              : // Waits until no reactor exists and no reap runs, for chttpsvr_engine_wait(),
    1422              : // then joins the reaper. It waits on stopped_cv under srv_engine_bundler.mutex
    1423              : // and forgets an engine inherited across fork() first, so a child never waits
    1424              : // for threads it doesn't have.
    1425           57 : static void engine_wait_until_stopped(void) {
    1426           57 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1427           57 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1428           57 :   engine_forget_inherited_locked();
    1429          103 :   while (srv_engine_bundler.reactor || srv_engine_bundler.stopping)
    1430           46 :     ccol__cond_var_wait(srv_engine_bundler.stopped_cv,
    1431              :                         srv_engine_bundler.mutex);
    1432           57 :   join_reaper_if_needed_locked();
    1433           57 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1434           57 : }
    1435              : 
    1436              : // Stops the engine of generation gen; the stop watcher calls it for
    1437              : // chttpsvr_engine_stop(). It locks a mutex and may create a thread, so it runs
    1438              : // only on an ordinary thread, never in a signal handler. Under
    1439              : // srv_engine_bundler.mutex it zeroes reactor_refs and sets stopping, then
    1440              : // spawns the reaper. It does nothing when no reactor runs, when gen isn't the
    1441              : // running generation, or when stopping is set: A repeated or overlapping stop,
    1442              : // such as a second SIGTERM, would otherwise start two reapers that destroy the
    1443              : // same reactor, which is fatal.
    1444           23 : static void engine_force_stop_now(uintptr_t gen) {
    1445           23 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1446           23 :   bool should_reap = false;
    1447           23 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1448           23 :   engine_forget_inherited_locked();
    1449           23 :   if (srv_engine_bundler.reactor && !srv_engine_bundler.stopping &&
    1450           22 :       gen == atomic_load(&srv_engine_bundler.generation)) {
    1451           21 :     srv_engine_bundler.reactor_refs = 0;
    1452           21 :     srv_engine_bundler.stopping = true;
    1453           21 :     should_reap = true;
    1454              :   }
    1455           23 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1456           23 :   if (should_reap) spawn_reaper();
    1457           23 : }
    1458              : 
    1459              : // The stop watcher. chttpsvr_engine_stop() is documented as async-signal-safe,
    1460              : // while the stop itself locks srv_engine_bundler.mutex and creates a thread. A
    1461              : // signal that lands on a thread holding that mutex (a SIGTERM in the middle of
    1462              : // chttpsvr_start(), say) would deadlock. So the stop call only does an atomic
    1463              : // load, an atomic store and a semaphore post, and this always-running thread
    1464              : // does the real work.
    1465              : static struct {
    1466              :   ccol__semaphore sem;
    1467              :   // True once sem and thread are live; the only field chttpsvr_engine_stop()
    1468              :   // reads.
    1469              :   _Atomic bool ready;
    1470              :   ccol__thread_id thread;
    1471              :   // Guards the start attempts, under srv_engine_bundler.mutex. It's separate
    1472              :   // from ready so a failed start can be retried later.
    1473              :   bool started;
    1474              :   _Atomic bool exit_requested;
    1475              :   // Each kind of work has its own request flag, set before its post, so an
    1476              :   // extra post is harmless and a join request is never taken for a stop.
    1477              :   // stop_requested holds the generation a stop names, or 0, and the watcher
    1478              :   // stops only that generation. The reaper sets join_reaper_requested as its
    1479              :   // last act.
    1480              :   _Atomic uintptr_t stop_requested;
    1481              :   _Atomic bool join_reaper_requested;
    1482              :   // The process that started the watcher thread, guarded by
    1483              :   // srv_engine_bundler.mutex.
    1484              :   pid_t pid;
    1485              : } g_engine_stop_watcher = {0};
    1486              : 
    1487              : // Forgets the engine a fork() child inherited: The reactor handle, its
    1488              : // references and generation, the fallback logger and the reaper and watcher
    1489              : // flags, with none of their threads. Without this the child's servers would use
    1490              : // a reactor with no poller and its waits would never end, so the child starts
    1491              : // with no engine. It runs under srv_engine_bundler.mutex on every path that
    1492              : // acquires, stops or waits for the engine, and decides by comparing reactor_pid
    1493              : // and the watcher's pid with getpid(), so it works with
    1494              : // CCOL_FORK_SAFETY_REQUIRED=0. It resets those fields and closes the inherited
    1495              : // fallback logger, but leaves the inherited reactor itself alone, since its
    1496              : // threads belong to the parent.
    1497          378 : static void engine_forget_inherited_locked(void) {
    1498          378 :   if (g_engine_stop_watcher.started && g_engine_stop_watcher.pid != getpid()) {
    1499            0 :     g_engine_stop_watcher.started = false;
    1500            0 :     atomic_store(&g_engine_stop_watcher.ready, false);
    1501            0 :     atomic_store(&g_engine_stop_watcher.join_reaper_requested, false);
    1502            0 :     atomic_store(&g_engine_stop_watcher.stop_requested, (uintptr_t)0);
    1503              :   }
    1504          378 :   if (!srv_engine_bundler.reactor && !srv_engine_bundler.stopping &&
    1505           72 :       !srv_engine_bundler.reaper_joinable)
    1506              :     return;
    1507          307 :   if (srv_engine_bundler.reactor_pid == getpid()) return;
    1508            2 :   clog inherited_log = srv_engine_bundler.log;
    1509            2 :   srv_engine_bundler.log = CLOG_NULL;
    1510            2 :   if (inherited_log && inherited_log != srv_engine_bundler.user_log)
    1511            2 :     clog_close(inherited_log);
    1512            2 :   srv_engine_bundler.reactor = CEVENTLOOP_NULL;
    1513            2 :   srv_engine_bundler.reactor_refs = 0;
    1514            2 :   srv_engine_bundler.stopping = false;
    1515            2 :   srv_engine_bundler.reaper_joinable = false;
    1516            2 :   atomic_store(&srv_engine_bundler.generation, (uintptr_t)0);
    1517              : }
    1518              : 
    1519              : #ifdef RUNNING_UNIT_TESTS
    1520              : // Test hook: Returns the process that created the running reactor, or 0, so a
    1521              : // test can check that a fork() child runs a reactor of its own.
    1522            3 : pid_t chttpsvr__engine_reactor_pid_for_tests(void) {
    1523            3 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1524            3 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1525            3 :   pid_t pid = srv_engine_bundler.reactor ? srv_engine_bundler.reactor_pid : 0;
    1526            3 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1527            3 :   return pid;
    1528              : }
    1529              : #endif
    1530              : 
    1531              : // Asks the watcher to join the reaper; the reaper calls it as its last act, so
    1532              : // its thread is joined even when nobody waits for the engine. It always raises
    1533              : // join_reaper_requested, even with no watcher, so the backstop in
    1534              : // cleanup_engine_stop_watcher can find a request nobody serviced, and posts the
    1535              : // semaphore when the watcher is ready.
    1536           62 : static void engine_request_reaper_join(void) {
    1537           62 :   atomic_store(&g_engine_stop_watcher.join_reaper_requested, true);
    1538           62 :   if (atomic_load(&g_engine_stop_watcher.ready))
    1539           61 :     ccol__semaphore_post(g_engine_stop_watcher.sem);
    1540           62 : }
    1541              : 
    1542              : // Joins a finished reaper for the watcher and the exit destructor, so no
    1543              : // returned thread keeps its stack mapped. The join under
    1544              : // srv_engine_bundler.mutex is safe only because the reaper takes no lock after
    1545              : // it clears stopping. With stopping set a new reap runs, which means the
    1546              : // previous reaper was already joined, and the new one posts its own request.
    1547           61 : static void engine_join_finished_reaper(void) {
    1548           61 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1549           61 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1550           61 :   if (!srv_engine_bundler.stopping) join_reaper_if_needed_locked();
    1551           61 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1552           61 : }
    1553              : 
    1554              : #ifdef RUNNING_UNIT_TESTS
    1555              : // Test hook: Returns true while a spawned reaper thread is still unjoined, so a
    1556              : // test can check that the watcher joins it.
    1557            6 : bool chttpsvr__engine_reaper_unjoined_for_tests(void) {
    1558            6 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1559            6 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1560            6 :   bool unjoined = srv_engine_bundler.reaper_joinable;
    1561            6 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1562            6 :   return unjoined;
    1563              : }
    1564              : #endif
    1565              : 
    1566              : #ifdef RUNNING_UNIT_TESTS
    1567              : // Test hook: A delay in ms the watcher waits after each wakeup before it acts
    1568              : // on a stop request.
    1569              : static _Atomic unsigned g_engine_stop_watcher_delay_ms_for_tests = 0;
    1570            2 : void chttpsvr__set_engine_stop_watcher_delay_for_tests(unsigned ms) {
    1571            2 :   atomic_store(&g_engine_stop_watcher_delay_ms_for_tests, ms);
    1572            2 : }
    1573              : // Sleeps for the test delay above, if one is set, so a test can start an engine
    1574              : // between a stop request and its handling.
    1575           84 : static void engine_stop_watcher_delay_if_armed(void) {
    1576           84 :   unsigned ms = atomic_load(&g_engine_stop_watcher_delay_ms_for_tests);
    1577           84 :   if (!ms) return;
    1578            3 :   struct timespec nap = {(time_t)(ms / 1000), (long)(ms % 1000) * 1000000L};
    1579            3 :   nanosleep(&nap, NULL);
    1580              : }
    1581              : #endif
    1582              : 
    1583              : // The stop watcher thread. It exists so chttpsvr_engine_stop() can stay
    1584              : // async-signal-safe while the stop itself needs a mutex and a new thread. It
    1585              : // waits on the semaphore, then serves a pending reaper join and a pending stop
    1586              : // request (each read and cleared with an atomic exchange), until exit_requested
    1587              : // is set.
    1588           12 : static void *engine_stop_watcher_fn(void *arg) {
    1589           96 :   (void)arg;
    1590           96 :   for (;;) {
    1591           96 :     ccol__semaphore_wait(g_engine_stop_watcher.sem);
    1592           91 :     if (atomic_load(&g_engine_stop_watcher.exit_requested)) return NULL;
    1593           84 :     if (atomic_exchange(&g_engine_stop_watcher.join_reaper_requested, false))
    1594           61 :       engine_join_finished_reaper();
    1595              : #ifdef RUNNING_UNIT_TESTS
    1596           84 :     engine_stop_watcher_delay_if_armed();
    1597              : #endif
    1598           84 :     uintptr_t stop_gen =
    1599           84 :         atomic_exchange(&g_engine_stop_watcher.stop_requested, (uintptr_t)0);
    1600           84 :     if (stop_gen != 0) engine_force_stop_now(stop_gen);
    1601              :   }
    1602              : }
    1603              : 
    1604              : #ifdef RUNNING_UNIT_TESTS
    1605              : // Test hook: While set, creating the watcher thread fails.
    1606              : static _Atomic bool g_force_watcher_thread_create_fail_for_tests = false;
    1607            2 : void chttpsvr__force_watcher_thread_create_fail_for_tests(bool force) {
    1608            2 :   atomic_store(&g_force_watcher_thread_create_fail_for_tests, force);
    1609            2 : }
    1610              : #endif
    1611              : 
    1612              : // Starts the watcher thread if it isn't running and tells whether it runs, so
    1613              : // engine_acquire can refuse to run an engine that chttpsvr_engine_stop()
    1614              : // couldn't reach. The caller holds srv_engine_bundler.mutex on an ordinary
    1615              : // thread. On success it sets started, pid and ready; a failure leaves them
    1616              : // unset and is retried on every later call. A stop before the first engine
    1617              : // start does nothing, and it's never replayed against a later start.
    1618          298 : static bool engine_stop_watcher_ensure_started_locked(void) {
    1619          298 :   if (g_engine_stop_watcher.started) return true;
    1620           13 :   if (ccol__semaphore_init(g_engine_stop_watcher.sem, 0) != 0) return false;
    1621           13 :   bool created = false;
    1622              : #ifdef RUNNING_UNIT_TESTS
    1623           13 :   if (!atomic_load(&g_force_watcher_thread_create_fail_for_tests))
    1624              : #endif
    1625           12 :     created = ccol__thread_create(g_engine_stop_watcher.thread,
    1626              :                                   engine_stop_watcher_fn, NULL) == 0;
    1627           12 :   if (!created) {
    1628            1 :     ccol__semaphore_destroy(g_engine_stop_watcher.sem);
    1629            1 :     return false;
    1630              :   }
    1631           12 :   g_engine_stop_watcher.started = true;
    1632           12 :   g_engine_stop_watcher.pid = getpid();
    1633           12 :   atomic_store(&g_engine_stop_watcher.ready, true);
    1634           12 :   return true;
    1635              : }
    1636              : 
    1637              : // At process exit, joins the watcher and any reaper it didn't get to, so
    1638              : // valgrind sees no thread stack left behind, and closes the
    1639              : // chttpsvr_set_engine_logger() logger. started and thread are written once and
    1640              : // never reset, so reading them unlocked is safe. ready is cleared before the
    1641              : // semaphore is destroyed, because a signal handler may still call
    1642              : // chttpsvr_engine_stop() during exit. When an engine still runs, the logger
    1643              : // stays open and close_user_log_at_stop asks that engine's reaper to close it.
    1644            7 : __attribute__((destructor)) static void cleanup_engine_stop_watcher(void) {
    1645            7 :   if (g_engine_stop_watcher.started) {
    1646            7 :     atomic_store(&g_engine_stop_watcher.exit_requested, true);
    1647            7 :     ccol__semaphore_post(g_engine_stop_watcher.sem);
    1648            7 :     ccol__thread_join(g_engine_stop_watcher.thread);
    1649            7 :     atomic_store(&g_engine_stop_watcher.ready, false);
    1650            7 :     ccol__semaphore_destroy(g_engine_stop_watcher.sem);
    1651              :   }
    1652            7 :   if (atomic_exchange(&g_engine_stop_watcher.join_reaper_requested, false))
    1653            0 :     engine_join_finished_reaper();
    1654              : 
    1655            7 :   if (srv_engine_bundler.user_log) {
    1656            2 :     ccol__mutex_lock(srv_engine_bundler.mutex);
    1657            2 :     clog user_log = CLOG_NULL;
    1658            2 :     if (!srv_engine_bundler.log) {
    1659            1 :       user_log = srv_engine_bundler.user_log;
    1660            1 :       srv_engine_bundler.user_log = CLOG_NULL;
    1661              :     } else {
    1662            1 :       srv_engine_bundler.close_user_log_at_stop = true;
    1663              :     }
    1664            2 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
    1665            2 :     if (user_log) clog_close(user_log);
    1666              :   }
    1667            7 : }
    1668              : 
    1669              : // Requests a stop of the running engine; it's the body of
    1670              : // chttpsvr_engine_stop(), which a signal handler may call, so it uses only
    1671              : // atomic operations and a semaphore post. It reads generation and the watcher's
    1672              : // ready flag and does nothing when no engine runs or the watcher isn't up.
    1673              : // Otherwise it stores the generation in stop_requested and wakes the watcher.
    1674              : // The flag is set only inside the ready test, so a stale request never waits
    1675              : // for some unrelated later post.
    1676           24 : static void engine_force_stop(void) {
    1677           24 :   uintptr_t gen = atomic_load(&srv_engine_bundler.generation);
    1678           24 :   if (gen != 0 && atomic_load(&g_engine_stop_watcher.ready)) {
    1679           23 :     atomic_store(&g_engine_stop_watcher.stop_requested, gen);
    1680           23 :     ccol__semaphore_post(g_engine_stop_watcher.sem);
    1681              :   }
    1682           24 : }
    1683              : 
    1684              : #ifdef RUNNING_UNIT_TESTS
    1685              : // Test hook: Raises sig on this thread while it holds srv_engine_bundler.mutex,
    1686              : // to prove that a signal handler which calls chttpsvr_engine_stop() never
    1687              : // deadlocks. Such a handler deadlocks here if that call ever takes the mutex or
    1688              : // creates a thread.
    1689            1 : void chttpsvr__test_hold_engine_mutex_and_signal_self(int sig) {
    1690            1 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1691            1 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    1692            1 :   raise(sig);
    1693            1 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    1694            1 : }
    1695              : #endif
    1696              : 
    1697              : static void conn_close(chttpsvr_conn *conn);
    1698              : static void conn_linger(chttpsvr_conn *conn);
    1699              : static void conn_linger_step(chttpsvr_conn *conn);
    1700              : static bool conn_request_bytes_may_remain(chttpsvr_conn *conn);
    1701              : static void conn_reject_and_close(chttpsvr_conn *conn, bool run_middleware);
    1702              : static void chttpsvr_finish_destroy(struct chttpserver *raw);
    1703              : static void retired_pools_reap(struct chttpserver *srv, bool wait_all);
    1704              : 
    1705              : static void timespec_add_ms(struct timespec *ts, unsigned ms);
    1706              : static void slow_clock(struct timespec *ts);
    1707              : static void mem_release(chttpsvr_conn *conn);
    1708              : static void sweep_parked_waits(struct chttpserver *srv,
    1709              :                                struct timespec now_slow);
    1710              : static bool parked_expired(struct chttpserver *srv, chttpsvr_conn *c,
    1711              :                            struct timespec now, struct timespec now_slow);
    1712              : static bool parked_needs_kernel_query(struct chttpserver *srv,
    1713              :                                       const chttpsvr_conn *c,
    1714              :                                       struct timespec now,
    1715              :                                       struct timespec now_slow);
    1716              : #ifdef RUNNING_UNIT_TESTS
    1717              : // Test counters: How many kernel queries judged a parked connection, and how
    1718              : // many of those the sweep made while holding idle_mutex (that must stay 0).
    1719              : static _Atomic size_t g_parked_queries_for_tests = 0;
    1720              : static _Atomic size_t g_parked_queries_locked_for_tests = 0;
    1721              : static __thread bool g_sweep_holds_idle_mutex_for_tests = false;
    1722              : // Counts one kernel query of a parked connection, and counts it again as locked
    1723              : // when the sweep holds idle_mutex, for the test that checks the sweep queries
    1724              : // outside that lock.
    1725          286 : static void parked_query_note_for_tests(void) {
    1726          286 :   atomic_fetch_add_explicit(&g_parked_queries_for_tests, 1,
    1727              :                             memory_order_relaxed);
    1728          286 :   if (g_sweep_holds_idle_mutex_for_tests)
    1729            0 :     atomic_fetch_add_explicit(&g_parked_queries_locked_for_tests, 1,
    1730              :                               memory_order_relaxed);
    1731          286 : }
    1732              : // Test hook: Reads the two counters above into *total and *locked.
    1733          134 : void chttpsvr__parked_queries_for_tests(size_t *total, size_t *locked) {
    1734          134 :   *total = atomic_load(&g_parked_queries_for_tests);
    1735          134 :   *locked = atomic_load(&g_parked_queries_locked_for_tests);
    1736          134 : }
    1737              : #endif
    1738              : static void conn_resume_parked(chttpsvr_conn *conn);
    1739              : static bool conn_divert_gate(chttpsvr_conn *conn);
    1740              : static ssize_t drain_body_socket_read(chttpsvr_conn *conn,
    1741              :                                       chttp1_stream *stream, char *raw,
    1742              :                                       size_t len);
    1743              : static void send_response_park(chttpsvr_conn *conn, chttp1_stream *stream,
    1744              :                                const char *head, size_t head_len,
    1745              :                                size_t body_pos, bool keep_alive, bool no_body,
    1746              :                                bool internal);
    1747              : static void conn_park_write(chttpsvr_conn *conn, struct chttpserver *srv);
    1748              : static bool conn_park_arm(chttpsvr_conn *conn, uint8_t kind);
    1749              : static void conn_end_parked_write(chttpsvr_conn *conn);
    1750              : static void conn_dispatch_reject(chttpsvr_conn *conn);
    1751              : static void parked_unlink_locked(struct chttpserver *srv, chttpsvr_conn *c);
    1752              : static void task_park_body(chttpsvr_conn *conn, struct chttpserver *srv,
    1753              :                            chttp1_stream *stream, chttpsvr_req *req);
    1754              : 
    1755              : // Returns the next capacity of a realloc'ed pointer array (initial when cap is
    1756              : // 0, else cap * 2), for the registries of this file that grow with plain
    1757              : // realloc. It returns 0, which the callers treat like a failed realloc, when
    1758              : // the doubling or the later multiplication by elem_size would overflow size_t.
    1759              : // It touches no global state, so a test can drive it with a fake cap.
    1760         1361 : static size_t doubling_growth_cap(size_t cap, size_t elem_size,
    1761              :                                   size_t initial) {
    1762         1361 :   if (cap == 0) return initial;
    1763           63 :   if (cap > SIZE_MAX / 2 || cap * 2 > SIZE_MAX / elem_size) return 0;
    1764              :   return cap * 2;
    1765              : }
    1766              : 
    1767              : #ifdef RUNNING_UNIT_TESTS
    1768              : // Returns doubling_growth_cap(cap, elem_size, initial). It exists so the tests
    1769              : // can check the overflow-safe growth rule directly.
    1770            6 : size_t chttpsvr__doubling_growth_cap_for_tests(size_t cap, size_t elem_size,
    1771              :                                                size_t initial) {
    1772            6 :   return doubling_growth_cap(cap, elem_size, initial);
    1773              : }
    1774              : #endif
    1775              : 
    1776              : #ifdef RUNNING_UNIT_TESTS
    1777              : // Test hook: The next servers_register() that has to add a server fails, as if
    1778              : // the growth of the array failed. The tests use it to reach the failed-start
    1779              : // cleanup of chttpsvr_start. The setter only stores the flag.
    1780              : static _Atomic bool g_servers_register_fail_for_tests = false;
    1781            1 : void chttpsvr__fail_next_servers_register_for_tests(void) {
    1782            1 :   atomic_store(&g_servers_register_fail_for_tests, true);
    1783            1 : }
    1784              : #endif
    1785              : 
    1786              : // Adds srv to the server registry (servers_bundler.servers) unless it's already
    1787              : // there. chttpsvr_start calls it so the idle sweep walks the server's
    1788              : // connections and an engine force-stop quiesces the server; a server outside
    1789              : // the registry gets neither. Starts and restarts both call it, so a server
    1790              : // already in the array is skipped; a duplicate would stay behind as a dangling
    1791              : // pointer after the destroy. Returns false when the array can't grow, and the
    1792              : // start then fails. It takes servers_bundler.mutex, and can be the first thing
    1793              : // in the process to touch that mutex, so it runs the engine globals init first.
    1794          317 : static bool servers_register(struct chttpserver *srv) {
    1795          317 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1796          317 :   ccol__mutex_lock(servers_bundler.mutex);
    1797         1063 :   for (size_t i = 0; i < servers_bundler.count; i++) {
    1798          764 :     if (servers_bundler.servers[i] == srv) {
    1799           18 :       ccol__mutex_unlock(servers_bundler.mutex);
    1800           18 :       return true;
    1801              :     }
    1802              :   }
    1803          299 :   bool room = servers_bundler.count < servers_bundler.capacity;
    1804              : #ifdef RUNNING_UNIT_TESTS
    1805          299 :   if (atomic_exchange(&g_servers_register_fail_for_tests, false)) {
    1806            1 :     ccol__mutex_unlock(servers_bundler.mutex);
    1807            1 :     return false;
    1808              :   }
    1809              : #endif
    1810          298 :   if (!room) {
    1811           60 :     size_t new_cap = doubling_growth_cap(servers_bundler.capacity,
    1812              :                                          sizeof(struct chttpserver *), 8);
    1813           60 :     struct chttpserver **nn = new_cap > 0
    1814           60 :                                   ? (struct chttpserver **)realloc(
    1815           60 :                                         servers_bundler.servers,
    1816              :                                         new_cap * sizeof(struct chttpserver *))
    1817              :                                   : NULL;
    1818           60 :     if (!nn) {
    1819            0 :       ccol__mutex_unlock(servers_bundler.mutex);
    1820            0 :       return false;
    1821              :     }
    1822           60 :     servers_bundler.servers = nn;
    1823           60 :     servers_bundler.capacity = new_cap;
    1824              :   }
    1825          298 :   servers_bundler.servers[servers_bundler.count++] = srv;
    1826          298 :   ccol__mutex_unlock(servers_bundler.mutex);
    1827          298 :   return true;
    1828              : }
    1829              : 
    1830              : // Removes srv from the server registry by a swap with the last entry, and does
    1831              : // nothing when srv isn't there. It's split out of servers_unregister so the
    1832              : // fork child fixup, which already holds the inherited servers_bundler.mutex,
    1833              : // can call it. The caller holds that mutex.
    1834          577 : static void servers_unregister_locked(struct chttpserver *srv) {
    1835         2012 :   for (size_t i = 0; i < servers_bundler.count; i++) {
    1836         1733 :     if (servers_bundler.servers[i] == srv) {
    1837          298 :       servers_bundler.servers[i] =
    1838          298 :           servers_bundler.servers[servers_bundler.count - 1];
    1839          298 :       servers_bundler.count--;
    1840          298 :       break;
    1841              :     }
    1842              :   }
    1843          577 : }
    1844              : 
    1845              : // Removes srv from the server registry under servers_bundler.mutex, for the
    1846              : // destroy and for a failed start. It runs the engine globals init first, like
    1847              : // every function that touches that mutex.
    1848          577 : static void servers_unregister(struct chttpserver *srv) {
    1849          577 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    1850          577 :   ccol__mutex_lock(servers_bundler.mutex);
    1851          577 :   servers_unregister_locked(srv);
    1852          577 :   ccol__mutex_unlock(servers_bundler.mutex);
    1853          577 : }
    1854              : 
    1855              : // Takes raw out of the server registry and drops its engine reference, for a
    1856              : // chttpsvr_start() that took both and then failed. Without it a failed start
    1857              : // keeps the shared reactor alive and chttpsvr_engine_wait() blocks for ever.
    1858              : // acquired_here must be the need_acquire of that start: A failed restart of a
    1859              : // server that an earlier start registered keeps its registration and its
    1860              : // reference, or the reactor could go away under its live connections. It reads
    1861              : // and clears raw->contributed_to_engine and raw->engine_gen under raw->mutex
    1862              : // and releases the engine after that lock. It may run while the start holds its
    1863              : // resolve pin, because a concurrent quiesce_server_once waits for that pin
    1864              : // before it does the same cleanup.
    1865           12 : static void chttpsvr_undo_start_registration(struct chttpserver *raw,
    1866              :                                              bool acquired_here) {
    1867           12 :   if (!acquired_here) return;
    1868           11 :   servers_unregister(raw);
    1869           11 :   bool release = false;
    1870           11 :   uintptr_t gen = 0;
    1871           11 :   ccol__mutex_lock(raw->mutex);
    1872           11 :   if (raw->contributed_to_engine) {
    1873           11 :     raw->contributed_to_engine = false;
    1874           11 :     release = true;
    1875           11 :     gen = raw->engine_gen;
    1876           11 :     raw->engine_gen = 0;
    1877              :   }
    1878           11 :   ccol__mutex_unlock(raw->mutex);
    1879           11 :   if (release) engine_release(gen);
    1880              : }
    1881              : 
    1882              : // The interval of the idle sweep, which bounds how late a timeout or a listener
    1883              : // resume can come. The batch size is the stack buffer in which a teardown pass
    1884              : // and mem_admit claim connections under a lock, so they can close or dispatch
    1885              : // them outside it.
    1886              : #define CHTTPSVR_IDLE_SWEEP_INTERVAL_MS 1000
    1887              : #define CHTTPSVR_IDLE_CLOSE_BATCH 64
    1888              : 
    1889              : // Resumes the listener registration of srv once current_connections is below
    1890              : // max_connections again. listener_on_readable pauses the listener at the cap so
    1891              : // the reactor doesn't spin on a backlog it can't accept, and this lifts the
    1892              : // pause. Only the sweep calls it: A resume straight from conn_free would touch
    1893              : // srv after the decrement that drain_and_close_all_connections waits for, and
    1894              : // the destroy could free srv under it. It reads srv->listen_reg under
    1895              : // srv->mutex. A paused listener therefore resumes within one tick.
    1896          256 : static void listener_resume_if_capacity_freed(struct chttpserver *srv) {
    1897          256 :   size_t cap = atomic_load(&srv->max_connections);
    1898          256 :   if (!cap || atomic_load(&srv->current_connections) >= cap) return;
    1899          256 :   ccol__mutex_lock(srv->mutex);
    1900          256 :   ceventloop_reg lreg = srv->listen_reg;
    1901          256 :   ccol__mutex_unlock(srv->mutex);
    1902          256 :   if (!lreg) return;
    1903          227 :   ceventloop_resume(srv_engine_bundler.reactor, lreg);
    1904              : }
    1905              : 
    1906              : // Resumes the listener registration of srv when it was paused because accept4()
    1907              : // or an allocation after it ran out of resources. The pause stops the reactor
    1908              : // from spinning on that failure, and the sweep calls this once per tick to
    1909              : // retry. It clears listener_paused_for_resource_pressure atomically and reads
    1910              : // srv->listen_reg under srv->mutex. It's kept apart from the max_connections
    1911              : // resume because the two reasons for a pause are independent. A new pause can
    1912              : // land between the exchange and the resume; the dispatch that made it sets the
    1913              : // flag again, so the next tick repeats the cycle.
    1914          241 : static void listener_resume_if_resource_pressure_cleared(
    1915              :     struct chttpserver *srv) {
    1916          241 :   if (!atomic_exchange(&srv->listener_paused_for_resource_pressure, false))
    1917              :     return;
    1918            3 :   ccol__mutex_lock(srv->mutex);
    1919            3 :   ceventloop_reg lreg = srv->listen_reg;
    1920            3 :   ccol__mutex_unlock(srv->mutex);
    1921            3 :   if (!lreg) return;
    1922            3 :   ceventloop_resume(srv_engine_bundler.reactor, lreg);
    1923              : }
    1924              : 
    1925              : // Returns the nanoseconds from earlier to later, negative when later comes
    1926              : // first, for the timeout checks.
    1927         6561 : static inline __attribute__((always_inline)) long long ns_between(
    1928              :     struct timespec later, struct timespec earlier) {
    1929         6561 :   return (long long)(later.tv_sec - earlier.tv_sec) * 1000000000LL +
    1930         6561 :          (long long)(later.tv_nsec - earlier.tv_nsec);
    1931              : }
    1932              : 
    1933              : // Returns ns as whole milliseconds rounded up, for remaining times that must
    1934              : // never be cut short.
    1935         5065 : static inline __attribute__((always_inline)) long long ms_ceil_of_ns(
    1936              :     long long ns) {
    1937           37 :   return ns > 0 ? (ns + 999999LL) / 1000000LL : ns / 1000000LL;
    1938              : }
    1939              : 
    1940              : // Tells whether at least idle_ms (non-zero) whole milliseconds lie between
    1941              : // last_activity and the sweep's time stamp. The sweep uses it for the idle
    1942              : // timeout, and conn_header_phase_expired for the header-phase limit. The sweep
    1943              : // takes its stamp before it locks idle_mutex and idle_list_add on another
    1944              : // thread can refresh last_activity after that, so the elapsed time can be
    1945              : // negative; it's signed and a negative value never times out, where an unsigned
    1946              : // compare would wrap and close a connection that just went idle. long long
    1947              : // keeps it from overflowing on ILP32.
    1948          424 : static bool conn_idle_timed_out(struct timespec now,
    1949              :                                 struct timespec last_activity,
    1950              :                                 unsigned idle_ms) {
    1951          424 :   long long elapsed_ms = ns_between(now, last_activity) / 1000000LL;
    1952          411 :   if (elapsed_ms < 0) return false;
    1953            7 :   return (unsigned long long)elapsed_ms >= (unsigned long long)idle_ms;
    1954              : }
    1955              : 
    1956              : // Tells whether conn has spent more than max_ms in the reactor phase of its
    1957              : // request (TLS handshake plus header read), counted from header_phase_start.
    1958              : // The sweep needs a total bound here because a peer that sends one header byte
    1959              : // every few seconds keeps resetting last_activity and would otherwise hold its
    1960              : // connection for ever. It's false while the phase clock isn't armed.
    1961          107 : static bool conn_header_phase_expired(struct timespec now,
    1962              :                                       const chttpsvr_conn *conn,
    1963              :                                       unsigned max_ms) {
    1964          107 :   if (!conn->header_phase_active) return false;
    1965            2 :   return conn_idle_timed_out(now, conn->header_phase_start, max_ms);
    1966              : }
    1967              : 
    1968              : // Starts the header phase clock of the current request (header_phase_start and
    1969              : // header_phase_active of conn) unless it's already running. The reactor calls
    1970              : // it at each handshake step and header read, and only the first call counts, so
    1971              : // no later step moves the deadline that conn_header_phase_expired checks.
    1972         1395 : static void conn_header_phase_arm(chttpsvr_conn *conn,
    1973              :                                   const struct timespec *now) {
    1974         1395 :   if (conn->header_phase_active) return;
    1975         1279 :   conn->header_phase_start = *now;
    1976         1279 :   conn->header_phase_active = true;
    1977              : }
    1978              : 
    1979              : #ifdef RUNNING_UNIT_TESTS
    1980              : // Returns conn_idle_timed_out(now, last_activity, idle_ms). The tests use it to
    1981              : // check a last_activity later than the sweep's stamp without racing a live
    1982              : // sweep.
    1983           11 : bool chttpsvr__conn_idle_timed_out_for_tests(struct timespec now,
    1984              :                                              struct timespec last_activity,
    1985              :                                              unsigned idle_ms) {
    1986           11 :   return conn_idle_timed_out(now, last_activity, idle_ms);
    1987              : }
    1988              : #endif
    1989              : 
    1990              : // Runs one sweep tick for srv: It resumes a paused listener, closes the idle
    1991              : // connections past the idle or header-phase limit, and ends the parked
    1992              : // connections that parked_expired judges expired (a parked body gets a 408,
    1993              : // anything else is closed). It's the only place that enforces those limits,
    1994              : // because these connections have no thread. idle_sweep_fn calls it with srv
    1995              : // pinned, and it returns the number of connections it visited. Unlinking a
    1996              : // connection from the idle or parked list under idle_mutex is the claim, so no
    1997              : // dispatch owns it at the same time; the closes and rejects run after the lock,
    1998              : // because conn_close reaches ceventloop_remove. One tick takes every expired
    1999              : // connection with no cap. Parked connections whose verdict needs a kernel query
    2000              : // are claimed under the lock, judged outside it and put back at the parked tail
    2001              : // if they survive. It also runs sweep_parked_waits and reaps retired pools.
    2002          241 : static size_t sweep_server(struct chttpserver *srv, struct timespec now) {
    2003          241 :   listener_resume_if_capacity_freed(srv);
    2004          241 :   listener_resume_if_resource_pressure_cleared(srv);
    2005              : 
    2006          241 :   unsigned idle_ms = atomic_load(&srv->idle_timeout_ms);
    2007          241 :   unsigned hdr_ms = atomic_load(&srv->max_header_read_duration_ms);
    2008          241 :   struct timespec now_slow;
    2009          241 :   slow_clock(&now_slow);
    2010              : 
    2011          241 :   chttpsvr_conn *idle_close = NULL;
    2012          241 :   chttpsvr_conn *parked_close = NULL;
    2013          241 :   chttpsvr_conn *parked_reject = NULL;
    2014          241 :   chttpsvr_conn *parked_query = NULL;
    2015          241 :   size_t expired_n = 0, lingers_n = 0;
    2016          241 :   size_t visited = 0;
    2017          241 :   ccol__mutex_lock(srv->idle_mutex);
    2018              : #ifdef RUNNING_UNIT_TESTS
    2019          241 :   g_sweep_holds_idle_mutex_for_tests = true;
    2020              : #endif
    2021          241 :   chttpsvr_conn *c = (idle_ms || hdr_ms) ? srv->idle_head : NULL;
    2022          654 :   while (c) {
    2023          413 :     chttpsvr_conn *next = c->idle_next;
    2024          413 :     visited++;
    2025          824 :     if ((idle_ms && conn_idle_timed_out(now, c->last_activity, idle_ms)) ||
    2026          656 :         (hdr_ms && conn_header_phase_expired(now, c, hdr_ms))) {
    2027          304 :       if (c->idle_prev) c->idle_prev->idle_next = c->idle_next;
    2028          304 :       if (c->idle_next) c->idle_next->idle_prev = c->idle_prev;
    2029          304 :       if (srv->idle_head == c) srv->idle_head = c->idle_next;
    2030          304 :       if (srv->idle_tail == c) srv->idle_tail = c->idle_prev;
    2031          304 :       c->idle_prev = NULL;
    2032          304 :       c->in_idle_list = false;
    2033          304 :       c->idle_next = idle_close;
    2034          304 :       idle_close = c;
    2035          304 :       expired_n++;
    2036              :     }
    2037              :     c = next;
    2038              :   }
    2039          241 :   c = srv->parked_head;
    2040          284 :   while (c) {
    2041           43 :     chttpsvr_conn *next = c->parked_next;
    2042           43 :     visited++;
    2043           43 :     if (parked_needs_kernel_query(srv, c, now, now_slow)) {
    2044           32 :       parked_unlink_locked(srv, c);
    2045           16 :       c->parked_next = parked_query;
    2046           16 :       parked_query = c;
    2047           27 :     } else if (parked_expired(srv, c, now, now_slow)) {
    2048            6 :       parked_unlink_locked(srv, c);
    2049            3 :       if (c->park == CONN_PARK_BODY) {
    2050            0 :         c->parked_next = parked_reject;
    2051            0 :         parked_reject = c;
    2052              :       } else {
    2053            3 :         c->parked_next = parked_close;
    2054            3 :         parked_close = c;
    2055              :       }
    2056            3 :       if (c->park == CONN_PARK_LINGER) lingers_n++;
    2057            3 :       expired_n++;
    2058              :     }
    2059              :     c = next;
    2060              :   }
    2061              : #ifdef RUNNING_UNIT_TESTS
    2062          241 :   g_sweep_holds_idle_mutex_for_tests = false;
    2063              : #endif
    2064          241 :   ccol__mutex_unlock(srv->idle_mutex);
    2065          241 :   if (parked_query) {
    2066              :     chttpsvr_conn *keep = NULL;
    2067           30 :     while (parked_query) {
    2068           16 :       chttpsvr_conn *q = parked_query;
    2069           16 :       parked_query = q->parked_next;
    2070           16 :       if (parked_expired(srv, q, now, now_slow)) {
    2071           10 :         if (q->park == CONN_PARK_BODY) {
    2072            8 :           q->parked_next = parked_reject;
    2073            8 :           parked_reject = q;
    2074              :         } else {
    2075            2 :           q->parked_next = parked_close;
    2076            2 :           parked_close = q;
    2077              :         }
    2078           10 :         expired_n++;
    2079              :       } else {
    2080            6 :         q->parked_next = keep;
    2081            6 :         keep = q;
    2082              :       }
    2083              :     }
    2084           14 :     ccol__mutex_lock(srv->idle_mutex);
    2085           20 :     while (keep) {
    2086            6 :       chttpsvr_conn *k = keep;
    2087            6 :       keep = k->parked_next;
    2088            6 :       k->parked_prev = srv->parked_tail;
    2089            6 :       k->parked_next = NULL;
    2090            6 :       if (srv->parked_tail) srv->parked_tail->parked_next = k;
    2091            6 :       srv->parked_tail = k;
    2092            6 :       if (!srv->parked_head) srv->parked_head = k;
    2093            6 :       k->in_parked_list = true;
    2094              :     }
    2095           14 :     ccol__mutex_unlock(srv->idle_mutex);
    2096              :   }
    2097          241 :   if (expired_n > lingers_n) {
    2098           14 :     SRV_ENGINE_LOG(clog_info, "timeout closing %zu connection(s)",
    2099              :                    expired_n - lingers_n);
    2100              :   }
    2101          545 :   while (idle_close) {
    2102          304 :     chttpsvr_conn *next = idle_close->idle_next;
    2103          304 :     idle_close->idle_next = NULL;
    2104          304 :     idle_close->park = CONN_PARK_NONE;
    2105          304 :     conn_close(idle_close);
    2106          304 :     idle_close = next;
    2107              :   }
    2108          246 :   while (parked_close) {
    2109            5 :     chttpsvr_conn *next = parked_close->parked_next;
    2110            5 :     parked_close->parked_next = NULL;
    2111            5 :     parked_close->park = CONN_PARK_NONE;
    2112            5 :     conn_close(parked_close);
    2113            5 :     parked_close = next;
    2114              :   }
    2115          249 :   while (parked_reject) {
    2116            8 :     chttpsvr_conn *r = parked_reject;
    2117            8 :     parked_reject = r->parked_next;
    2118            8 :     r->parked_next = NULL;
    2119            8 :     r->park = CONN_PARK_NONE;
    2120            8 :     r->req_rejected = true;
    2121            8 :     r->reject_status = CHTTP_STATUS_REQUEST_TIMEOUT;
    2122            8 :     conn_dispatch_reject(r);
    2123              :   }
    2124              : 
    2125          241 :   sweep_parked_waits(srv, now_slow);
    2126          241 :   if (expired_n) listener_resume_if_capacity_freed(srv);
    2127          241 :   retired_pools_reap(srv, false);
    2128          241 :   return visited;
    2129              : }
    2130              : 
    2131              : #ifdef RUNNING_UNIT_TESTS
    2132              : // Test counters of how the sweep thread stopped: Woken by the stop, or only
    2133              : // after its tick wait ran out. g_idle_sweep_stop_ns_for_tests is the
    2134              : // CLOCK_MONOTONIC instant of the last stop, guarded by
    2135              : // idle_sweep_bundler.wake_mu. The getter reads both counters.
    2136              : static _Atomic size_t g_idle_sweep_exits_woken_for_tests = 0;
    2137              : static uint64_t g_idle_sweep_stop_ns_for_tests = 0;
    2138              : static _Atomic size_t g_idle_sweep_exits_timed_out_for_tests = 0;
    2139            2 : void chttpsvr__idle_sweep_exits_for_tests(size_t *woken, size_t *timed_out) {
    2140            2 :   *woken = atomic_load(&g_idle_sweep_exits_woken_for_tests);
    2141            2 :   *timed_out = atomic_load(&g_idle_sweep_exits_timed_out_for_tests);
    2142            2 : }
    2143              : #endif
    2144              : 
    2145              : // The body of the shared sweep thread: It calls sweep_server for every
    2146              : // registered server once per tick until stop_flag is set. The idle,
    2147              : // header-phase and parked limits and the listener resumes all depend on it. It
    2148              : // waits on wake_cv until the tick deadline or a stop; the stop sets stop_flag
    2149              : // under wake_mu, so it is never missed. Then it copies servers_bundler.servers
    2150              : // and pins every server with servers_bundler_pins under servers_bundler.mutex,
    2151              : // and sweeps after that mutex is released, so a slow tick doesn't hold up
    2152              : // starts, destroys and engine stops of other servers. Each server is unpinned
    2153              : // under its own mutex with a broadcast of resolve_cv. A failed snapshot
    2154              : // allocation skips the tick.
    2155           63 : static void *idle_sweep_fn(void *arg) {
    2156           63 :   (void)arg;
    2157           63 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    2158              : #ifdef RUNNING_UNIT_TESTS
    2159           63 :   bool stopped_after_timeout = false;
    2160              : #endif
    2161          122 :   while (!atomic_load(&idle_sweep_bundler.stop_flag)) {
    2162          122 :     struct timespec tick_deadline;
    2163          122 :     clock_gettime(CLOCK_MONOTONIC, &tick_deadline);
    2164          244 :     timespec_add_ms(&tick_deadline, CHTTPSVR_IDLE_SWEEP_INTERVAL_MS);
    2165              : #ifdef RUNNING_UNIT_TESTS
    2166          122 :     bool wait_timed_out = false;
    2167              : #endif
    2168          122 :     ccol__mutex_lock(idle_sweep_bundler.wake_mu);
    2169          183 :     while (!atomic_load(&idle_sweep_bundler.stop_flag)) {
    2170          122 :       if (ccol__cond_var_timedwait(idle_sweep_bundler.wake_cv,
    2171              :                                    idle_sweep_bundler.wake_mu,
    2172              :                                    tick_deadline) == ETIMEDOUT) {
    2173              : #ifdef RUNNING_UNIT_TESTS
    2174           59 :         uint64_t deadline_ns = (uint64_t)tick_deadline.tv_sec * 1000000000ULL +
    2175           59 :                                (uint64_t)tick_deadline.tv_nsec;
    2176          118 :         wait_timed_out =
    2177           59 :             !atomic_load(&idle_sweep_bundler.stop_flag) ||
    2178            0 :             g_idle_sweep_stop_ns_for_tests + 100000000ULL < deadline_ns;
    2179              : #endif
    2180           59 :         break;
    2181              :       }
    2182              :     }
    2183          120 :     ccol__mutex_unlock(idle_sweep_bundler.wake_mu);
    2184          120 :     if (atomic_load(&idle_sweep_bundler.stop_flag)) {
    2185              : #ifdef RUNNING_UNIT_TESTS
    2186           61 :       stopped_after_timeout = wait_timed_out;
    2187              : #endif
    2188           61 :       break;
    2189              :     }
    2190              : 
    2191           59 :     struct timespec now;
    2192           59 :     clock_gettime(CLOCK_MONOTONIC, &now);
    2193              : 
    2194           59 :     ccol__mutex_lock(servers_bundler.mutex);
    2195           59 :     size_t n = servers_bundler.count;
    2196          118 :     struct chttpserver **snapshot =
    2197           56 :         n > 0 ? (struct chttpserver **)malloc(n * sizeof(struct chttpserver *))
    2198           59 :               : NULL;
    2199           59 :     if (n > 0 && !snapshot) {
    2200              :       n = 0;
    2201              :     } else {
    2202          283 :       for (size_t i = 0; i < n; i++) {
    2203          224 :         snapshot[i] = servers_bundler.servers[i];
    2204          224 :         atomic_fetch_add(&snapshot[i]->servers_bundler_pins, 1);
    2205              :       }
    2206              :     }
    2207           59 :     ccol__mutex_unlock(servers_bundler.mutex);
    2208              : 
    2209          283 :     for (size_t i = 0; i < n; i++) {
    2210          224 :       struct chttpserver *srv = snapshot[i];
    2211          224 :       sweep_server(srv, now);
    2212              : 
    2213          224 :       ccol__mutex_lock(srv->mutex);
    2214          224 :       atomic_fetch_sub(&srv->servers_bundler_pins, 1);
    2215          224 :       ccol__cond_var_broadcast(srv->resolve_cv);
    2216          224 :       ccol__mutex_unlock(srv->mutex);
    2217              :     }
    2218           59 :     free(snapshot);
    2219              :   }
    2220              : #ifdef RUNNING_UNIT_TESTS
    2221           61 :   atomic_fetch_add(stopped_after_timeout
    2222              :                        ? &g_idle_sweep_exits_timed_out_for_tests
    2223              :                        : &g_idle_sweep_exits_woken_for_tests,
    2224              :                    1);
    2225              : #endif
    2226           61 :   return NULL;
    2227              : }
    2228              : 
    2229              : #ifdef RUNNING_UNIT_TESTS
    2230              : // Test hook that makes the next start of the sweep thread fail as if
    2231              : // ccol__thread_create() had failed, so the tests can reach that failure of
    2232              : // chttpsvr_start.
    2233              : static _Atomic bool g_force_idle_sweep_thread_create_fail_for_tests = false;
    2234            2 : void chttpsvr__force_idle_sweep_thread_create_fail_for_tests(bool force) {
    2235            2 :   atomic_store(&g_force_idle_sweep_thread_create_fail_for_tests, force);
    2236            2 : }
    2237              : #endif
    2238              : // Clears idle_sweep_bundler.running in a fork() child that inherited it,
    2239              : // because the child has no sweep thread and must start its own instead of
    2240              : // joining the parent's. The caller holds servers_bundler.mutex.
    2241          375 : static void idle_sweep_forget_inherited_locked(void) {
    2242          375 :   if (idle_sweep_bundler.running && idle_sweep_bundler.pid != getpid())
    2243            0 :     idle_sweep_bundler.running = false;
    2244          375 : }
    2245              : 
    2246              : // Starts the shared sweep thread unless it runs, for chttpsvr_start. Returns
    2247              : // false only when the thread could not be created; the start then fails,
    2248              : // because the idle limits and the max_connections recovery depend on this
    2249              : // thread. It works under servers_bundler.mutex and sets
    2250              : // idle_sweep_bundler.running, pid and the cleared stop_flag.
    2251          313 : static bool idle_sweep_start_if_needed(void) {
    2252          313 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    2253          313 :   ccol__mutex_lock(servers_bundler.mutex);
    2254          313 :   idle_sweep_forget_inherited_locked();
    2255          313 :   if (!idle_sweep_bundler.running) {
    2256           64 :     atomic_store(&idle_sweep_bundler.stop_flag, false);
    2257              : #ifdef RUNNING_UNIT_TESTS
    2258           64 :     if (atomic_load(&g_force_idle_sweep_thread_create_fail_for_tests)) {
    2259              :     } else
    2260              : #endif
    2261           63 :         if (ccol__thread_create(idle_sweep_bundler.thread, idle_sweep_fn,
    2262              :                                 NULL) == 0) {
    2263           63 :       idle_sweep_bundler.running = true;
    2264           63 :       idle_sweep_bundler.pid = getpid();
    2265              :     }
    2266              :   }
    2267          313 :   bool ok = idle_sweep_bundler.running;
    2268          313 :   ccol__mutex_unlock(servers_bundler.mutex);
    2269          313 :   return ok;
    2270              : }
    2271              : 
    2272              : // Stops and joins the sweep thread. The engine reaper calls it, since the
    2273              : // thread serves every server of the engine and must not outlive it. Under
    2274              : // servers_bundler.mutex it clears idle_sweep_bundler.running and, under
    2275              : // wake_mu, sets stop_flag and signals wake_cv; the join runs after both locks
    2276              : // are released.
    2277           62 : static void idle_sweep_stop_if_running(void) {
    2278           62 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    2279           62 :   bool was_running = false;
    2280           62 :   ccol__thread_id t = {0};
    2281           62 :   ccol__mutex_lock(servers_bundler.mutex);
    2282           62 :   idle_sweep_forget_inherited_locked();
    2283           62 :   if (idle_sweep_bundler.running) {
    2284           61 :     ccol__mutex_lock(idle_sweep_bundler.wake_mu);
    2285              : #ifdef RUNNING_UNIT_TESTS
    2286              :     {
    2287           61 :       struct timespec stop_ts;
    2288           61 :       clock_gettime(CLOCK_MONOTONIC, &stop_ts);
    2289           61 :       g_idle_sweep_stop_ns_for_tests =
    2290           61 :           (uint64_t)stop_ts.tv_sec * 1000000000ULL + (uint64_t)stop_ts.tv_nsec;
    2291              :     }
    2292              : #endif
    2293           61 :     atomic_store(&idle_sweep_bundler.stop_flag, true);
    2294           61 :     ccol__cond_var_signal(idle_sweep_bundler.wake_cv);
    2295           61 :     ccol__mutex_unlock(idle_sweep_bundler.wake_mu);
    2296           61 :     t = idle_sweep_bundler.thread;
    2297           61 :     was_running = true;
    2298           61 :     idle_sweep_bundler.running = false;
    2299              :   }
    2300           62 :   ccol__mutex_unlock(servers_bundler.mutex);
    2301           62 :   if (was_running) ccol__thread_join(t);
    2302           62 : }
    2303              : 
    2304              : // Unlinks c from the parked list of srv and clears in_parked_list. Unlinking is
    2305              : // what claims a parked connection, for the sweep, a dispatch or a close. The
    2306              : // caller holds srv->idle_mutex.
    2307       153758 : static void parked_unlink_locked(struct chttpserver *srv, chttpsvr_conn *c) {
    2308           57 :   if (c->parked_prev) c->parked_prev->parked_next = c->parked_next;
    2309       153758 :   if (c->parked_next) c->parked_next->parked_prev = c->parked_prev;
    2310       153749 :   if (srv->parked_head == c) srv->parked_head = c->parked_next;
    2311       153758 :   if (srv->parked_tail == c) srv->parked_tail = c->parked_prev;
    2312       153758 :   c->parked_prev = c->parked_next = NULL;
    2313           19 :   c->in_parked_list = false;
    2314            0 : }
    2315              : 
    2316              : #ifdef RUNNING_UNIT_TESTS
    2317              : // Test counter of the ceventloop_modify calls conn_reg_modify makes, so a test
    2318              : // can see that a keep-alive request makes no direction change.
    2319              : static _Atomic size_t g_conn_reg_modify_calls_for_tests = 0;
    2320            2 : size_t chttpsvr__conn_reg_modify_calls_for_tests(void) {
    2321            2 :   return atomic_load(&g_conn_reg_modify_calls_for_tests);
    2322              : }
    2323              : #endif
    2324              : // Points conn->reg at dir and returns the result of ceventloop_modify. It skips
    2325              : // the call when conn->reg_dir already matches, which spares an ordinary
    2326              : // keep-alive request a system call. Every direction change goes through here
    2327              : // and every ceventloop_add of conn->reg sets reg_dir, so reg_dir always matches
    2328              : // the registration; it updates reg_dir on success.
    2329          916 : static inline ccol_retval conn_reg_modify(chttpsvr_conn *conn,
    2330              :                                           cselect_dir dir) {
    2331          916 :   if (conn->reg_dir == (uint8_t)dir) return ccol_success;
    2332              : #ifdef RUNNING_UNIT_TESTS
    2333           23 :   atomic_fetch_add_explicit(&g_conn_reg_modify_calls_for_tests, 1,
    2334              :                             memory_order_relaxed);
    2335              : #endif
    2336           23 :   ccol_retval rv =
    2337           23 :       ceventloop_modify(srv_engine_bundler.reactor, conn->reg, dir);
    2338           23 :   if (rv == ccol_success) conn->reg_dir = (uint8_t)dir;
    2339              :   return rv;
    2340              : }
    2341              : 
    2342              : // Puts a parked connection at the tail of the parked list, so the sweep
    2343              : // enforces its limits and a dispatch can claim it on readiness. It does nothing
    2344              : // when conn is already there, and works under srv->idle_mutex.
    2345       153752 : static void parked_list_add(chttpsvr_conn *conn) {
    2346       153752 :   struct chttpserver *srv = conn->srv;
    2347       153752 :   ccol__mutex_lock(srv->idle_mutex);
    2348       153752 :   if (!conn->in_parked_list) {
    2349       153752 :     conn->parked_prev = srv->parked_tail;
    2350       153752 :     conn->parked_next = NULL;
    2351       153752 :     if (srv->parked_tail) srv->parked_tail->parked_next = conn;
    2352       153752 :     srv->parked_tail = conn;
    2353       153752 :     if (!srv->parked_head) srv->parked_head = conn;
    2354       153752 :     conn->in_parked_list = true;
    2355              :   }
    2356       153752 :   ccol__mutex_unlock(srv->idle_mutex);
    2357       153752 : }
    2358              : 
    2359              : // Puts conn at the tail of the idle list and refreshes last_activity, so the
    2360              : // sweep can time it out and a dispatch or closer can claim it. It does nothing
    2361              : // to the list when conn is already there, and works under srv->idle_mutex.
    2362         1232 : static void idle_list_add(chttpsvr_conn *conn) {
    2363         1232 :   struct chttpserver *srv = conn->srv;
    2364         1232 :   ccol__mutex_lock(srv->idle_mutex);
    2365         1232 :   if (!conn->in_idle_list) {
    2366         1232 :     conn->idle_prev = srv->idle_tail;
    2367         1232 :     conn->idle_next = NULL;
    2368         1232 :     if (srv->idle_tail) srv->idle_tail->idle_next = conn;
    2369         1232 :     srv->idle_tail = conn;
    2370         1232 :     if (!srv->idle_head) srv->idle_head = conn;
    2371         1232 :     conn->in_idle_list = true;
    2372              :   }
    2373         1232 :   clock_gettime(CLOCK_MONOTONIC, &conn->last_activity);
    2374         1232 :   ccol__mutex_unlock(srv->idle_mutex);
    2375         1232 : }
    2376              : 
    2377              : // Takes conn out of the idle list, or out of the parked list, under
    2378              : // srv->idle_mutex, when its owner keeps it for itself or closes it.
    2379         3853 : static void idle_list_remove(chttpsvr_conn *conn) {
    2380         3853 :   struct chttpserver *srv = conn->srv;
    2381         3853 :   ccol__mutex_lock(srv->idle_mutex);
    2382         3854 :   if (conn->in_idle_list) {
    2383            0 :     if (conn->idle_prev) conn->idle_prev->idle_next = conn->idle_next;
    2384            0 :     if (conn->idle_next) conn->idle_next->idle_prev = conn->idle_prev;
    2385            0 :     if (srv->idle_head == conn) srv->idle_head = conn->idle_next;
    2386            0 :     if (srv->idle_tail == conn) srv->idle_tail = conn->idle_prev;
    2387            0 :     conn->idle_prev = conn->idle_next = NULL;
    2388            0 :     conn->in_idle_list = false;
    2389         3854 :   } else if (conn->in_parked_list) {
    2390            0 :     parked_unlink_locked(srv, conn);
    2391              :   }
    2392         3854 :   ccol__mutex_unlock(srv->idle_mutex);
    2393         3854 : }
    2394              : 
    2395              : // Adds conn to the diverted registry of srv under diverted_mutex. A bounded
    2396              : // teardown walks this registry to shutdown(2) the fd of a connection whose
    2397              : // worker stays stuck in blocking I/O. conn_start_diverted calls it for every
    2398              : // request handed to a worker, and conn_dispatch_reject for every rejection it
    2399              : // writes. It does nothing when conn is already there.
    2400         1733 : static void diverted_list_add(chttpsvr_conn *conn) {
    2401         1733 :   struct chttpserver *srv = conn->srv;
    2402         1733 :   ccol__mutex_lock(srv->diverted_mutex);
    2403         1733 :   if (!conn->in_diverted_list) {
    2404         1733 :     conn->diverted_prev = srv->diverted_tail;
    2405         1733 :     conn->diverted_next = NULL;
    2406         1733 :     if (srv->diverted_tail) srv->diverted_tail->diverted_next = conn;
    2407         1733 :     srv->diverted_tail = conn;
    2408         1733 :     if (!srv->diverted_head) srv->diverted_head = conn;
    2409         1733 :     conn->in_diverted_list = true;
    2410              :   }
    2411         1733 :   ccol__mutex_unlock(srv->diverted_mutex);
    2412         1733 : }
    2413              : 
    2414              : // Removes conn from the diverted registry under diverted_mutex once no worker
    2415              : // owns it, so a teardown leaves it alone. conn_free calls it, and so does the
    2416              : // keep-alive tail that gives conn back to the reactor.
    2417         3845 : static void diverted_list_remove(chttpsvr_conn *conn) {
    2418         3845 :   struct chttpserver *srv = conn->srv;
    2419         3845 :   ccol__mutex_lock(srv->diverted_mutex);
    2420         3845 :   if (conn->in_diverted_list) {
    2421         1733 :     if (conn->diverted_prev)
    2422           43 :       conn->diverted_prev->diverted_next = conn->diverted_next;
    2423         1733 :     if (conn->diverted_next)
    2424          106 :       conn->diverted_next->diverted_prev = conn->diverted_prev;
    2425         1733 :     if (srv->diverted_head == conn) srv->diverted_head = conn->diverted_next;
    2426         1733 :     if (srv->diverted_tail == conn) srv->diverted_tail = conn->diverted_prev;
    2427         1733 :     conn->diverted_prev = conn->diverted_next = NULL;
    2428         1733 :     conn->in_diverted_list = false;
    2429              :   }
    2430         3845 :   ccol__mutex_unlock(srv->diverted_mutex);
    2431         3845 : }
    2432              : 
    2433              : // Calls shutdown(SHUT_RDWR) on the fd of every diverted connection, so a worker
    2434              : // blocked in a read or write gets an I/O error and finishes the request
    2435              : // normally. wait_in_flight_bounded calls it after the graceful wait runs out,
    2436              : // with srv->mutex released; it walks the registry under diverted_mutex. It's
    2437              : // shutdown() and not close(), because the worker owns the fd and a close here
    2438              : // could let the number be reused under it. The result of shutdown() is ignored.
    2439            4 : static void force_unblock_diverted_connections(struct chttpserver *srv) {
    2440            4 :   ccol__mutex_lock(srv->diverted_mutex);
    2441            8 :   for (chttpsvr_conn *c = srv->diverted_head; c; c = c->diverted_next)
    2442            4 :     shutdown(c->fd, SHUT_RDWR);
    2443            4 :   ccol__mutex_unlock(srv->diverted_mutex);
    2444            4 : }
    2445              : 
    2446              : // Claims conn out of the idle or parked list under srv->idle_mutex. A dispatch,
    2447              : // the sweep and a teardown all race for unowned connections, and without this
    2448              : // claim a closer could free a connection while a reactor thread reads from it
    2449              : // (on TLS a use-after-free of the SSL object). Returns true when the caller now
    2450              : // owns conn alone, false when someone else has it and the caller must not touch
    2451              : // conn. A dispatch can fire before the add that follows its ceventloop_add; its
    2452              : // claim then fails, and level-triggered readiness reports the event again.
    2453       154625 : static bool idle_list_try_claim(chttpsvr_conn *conn) {
    2454       154625 :   struct chttpserver *srv = conn->srv;
    2455       154625 :   bool claimed = false;
    2456       154625 :   ccol__mutex_lock(srv->idle_mutex);
    2457       154625 :   if (conn->in_idle_list) {
    2458          830 :     if (conn->idle_prev) conn->idle_prev->idle_next = conn->idle_next;
    2459          830 :     if (conn->idle_next) conn->idle_next->idle_prev = conn->idle_prev;
    2460          830 :     if (srv->idle_head == conn) srv->idle_head = conn->idle_next;
    2461          830 :     if (srv->idle_tail == conn) srv->idle_tail = conn->idle_prev;
    2462          830 :     conn->idle_prev = conn->idle_next = NULL;
    2463          830 :     conn->in_idle_list = false;
    2464          830 :     claimed = true;
    2465       153795 :   } else if (conn->in_parked_list) {
    2466       153730 :     parked_unlink_locked(srv, conn);
    2467       153730 :     claimed = true;
    2468              :   }
    2469       154625 :   ccol__mutex_unlock(srv->idle_mutex);
    2470       154625 :   return claimed;
    2471              : }
    2472              : 
    2473              : // Closes every idle connection of srv, and the parked ones when include_parked
    2474              : // is set. The destroy calls it after the listener is gone; without it a
    2475              : // keep-alive connection the client never closed leaks with the server. Each
    2476              : // connection is unlinked under idle_mutex in batches, the same claim as
    2477              : // idle_list_try_claim, and closed after the lock is released.
    2478         1307 : static void close_idle_connections(struct chttpserver *srv,
    2479              :                                    bool include_parked) {
    2480           29 :   for (;;) {
    2481         1336 :     chttpsvr_conn *to_close[CHTTPSVR_IDLE_CLOSE_BATCH];
    2482         1336 :     size_t to_close_n = 0;
    2483         1336 :     ccol__mutex_lock(srv->idle_mutex);
    2484         1336 :     chttpsvr_conn *c = srv->idle_head;
    2485         1434 :     while (c && to_close_n < CHTTPSVR_IDLE_CLOSE_BATCH) {
    2486           98 :       chttpsvr_conn *next = c->idle_next;
    2487           98 :       if (c->idle_prev) c->idle_prev->idle_next = c->idle_next;
    2488           98 :       if (c->idle_next) c->idle_next->idle_prev = c->idle_prev;
    2489           98 :       if (srv->idle_head == c) srv->idle_head = c->idle_next;
    2490           98 :       if (srv->idle_tail == c) srv->idle_tail = c->idle_prev;
    2491           98 :       c->idle_prev = c->idle_next = NULL;
    2492           98 :       c->in_idle_list = false;
    2493           98 :       to_close[to_close_n++] = c;
    2494           98 :       c = next;
    2495              :     }
    2496         1345 :     while (include_parked && srv->parked_head &&
    2497              :            to_close_n < CHTTPSVR_IDLE_CLOSE_BATCH) {
    2498            9 :       c = srv->parked_head;
    2499            9 :       parked_unlink_locked(srv, c);
    2500            9 :       c->park = CONN_PARK_NONE;
    2501            9 :       to_close[to_close_n++] = c;
    2502              :     }
    2503         1336 :     ccol__mutex_unlock(srv->idle_mutex);
    2504         1336 :     if (to_close_n == 0) break;
    2505          136 :     for (size_t i = 0; i < to_close_n; i++) conn_close(to_close[i]);
    2506              :   }
    2507         1307 : }
    2508              : 
    2509              : // Closes the idle and the parked connections of srv, for the teardown.
    2510          719 : static void close_all_idle_connections(struct chttpserver *srv) {
    2511          719 :   close_idle_connections(srv, true);
    2512              : }
    2513              : 
    2514              : // Returns the value of a hex digit, or -1, for percent_decode.
    2515          136 : static int hex_nibble(char c) {
    2516           80 :   if (c >= '0' && c <= '9') return c - '0';
    2517           56 :   if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    2518           48 :   if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    2519              :   return -1;
    2520              : }
    2521              : 
    2522              : // Decodes RFC 3986 %XX escapes from src into dst, for request paths and query
    2523              : // strings. '+' becomes a space when plus_as_space is set (query strings) and
    2524              : // stays as it is otherwise (paths). It works in place with dst == src. Returns
    2525              : // the decoded length, or -1 for a malformed escape or an escape that decodes to
    2526              : // NUL: Every caller treats the result as a C string, so "foo%00bar" would
    2527              : // otherwise compare equal to the route segment "foo".
    2528         3297 : static ssize_t percent_decode(char *dst, const char *src, bool plus_as_space) {
    2529         3297 :   size_t si = 0, di = 0;
    2530        36936 :   while (src[si]) {
    2531        33663 :     char c = src[si];
    2532        33663 :     if (c == '%') {
    2533           68 :       char c1 = src[si + 1];
    2534           68 :       if (!c1) return -1;
    2535           68 :       int hi = hex_nibble(c1);
    2536           68 :       char c2 = src[si + 2];
    2537           68 :       int lo = hex_nibble(c2);
    2538           68 :       if (hi < 0 || lo < 0) return -1;
    2539           50 :       char decoded = (char)((hi << 4) | lo);
    2540           50 :       if (decoded == '\0') return -1;
    2541           44 :       dst[di++] = decoded;
    2542           44 :       si += 3;
    2543        33595 :     } else if (c == '+' && plus_as_space) {
    2544            2 :       dst[di++] = ' ';
    2545            2 :       si++;
    2546              :     } else {
    2547        33593 :       dst[di++] = c;
    2548        33593 :       si++;
    2549              :     }
    2550              :   }
    2551         3273 :   return (ssize_t)di;
    2552              : }
    2553              : 
    2554              : // Percent-decodes a path segment, where '+' is literal, for the route search.
    2555         2788 : static ssize_t decode_path_unsafe(char *dst, const char *src) {
    2556         2788 :   return percent_decode(dst, src, false);
    2557              : }
    2558              : 
    2559              : // Percent-decodes a query string part, where '+' is a space, for the query
    2560              : // parameters.
    2561          509 : static ssize_t decode_url_unsafe(char *dst, const char *src) {
    2562          509 :   return percent_decode(dst, src, true);
    2563              : }
    2564              : 
    2565              : // Turns an absolute-form request target ("http://host/items") into the
    2566              : // origin-form slice inside it. RFC 7230 section 5.3.2 makes a server accept
    2567              : // that form, which clients send through a proxy, and without this it would
    2568              : // route as four segments and get a 404. Only http and https are recognised,
    2569              : // case-insensitively; the authority is dropped on purpose, since we route on
    2570              : // the path alone and section 5.4 says to ignore Host here. *out and *out_len
    2571              : // describe a slice of target. Returns true when a prefix was stripped, because
    2572              : // an empty path then means "/".
    2573         1206 : static bool strip_absolute_form(const char *target, size_t target_len,
    2574              :                                 const char **out, size_t *out_len) {
    2575         1206 :   *out = target;
    2576         1206 :   *out_len = target_len;
    2577              : 
    2578         1206 :   size_t scheme_len;
    2579         1206 :   if (target_len > 7 && ccol_ascii_ncasecmp(target, "http://", 7) == 0)
    2580              :     scheme_len = 7;
    2581          508 :   else if (target_len > 8 && ccol_ascii_ncasecmp(target, "https://", 8) == 0)
    2582              :     scheme_len = 8;
    2583              :   else
    2584              :     return false;
    2585              : 
    2586            9 :   size_t i = scheme_len;
    2587          103 :   while (i < target_len && target[i] != '/' && target[i] != '?' &&
    2588              :          target[i] != '#')
    2589           94 :     i++;
    2590              : 
    2591            9 :   *out = target + i;
    2592            9 :   *out_len = target_len - i;
    2593            9 :   return true;
    2594              : }
    2595              : 
    2596              : // The method parse_method returns for a method it doesn't know. It's outside
    2597              : // the public enum, so no route can match it.
    2598              : #define CHTTP_METHOD_UNKNOWN ((chttp_method)(CHTTP_ANY + 1))
    2599              : 
    2600              : // The largest body "OPTIONS *" may carry with the connection kept alive. A
    2601              : // bigger body is discarded and the connection closes after the 200, as in Go's
    2602              : // net/http.
    2603              : #define CHTTPSVR_OPTIONS_STAR_MAX_BODY ((size_t)4096)
    2604              : 
    2605              : // Does nothing. It's the handler of options_star_route, the route that "OPTIONS
    2606              : // *" matches; that route is never registered and only lets the worker path
    2607              : // treat the request as a buffered route. task_worker answers the request
    2608              : // itself, so this never runs.
    2609            0 : static void options_star_unused_handler(chttpsvr_req *req, chttpsvr_resp *resp,
    2610              :                                         void *ctx) {
    2611            0 :   (void)req;
    2612            0 :   (void)resp;
    2613            0 :   (void)ctx;
    2614            0 : }
    2615              : static chttpsvr_route options_star_route = {.method = CHTTP_OPTIONS,
    2616              :                                             .fn = options_star_unused_handler};
    2617              : 
    2618              : static void chttpsvr_next(chttpsvr_req *req, chttpsvr_resp *resp);
    2619              : static void task_worker(void *arg);
    2620              : #ifdef RUNNING_UNIT_TESTS
    2621              : // Test counter of the requests conn_start_diverted hands to the worker pool.
    2622              : atomic_size_t chttpsvr__worker_submits_for_tests;
    2623              : #endif
    2624              : static void task_resume(void *arg);
    2625              : static void reject_task(void *arg);
    2626              : static void destroy_resp(chttpsvr_resp *resp, ccol_memmgmt_procs *mp);
    2627              : static void conn_on_readable(ceventloop loop, ceventloop_reg reg,
    2628              :                              cselectable *sel, void *arg);
    2629              : static void conn_on_writable(ceventloop loop, ceventloop_reg reg,
    2630              :                              cselectable *sel, void *arg);
    2631              : static void conn_on_error(ceventloop loop, ceventloop_reg reg, cselectable *sel,
    2632              :                           void *arg);
    2633              : static void listener_on_readable(ceventloop loop, ceventloop_reg reg,
    2634              :                                  cselectable *sel, void *arg);
    2635              : 
    2636              : // Splits a route pattern such as "/users/{id}" into segments and collects the
    2637              : // names of its {name} segments, which route registration stores for the route
    2638              : // search. The pattern must start with '/', must not end with one and must not
    2639              : // hold "//". A name is letters, digits and '_', and the same name twice is
    2640              : // refused, because chttpsvr_req_param would only ever return the first. On
    2641              : // success the four out-parameters receive arrays allocated from mp (NULL and 0
    2642              : // for "/"). Returns ccol_invalid_args or ccol_not_enough_memory and frees
    2643              : // everything on failure.
    2644          928 : static ccol_retval compile_pattern(const char *pattern, char ***segs_out,
    2645              :                                    int *seg_count_out, char ***param_names_out,
    2646              :                                    int *param_count_out,
    2647              :                                    ccol_memmgmt_procs *mp) {
    2648          928 :   if (pattern[0] != '/') return ccol_invalid_args;
    2649              : 
    2650          925 :   const char *p = pattern;
    2651          925 :   if (*p == '/') p++;
    2652              : 
    2653              :   {
    2654          925 :     size_t plen = strlen(p);
    2655          925 :     if (plen > 0 && p[plen - 1] == '/') return ccol_invalid_args;
    2656              :   }
    2657              : 
    2658              :   int seg_count = 0;
    2659              :   {
    2660              :     const char *s = p;
    2661         1080 :     while (*s) {
    2662         1075 :       const char *e = strchr(s, '/');
    2663         1075 :       size_t len = e ? (size_t)(e - s) : strlen(s);
    2664         1075 :       if (len == 0 && e != NULL) return ccol_invalid_args;
    2665         1073 :       if (len > 0) seg_count++;
    2666         1073 :       if (!e) break;
    2667          157 :       s = e + 1;
    2668              :     }
    2669              :   }
    2670              : 
    2671          921 :   if (seg_count == 0) {
    2672            5 :     *segs_out = NULL;
    2673            5 :     *seg_count_out = 0;
    2674            5 :     *param_names_out = NULL;
    2675            5 :     *param_count_out = 0;
    2676            5 :     return ccol_success;
    2677              :   }
    2678              : 
    2679          916 :   char **segs =
    2680          916 :       (char **)ccol__mem_calloc(mp, (size_t)seg_count, sizeof(char *));
    2681          916 :   if (!segs) return ccol_not_enough_memory;
    2682              : 
    2683              :   int si = 0;
    2684              :   int param_count = 0;
    2685              :   const char *s = p;
    2686         1059 :   while (*s && si < seg_count) {
    2687         1059 :     const char *e = strchr(s, '/');
    2688         1059 :     size_t len = e ? (size_t)(e - s) : strlen(s);
    2689         1059 :     if (len == 0) {
    2690            0 :       if (!e) break;
    2691            0 :       s = e + 1;
    2692            0 :       continue;
    2693              :     }
    2694         1059 :     segs[si] = (char *)ccol__mem_alloc(mp, len + 1);
    2695         1059 :     if (!segs[si]) {
    2696           13 :       for (int j = 0; j < si; j++) ccol__mem_free(mp, segs[j]);
    2697            6 :       ccol__mem_free(mp, segs);
    2698            6 :       return ccol_not_enough_memory;
    2699              :     }
    2700         1053 :     memcpy(segs[si], s, len);
    2701         1053 :     segs[si][len] = '\0';
    2702         1053 :     if (segs[si][0] == '{') {
    2703          123 :       if (len < 3 || segs[si][len - 1] != '}') {
    2704            2 :         for (int j = 0; j <= si; j++) ccol__mem_free(mp, segs[j]);
    2705            1 :         ccol__mem_free(mp, segs);
    2706            1 :         return ccol_invalid_args;
    2707              :       }
    2708          387 :       for (size_t ci = 1; ci < len - 1; ci++) {
    2709          268 :         char c = segs[si][ci];
    2710          273 :         if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
    2711            5 :               (c >= '0' && c <= '9') || c == '_')) {
    2712            6 :           for (int j = 0; j <= si; j++) ccol__mem_free(mp, segs[j]);
    2713            3 :           ccol__mem_free(mp, segs);
    2714            3 :           return ccol_invalid_args;
    2715              :         }
    2716              :       }
    2717          119 :       param_count++;
    2718              :     }
    2719         1049 :     si++;
    2720         1049 :     if (!e) break;
    2721          145 :     s = e + 1;
    2722              :   }
    2723              : 
    2724          904 :   char **param_names = NULL;
    2725          904 :   if (param_count > 0) {
    2726           74 :     param_names =
    2727           74 :         (char **)ccol__mem_calloc(mp, (size_t)param_count, sizeof(char *));
    2728           74 :     if (!param_names) {
    2729            8 :       for (int j = 0; j < seg_count; j++) ccol__mem_free(mp, segs[j]);
    2730            2 :       ccol__mem_free(mp, segs);
    2731            2 :       return ccol_not_enough_memory;
    2732              :     }
    2733              :     int pi = 0;
    2734          259 :     for (int i = 0; i < seg_count; i++) {
    2735          193 :       if (segs[i][0] == '{') {
    2736          113 :         size_t len = strlen(segs[i]);
    2737          113 :         param_names[pi] = (char *)ccol__mem_alloc(mp, len - 1);
    2738          113 :         if (!param_names[pi]) {
    2739            4 :           for (int j = 0; j < pi; j++) ccol__mem_free(mp, param_names[j]);
    2740            3 :           ccol__mem_free(mp, param_names);
    2741           13 :           for (int j = 0; j < seg_count; j++) ccol__mem_free(mp, segs[j]);
    2742            3 :           ccol__mem_free(mp, segs);
    2743            3 :           return ccol_not_enough_memory;
    2744              :         }
    2745          110 :         memcpy(param_names[pi], segs[i] + 1, len - 2);
    2746          110 :         param_names[pi][len - 2] = '\0';
    2747          151 :         for (int j = 0; j < pi; j++) {
    2748           44 :           if (strcmp(param_names[j], param_names[pi]) == 0) {
    2749            9 :             for (int k = 0; k <= pi; k++) ccol__mem_free(mp, param_names[k]);
    2750            3 :             ccol__mem_free(mp, param_names);
    2751           14 :             for (int k = 0; k < seg_count; k++) ccol__mem_free(mp, segs[k]);
    2752            3 :             ccol__mem_free(mp, segs);
    2753            3 :             return ccol_invalid_args;
    2754              :           }
    2755              :         }
    2756          107 :         pi++;
    2757              :       }
    2758              :     }
    2759              :   }
    2760              : 
    2761          896 :   *segs_out = segs;
    2762          896 :   *seg_count_out = seg_count;
    2763          896 :   *param_names_out = param_names;
    2764          896 :   *param_count_out = param_count;
    2765          896 :   return ccol_success;
    2766              : }
    2767              : 
    2768              : // Frees the segments and parameter names of a compiled route, when the route or
    2769              : // its router goes away.
    2770          901 : static void free_route_data(chttpsvr_route *r, ccol_memmgmt_procs *mp) {
    2771         1916 :   for (int i = 0; i < r->seg_count; i++) ccol__mem_free(mp, r->segs[i]);
    2772          901 :   ccol__mem_free(mp, r->segs);
    2773         1004 :   for (int i = 0; i < r->param_count; i++)
    2774          103 :     ccol__mem_free(mp, r->param_names[i]);
    2775          901 :   ccol__mem_free(mp, r->param_names);
    2776          901 : }
    2777              : 
    2778              : // The outcome of a route search: A match, a path that matches with another
    2779              : // method (405), an allocation failure, or no match (404).
    2780              : typedef enum {
    2781              :   ROUTE_MATCH_OK,
    2782              :   ROUTE_MATCH_METHOD,
    2783              :   ROUTE_MATCH_OOM,
    2784              :   ROUTE_MATCH_NONE
    2785              : } route_match;
    2786              : 
    2787              : // The result of find_route. router is the router of the match, or for a 405 or
    2788              : // 404 the sub-router that owns the path and runs its middleware (NULL for the
    2789              : // root). On a match the caller frees param_values. allowed_methods has one bit
    2790              : // per method that matches the path, HEAD included where it falls back to GET,
    2791              : // and feeds the Allow header of a 405.
    2792              : typedef struct {
    2793              :   chttpsvr_router *router;
    2794              :   chttpsvr_route *route;
    2795              :   char **param_values;
    2796              :   route_match result;
    2797              :   uint8_t allowed_methods;
    2798              : } match_result;
    2799              : 
    2800              : // One raw segment of a request path and its percent-decoded value, decoded on
    2801              : // first use and kept, so a router decodes each segment once however many routes
    2802              : // try it. raw points into the path and isn't NUL-terminated. ok is meaningful
    2803              : // once attempted is set and tells whether decoded holds a value.
    2804              : typedef struct {
    2805              :   const char *raw;
    2806              :   size_t raw_len;
    2807              :   bool attempted;
    2808              :   bool ok;
    2809              :   char *decoded;
    2810              :   size_t decoded_len;
    2811              : } seg_cache_entry;
    2812              : 
    2813              : // The segment cache of one path. count is the number of entries filled; see
    2814              : // seg_cache_build for why it stands in for the real segment count.
    2815              : typedef struct {
    2816              :   seg_cache_entry *entries;
    2817              :   size_t count;
    2818              :   ccol_memmgmt_procs *mp;
    2819              : } seg_cache;
    2820              : 
    2821              : // Splits sub_path on '/' into raw segments, without decoding them, and fills
    2822              : // cache with at most cap of them. The route search shares the cache between all
    2823              : // routes of a router so each segment is decoded once. It strips the leading
    2824              : // slash and keeps empty segments exactly like the route walk; a trailing '/'
    2825              : // counts as one more empty segment, so "/items/{id}" doesn't match "items/99/".
    2826              : // cap must be larger than the seg_count of every route of the router, so count
    2827              : // == seg_count is an exact test, and the cache size depends on the routes,
    2828              : // which the operator controls, and not on the path, which the client controls.
    2829              : // Returns 0, or -1 when out of memory.
    2830         1560 : static int seg_cache_build(const char *sub_path, size_t cap, seg_cache *cache,
    2831              :                            ccol_memmgmt_procs *mp) {
    2832         1560 :   cache->entries = NULL;
    2833         1560 :   cache->count = 0;
    2834         1560 :   cache->mp = mp;
    2835         1560 :   if (cap == 0) return 0;
    2836              : 
    2837         1560 :   const char *p = sub_path;
    2838         1560 :   if (*p == '/') p++;
    2839         1560 :   if (*p == '\0') return 0;
    2840              : 
    2841              :   size_t count = 0;
    2842              :   {
    2843              :     const char *s = p;
    2844         1884 :     while (count < cap) {
    2845         1835 :       const char *e = strchr(s, '/');
    2846         1835 :       count++;
    2847         1835 :       if (!e) break;
    2848          343 :       s = e + 1;
    2849              :     }
    2850              :   }
    2851              : 
    2852         1541 :   seg_cache_entry *entries =
    2853         1541 :       (seg_cache_entry *)ccol__mem_calloc(mp, count, sizeof(seg_cache_entry));
    2854         1541 :   if (!entries) return -1;
    2855              : 
    2856              :   size_t idx = 0;
    2857              :   const char *s = p;
    2858         1877 :   while (idx < count) {
    2859         1829 :     const char *e = strchr(s, '/');
    2860         1829 :     size_t len = e ? (size_t)(e - s) : strlen(s);
    2861         1829 :     entries[idx].raw = s;
    2862         1829 :     entries[idx].raw_len = len;
    2863         1829 :     idx++;
    2864         1829 :     if (!e) break;
    2865          338 :     s = e + 1;
    2866              :   }
    2867              : 
    2868         1539 :   cache->entries = entries;
    2869         1539 :   cache->count = count;
    2870         1539 :   return 0;
    2871              : }
    2872              : 
    2873              : // Frees the decoded values and the entries of the cache at the end of a route
    2874              : // search.
    2875         2251 : static void seg_cache_free(seg_cache *cache) {
    2876         2251 :   if (!cache->entries) return;
    2877         3368 :   for (size_t i = 0; i < cache->count; i++)
    2878         1829 :     ccol__mem_free(cache->mp, cache->entries[i].decoded);
    2879         1539 :   ccol__mem_free(cache->mp, cache->entries);
    2880         1539 :   cache->entries = NULL;
    2881         1539 :   cache->count = 0;
    2882              : }
    2883              : 
    2884              : // Returns the decoded value of segment idx, decoding it on the first call and
    2885              : // keeping it in the cache, so the routes and prefixes that ask share one
    2886              : // decode. NULL means the segment can't match anything: It's empty or its
    2887              : // encoding is malformed. The cache owns the result until seg_cache_free;
    2888              : // *len_out gets its length. *oom_out is set on an allocation failure. That
    2889              : // failure is remembered like the other outcomes and never retried, which is
    2890              : // safe only because every caller aborts the whole route search on it.
    2891        13156 : static const char *seg_cache_get(seg_cache *cache, size_t idx, size_t *len_out,
    2892              :                                  bool *oom_out) {
    2893        13156 :   *oom_out = false;
    2894        13156 :   seg_cache_entry *e = &cache->entries[idx];
    2895        13156 :   if (e->attempted) {
    2896        11455 :     if (!e->ok) return NULL;
    2897        11200 :     *len_out = e->decoded_len;
    2898        11200 :     return e->decoded;
    2899              :   }
    2900         1701 :   e->attempted = true;
    2901         1701 :   if (e->raw_len == 0) return NULL;
    2902              : 
    2903         1695 :   char *decoded = (char *)ccol__mem_alloc(cache->mp, e->raw_len + 1);
    2904         1695 :   if (!decoded) {
    2905            5 :     *oom_out = true;
    2906            5 :     return NULL;
    2907              :   }
    2908         1690 :   memcpy(decoded, e->raw, e->raw_len);
    2909         1690 :   decoded[e->raw_len] = '\0';
    2910         1690 :   ssize_t dlen = decode_path_unsafe(decoded, decoded);
    2911         1690 :   if (dlen < 0) {
    2912           14 :     ccol__mem_free(cache->mp, decoded);
    2913           14 :     return NULL;
    2914              :   }
    2915         1676 :   decoded[(size_t)dlen] = '\0';
    2916         1676 :   e->ok = true;
    2917         1676 :   e->decoded = decoded;
    2918         1676 :   e->decoded_len = (size_t)dlen;
    2919         1676 :   *len_out = e->decoded_len;
    2920         1676 :   return decoded;
    2921              : }
    2922              : 
    2923              : // Matches route against the shared segment cache, for find_route; a route with
    2924              : // a different segment count is rejected before anything is decoded. On a match
    2925              : // *pv_out (when given) gets a new array of copies of the parameter values,
    2926              : // because the cache's values must stay intact for the next route. A NULL pv_out
    2927              : // only probes whether the path matches, to tell a 405 from a 404. Returns 1 for
    2928              : // a match, 0 for none and -1 when out of memory, which ends the whole search.
    2929        11970 : static int match_route_cached(seg_cache *cache, chttpsvr_route *route,
    2930              :                               char ***pv_out, ccol_memmgmt_procs *mp) {
    2931        11970 :   if ((size_t)route->seg_count != cache->count) return 0;
    2932        10490 :   if (route->seg_count == 0) {
    2933           13 :     if (pv_out) *pv_out = NULL;
    2934           13 :     return 1;
    2935              :   }
    2936              : 
    2937              :   char **pv = NULL;
    2938              :   int param_idx = 0;
    2939        11637 :   for (int i = 0; i < route->seg_count; i++) {
    2940        10616 :     size_t dlen = 0;
    2941        10616 :     bool oom = false;
    2942        10616 :     const char *decoded = seg_cache_get(cache, (size_t)i, &dlen, &oom);
    2943        10616 :     if (!decoded) {
    2944          226 :       if (oom) {
    2945            4 :         if (pv) {
    2946            4 :           for (int j = 0; j < param_idx; j++) ccol__mem_free(mp, pv[j]);
    2947            2 :           ccol__mem_free(mp, pv);
    2948              :         }
    2949            7 :         return -1;
    2950              :       }
    2951          222 :       goto no_match;
    2952              :     }
    2953              : 
    2954        10390 :     if (route->segs[i][0] == '{') {
    2955          101 :       if (pv_out) {
    2956          100 :         if (!pv) {
    2957           60 :           pv = (char **)ccol__mem_calloc(mp, (size_t)route->param_count,
    2958              :                                          sizeof(char *));
    2959           60 :           if (!pv) return -1;
    2960              :         }
    2961           99 :         char *val = (char *)ccol__mem_alloc(mp, dlen + 1);
    2962           99 :         if (!val) {
    2963            3 :           for (int j = 0; j < param_idx; j++) ccol__mem_free(mp, pv[j]);
    2964            2 :           ccol__mem_free(mp, pv);
    2965            2 :           return -1;
    2966              :         }
    2967           97 :         memcpy(val, decoded, dlen + 1);
    2968           97 :         pv[param_idx++] = val;
    2969              :       }
    2970              :     } else {
    2971        10289 :       if (strcmp(decoded, route->segs[i]) != 0) goto no_match;
    2972              :     }
    2973              :   }
    2974         1021 :   if (pv_out) *pv_out = pv;
    2975              :   return 1;
    2976              : 
    2977         9449 : no_match:
    2978         9449 :   if (pv) {
    2979            4 :     for (int j = 0; j < param_idx; j++) ccol__mem_free(mp, pv[j]);
    2980            2 :     ccol__mem_free(mp, pv);
    2981              :   }
    2982              :   return 0;
    2983              : }
    2984              : 
    2985              : // Decides whether router->prefix owns the request path in cache, so find_route
    2986              : // can pick the sub-router whose routes and middleware handle the request. The
    2987              : // cache is built once from the full path and shared between the sub-routers.
    2988              : // Ownership is judged on the decoded path, as chttpsvr_req_path() reports it,
    2989              : // so "/admin%2Fsecret" belongs to the "/admin" mount. Returns 1 when the prefix
    2990              : // ends between raw segments (*sub_path_out gets the rest of the path), 2 when
    2991              : // it ends inside a segment whose decoded value holds a '/' (the router answers
    2992              : // 404), 0 when it doesn't own the path, and -1 when out of memory.
    2993         2800 : static int prefix_matches(seg_cache *cache, chttpsvr_router *router,
    2994              :                           const char **sub_path_out) {
    2995         2800 :   const char *pp = router->prefix + 1;
    2996              : 
    2997         2800 :   if (*pp == '\0') {
    2998          269 :     if (cache->count != 0) return 0;
    2999            3 :     *sub_path_out = "/";
    3000            3 :     return 1;
    3001              :   }
    3002              : 
    3003         2531 :   size_t prem = router->prefix_len - 1;
    3004         2531 :   size_t idx = 0;
    3005         2619 :   for (;;) {
    3006         5106 :     if (idx >= cache->count) return 0;
    3007              : 
    3008         2540 :     size_t dlen = 0;
    3009         2540 :     bool oom = false;
    3010         2540 :     const char *decoded = seg_cache_get(cache, idx, &dlen, &oom);
    3011         2540 :     if (oom) return -1;
    3012         2539 :     if (!decoded) return 0;
    3013              : 
    3014         2486 :     if (dlen < prem) {
    3015         1080 :       if (memcmp(decoded, pp, dlen) != 0 || pp[dlen] != '/') return 0;
    3016           44 :       pp += dlen + 1;
    3017           44 :       prem -= dlen + 1;
    3018           44 :       idx++;
    3019           44 :       continue;
    3020              :     }
    3021         1406 :     if (memcmp(decoded, pp, prem) != 0) return 0;
    3022           89 :     if (dlen == prem) {
    3023           82 :       const char *rp_after_last_seg =
    3024           82 :           cache->entries[idx].raw + cache->entries[idx].raw_len;
    3025           82 :       *sub_path_out = (*rp_after_last_seg == '\0') ? "/" : rp_after_last_seg;
    3026           82 :       return 1;
    3027              :     }
    3028            7 :     return decoded[prem] == '/' ? 2 : 0;
    3029              :   }
    3030              : }
    3031              : 
    3032              : static void free_param_values(char **pv, int count, ccol_memmgmt_procs *mp);
    3033              : 
    3034              : // Finds the route that answers method on path. http1_on_headers_complete calls
    3035              : // it for every request, and its result decides which handler runs and which
    3036              : // middleware chain runs with it. The caller holds srv->routes_lock. It returns
    3037              : // the matched router, route and decoded path parameter values (the caller owns
    3038              : // the values), or a 404 or 405 result with the owning router, or
    3039              : // ROUTE_MATCH_OOM.
    3040              : // Precedence comes from how specific a mount prefix is, never from the order of
    3041              : // registration. srv->routers keeps the root at index 0 and the sub-routers in
    3042              : // descending prefix segment count, so the loop visits the sub-routers first and
    3043              : // the root last. If the root went first, a pattern like "/{a}/{b}" would answer
    3044              : // paths inside a mount and its middleware (an authenticator, say) would be
    3045              : // skipped.
    3046              : // The most specific mount that owns the path owns the request: Only routers on
    3047              : // that same prefix may answer, and when none of their routes matches, the 404
    3048              : // or 405 comes back with that owner as the router so its middleware runs for
    3049              : // the rejection too.
    3050              : // A HEAD request also matches a GET route (RFC 9110 SS9.3.2), but only after
    3051              : // the whole router has been scanned, since an explicit HEAD or ANY route must
    3052              : // win. A path that matched with the wrong method sets a bit in allowed_methods
    3053              : // for the Allow header of the 405. Both segment caches are capped by operator
    3054              : // settings (max_prefix_seg_count, max_route_seg_count), never by the number of
    3055              : // segments in the client's path.
    3056         1131 : static match_result find_route(struct chttpserver *srv, const char *path,
    3057              :                                chttp_method method) {
    3058         1131 :   unsigned allowed_methods = 0;
    3059              : 
    3060         1131 :   seg_cache path_cache = {0};
    3061         1131 :   if (srv->router_count > 1) {
    3062          438 :     if (seg_cache_build(path, (size_t)srv->max_prefix_seg_count + 1,
    3063              :                         &path_cache, srv->m_procs) != 0)
    3064            1 :       return (match_result){NULL, NULL, NULL, ROUTE_MATCH_OOM, 0};
    3065              :   }
    3066              : 
    3067              :   chttpsvr_router *owner = NULL;
    3068         3945 :   for (size_t visit = 0; visit < srv->router_count; visit++) {
    3069         3860 :     size_t ri = (visit + 1 < srv->router_count) ? visit + 1 : 0;
    3070         3860 :     chttpsvr_router *router = srv->routers[ri];
    3071              : 
    3072         3860 :     const char *sub_path = NULL;
    3073         3860 :     if (router->prefix_len == 0) {
    3074         1055 :       if (owner) break;
    3075         1041 :       sub_path = path;
    3076              :     } else {
    3077         2805 :       if (owner && router->prefix_seg_count < owner->prefix_seg_count) break;
    3078         2800 :       int pm = prefix_matches(&path_cache, router, &sub_path);
    3079         2800 :       if (pm < 0) {
    3080            1 :         seg_cache_free(&path_cache);
    3081            1 :         return (match_result){NULL, NULL, NULL, ROUTE_MATCH_OOM, 0};
    3082              :       }
    3083         2806 :       if (pm == 0) continue;
    3084           88 :       if (!owner) owner = router;
    3085           88 :       if (pm == 2) continue;
    3086              :     }
    3087              : 
    3088         1126 :     if (router->route_count == 0) continue;
    3089              : 
    3090         1122 :     seg_cache cache;
    3091         1122 :     if (seg_cache_build(sub_path, (size_t)router->max_route_seg_count + 1,
    3092              :                         &cache, srv->m_procs) != 0) {
    3093            1 :       seg_cache_free(&path_cache);
    3094            1 :       return (match_result){NULL, NULL, NULL, ROUTE_MATCH_OOM, 0};
    3095              :     }
    3096              : 
    3097        12072 :     match_result found = {NULL, NULL, NULL, ROUTE_MATCH_NONE, 0};
    3098        12072 :     bool have_result = false;
    3099              :     chttpsvr_route *head_fallback_route = NULL;
    3100              :     char **head_fallback_pv = NULL;
    3101        12072 :     for (size_t i = 0; i < router->route_count; i++) {
    3102        11970 :       chttpsvr_route *route = router->routes[i];
    3103              : 
    3104        11970 :       char **pv = NULL;
    3105        11970 :       bool method_ok = (route->method == CHTTP_ANY || route->method == method);
    3106        23940 :       bool head_ok =
    3107        11970 :           !method_ok && method == CHTTP_HEAD && route->method == CHTTP_GET;
    3108        15881 :       int ms = match_route_cached(
    3109              :           &cache, route, (method_ok || head_ok) ? &pv : NULL, srv->m_procs);
    3110        11970 :       if (ms == -1) {
    3111              :         found = (match_result){NULL, NULL, NULL, ROUTE_MATCH_OOM, 0};
    3112              :         have_result = true;
    3113              :         break;
    3114              :       }
    3115        11985 :       if (ms == 0) continue;
    3116              : 
    3117         1034 :       if (!method_ok) {
    3118           22 :         if (head_ok) {
    3119            6 :           if (!head_fallback_route) {
    3120            6 :             head_fallback_route = route;
    3121            6 :             head_fallback_pv = pv;
    3122              :           } else {
    3123            0 :             free_param_values(pv, route->param_count, srv->m_procs);
    3124              :           }
    3125            6 :           continue;
    3126              :         }
    3127           16 :         allowed_methods |= 1u << route->method;
    3128           16 :         if (route->method == CHTTP_GET) allowed_methods |= 1u << CHTTP_HEAD;
    3129           16 :         continue;
    3130              :       }
    3131         1012 :       found = (match_result){router, route, pv, ROUTE_MATCH_OK, 0};
    3132         1012 :       have_result = true;
    3133         1012 :       break;
    3134              :     }
    3135         1121 :     if (!have_result && head_fallback_route) {
    3136            5 :       found = (match_result){router, head_fallback_route, head_fallback_pv,
    3137              :                              ROUTE_MATCH_OK, 0};
    3138            5 :       have_result = true;
    3139            5 :       head_fallback_pv = NULL;
    3140              :     }
    3141         1121 :     free_param_values(
    3142              :         head_fallback_pv,
    3143              :         head_fallback_route ? head_fallback_route->param_count : 0,
    3144              :         srv->m_procs);
    3145         1121 :     seg_cache_free(&cache);
    3146         1121 :     if (have_result) {
    3147         1024 :       seg_cache_free(&path_cache);
    3148         1024 :       return found;
    3149              :     }
    3150              :   }
    3151          104 :   seg_cache_free(&path_cache);
    3152          104 :   if (allowed_methods)
    3153           10 :     return (match_result){owner, NULL, NULL, ROUTE_MATCH_METHOD,
    3154           10 :                           (uint8_t)allowed_methods};
    3155           94 :   return (match_result){owner, NULL, NULL, ROUTE_MATCH_NONE, 0};
    3156              : }
    3157              : 
    3158              : // Frees an array of count path parameter values and the array itself; NULL does
    3159              : // nothing. find_route and every teardown of a request's state use it, because
    3160              : // each matched route leaves such an array on the connection.
    3161         4569 : static void free_param_values(char **pv, int count, ccol_memmgmt_procs *mp) {
    3162         4569 :   if (!pv) return;
    3163          145 :   for (int i = 0; i < count; i++) ccol__mem_free(mp, pv[i]);
    3164           53 :   ccol__mem_free(mp, pv);
    3165              : }
    3166              : 
    3167              : // Maps a request method token to its chttp_method. http1_on_request_line uses
    3168              : // it to pick the method routes match on, and returns 501 for the
    3169              : // CHTTP_METHOD_UNKNOWN it gives for any token outside the seven we implement.
    3170         1269 : static chttp_method parse_method(const char *s, size_t len) {
    3171         1269 :   if (len == 3 && memcmp(s, "GET", 3) == 0) return CHTTP_GET;
    3172          342 :   if (len == 4 && memcmp(s, "POST", 4) == 0) return CHTTP_POST;
    3173           80 :   if (len == 3 && memcmp(s, "PUT", 3) == 0) return CHTTP_PUT;
    3174           73 :   if (len == 6 && memcmp(s, "DELETE", 6) == 0) return CHTTP_DELETE;
    3175           72 :   if (len == 5 && memcmp(s, "PATCH", 5) == 0) return CHTTP_PATCH;
    3176           72 :   if (len == 4 && memcmp(s, "HEAD", 4) == 0) return CHTTP_HEAD;
    3177           59 :   if (len == 7 && memcmp(s, "OPTIONS", 7) == 0) return CHTTP_OPTIONS;
    3178              :   return CHTTP_METHOD_UNKNOWN;
    3179              : }
    3180              : 
    3181              : // Frees the headers and the body of resp and leaves it empty, so a keep-alive
    3182              : // connection can reuse the same response object for its next request and a
    3183              : // teardown leaks nothing.
    3184         3412 : static void destroy_resp(chttpsvr_resp *resp, ccol_memmgmt_procs *mp) {
    3185         3889 :   for (size_t i = 0; i < resp->header_count; i++) {
    3186          477 :     ccol__mem_free(mp, resp->headers[i].name);
    3187          477 :     ccol__mem_free(mp, resp->headers[i].value);
    3188              :   }
    3189         3412 :   ccol__mem_free(mp, resp->headers);
    3190         3412 :   resp->headers = NULL;
    3191         3412 :   resp->header_count = 0;
    3192         3412 :   resp->header_cap = 0;
    3193         3412 :   ccol__mem_free(mp, resp->body);
    3194         3412 :   resp->body = NULL;
    3195         3412 :   resp->body_len = 0;
    3196         3412 :   resp->body_cap = 0;
    3197         3412 : }
    3198              : 
    3199              : // Frees what a request built lazily for its handler (the parsed query
    3200              : // parameters, the query result and the extra context pairs), so nothing a
    3201              : // handler asked for outlives the request.
    3202         1466 : static void destroy_req_scratch(chttpsvr_req *req) {
    3203         1466 :   ccol_memmgmt_procs *mp = req->m_procs;
    3204         1466 :   if (req->qparams) {
    3205              :     chttpsvr_qparams *qp = req->qparams;
    3206          333 :     for (size_t i = 0; i < qp->count; i++) {
    3207          233 :       ccol__mem_free(mp, qp->keys[i]);
    3208          233 :       ccol__mem_free(mp, qp->values[i]);
    3209              :     }
    3210          100 :     ccol__mem_free(mp, qp->keys);
    3211           29 :     ccol__mem_free(mp, qp->values);
    3212          100 :     ccol__mem_free(mp, qp);
    3213              :   }
    3214         1467 :   if (req->qresult) ccol__mem_free(mp, req->qresult);
    3215         1467 :   if (req->ctx_more) {
    3216            4 :     ccol__mem_free(mp, req->ctx_more);
    3217            4 :     req->ctx_more = NULL;
    3218              :   }
    3219         1467 : }
    3220              : 
    3221              : // Returns the reason phrase of a status code, from the IANA registry, for the
    3222              : // status line that send_response writes. Clients ignore the phrase (RFC 9112
    3223              : // SS4), so an unlisted code just gets "Unknown".
    3224         1259 : static const char *status_reason(int status) {
    3225         1259 :   switch (status) {
    3226              :     case 200:
    3227              :       return "OK";
    3228            2 :     case 201:
    3229            2 :       return "Created";
    3230            1 :     case 202:
    3231            1 :       return "Accepted";
    3232            2 :     case 203:
    3233            2 :       return "Non-Authoritative Information";
    3234            4 :     case 204:
    3235            4 :       return "No Content";
    3236            1 :     case 205:
    3237            1 :       return "Reset Content";
    3238            1 :     case 206:
    3239            1 :       return "Partial Content";
    3240            1 :     case 207:
    3241            1 :       return "Multi-Status";
    3242            1 :     case 208:
    3243            1 :       return "Already Reported";
    3244            1 :     case 226:
    3245            1 :       return "IM Used";
    3246            2 :     case 300:
    3247            2 :       return "Multiple Choices";
    3248            1 :     case 301:
    3249            1 :       return "Moved Permanently";
    3250            1 :     case 302:
    3251            1 :       return "Found";
    3252            2 :     case 303:
    3253            2 :       return "See Other";
    3254            2 :     case 304:
    3255            2 :       return "Not Modified";
    3256            1 :     case 305:
    3257            1 :       return "Use Proxy";
    3258            1 :     case 307:
    3259            1 :       return "Temporary Redirect";
    3260            1 :     case 308:
    3261            1 :       return "Permanent Redirect";
    3262           85 :     case 400:
    3263           85 :       return "Bad Request";
    3264            3 :     case 401:
    3265            3 :       return "Unauthorized";
    3266            2 :     case 402:
    3267            2 :       return "Payment Required";
    3268           20 :     case 403:
    3269           20 :       return "Forbidden";
    3270           83 :     case 404:
    3271           83 :       return "Not Found";
    3272           10 :     case 405:
    3273           10 :       return "Method Not Allowed";
    3274            1 :     case 406:
    3275            1 :       return "Not Acceptable";
    3276            1 :     case 407:
    3277            1 :       return "Proxy Authentication Required";
    3278            8 :     case 408:
    3279            8 :       return "Request Timeout";
    3280            1 :     case 409:
    3281            1 :       return "Conflict";
    3282            1 :     case 410:
    3283            1 :       return "Gone";
    3284            1 :     case 411:
    3285            1 :       return "Length Required";
    3286            1 :     case 412:
    3287            1 :       return "Precondition Failed";
    3288            7 :     case 413:
    3289            7 :       return "Payload Too Large";
    3290            1 :     case 414:
    3291            1 :       return "URI Too Long";
    3292            1 :     case 415:
    3293            1 :       return "Unsupported Media Type";
    3294            1 :     case 416:
    3295            1 :       return "Range Not Satisfiable";
    3296            1 :     case 417:
    3297            1 :       return "Expectation Failed";
    3298            1 :     case 421:
    3299            1 :       return "Misdirected Request";
    3300            1 :     case 422:
    3301            1 :       return "Unprocessable Entity";
    3302            1 :     case 423:
    3303            1 :       return "Locked";
    3304            1 :     case 424:
    3305            1 :       return "Failed Dependency";
    3306            1 :     case 425:
    3307            1 :       return "Too Early";
    3308            2 :     case 426:
    3309            2 :       return "Upgrade Required";
    3310            1 :     case 428:
    3311            1 :       return "Precondition Required";
    3312            1 :     case 429:
    3313            1 :       return "Too Many Requests";
    3314            1 :     case 431:
    3315            1 :       return "Request Header Fields Too Large";
    3316            2 :     case 451:
    3317            2 :       return "Unavailable For Legal Reasons";
    3318           80 :     case 500:
    3319           80 :       return "Internal Server Error";
    3320            7 :     case 501:
    3321            7 :       return "Not Implemented";
    3322            1 :     case 502:
    3323            1 :       return "Bad Gateway";
    3324           12 :     case 503:
    3325           12 :       return "Service Unavailable";
    3326            1 :     case 504:
    3327            1 :       return "Gateway Timeout";
    3328            3 :     case 505:
    3329            3 :       return "HTTP Version Not Supported";
    3330            1 :     case 506:
    3331            1 :       return "Variant Also Negotiates";
    3332            1 :     case 507:
    3333            1 :       return "Insufficient Storage";
    3334            1 :     case 508:
    3335            1 :       return "Loop Detected";
    3336            1 :     case 510:
    3337            1 :       return "Not Extended";
    3338            2 :     case 511:
    3339            2 :       return "Network Authentication Required";
    3340            3 :     default:
    3341            3 :       return "Unknown";
    3342              :   }
    3343              : }
    3344              : 
    3345              : // Converts a chttpsvr_config duration from microseconds to the milliseconds the
    3346              : // server keeps; chttpsvr_start uses it for every duration field. It rounds up,
    3347              : // so a non-zero value never becomes the 0 that several fields read as "off" or
    3348              : // "default", and it saturates at UINT_MAX - 1. UINT_MAX stays free because it's
    3349              : // the internal form of CHTTPSVR_NO_DEADLINE.
    3350         1933 : static unsigned cfg_us_to_ms(uint64_t us) {
    3351          960 :   uint64_t ms = ccol_us_to_ms_ceil(us);
    3352          329 :   return ms >= (uint64_t)UINT_MAX ? UINT_MAX - 1u : (unsigned)ms;
    3353              : }
    3354              : 
    3355              : // Converts like cfg_us_to_ms, for the fields that accept CHTTPSVR_NO_DEADLINE,
    3356              : // which has to map to the internal UINT_MAX instead of being clamped.
    3357          642 : static unsigned cfg_deadline_us_to_ms(uint64_t us) {
    3358          642 :   return us == CHTTPSVR_NO_DEADLINE ? UINT_MAX : cfg_us_to_ms(us);
    3359              : }
    3360              : 
    3361              : // Turns a configured timeout into the poll(2)-style timeout that
    3362              : // chttp1_stream_read and chttp1_stream_write take. It's needed because the
    3363              : // config reads 0 as "wait forever", while those calls read 0 as "don't wait at
    3364              : // all" and fail before even one try, so 0 becomes -1. A value above INT_MAX is
    3365              : // clamped to INT_MAX, because the int cast would wrap it negative and turn a
    3366              : // long finite wait into "forever". Every configured timeout must pass through
    3367              : // here before it reaches those two calls.
    3368         1439 : static int to_stream_timeout_ms(unsigned configured_timeout_ms) {
    3369         1439 :   if (configured_timeout_ms == 0) return -1;
    3370         1432 :   if (configured_timeout_ms > (unsigned)INT_MAX) return INT_MAX;
    3371              :   return (int)configured_timeout_ms;
    3372              : }
    3373              : 
    3374              : // A growable buffer for one response's header block. It starts on the stack,
    3375              : // moves to the heap when the headers don't fit and then doubles. A fixed buffer
    3376              : // would drop a valid response with many or long headers (Set-Cookie, CSP) and
    3377              : // close the connection with nothing on the wire and nothing in the log. heap
    3378              : // says whether buf has to be freed.
    3379              : typedef struct {
    3380              :   char *buf;
    3381              :   size_t cap;
    3382              :   size_t len;
    3383              :   bool heap;
    3384              :   ccol_memmgmt_procs *mp;
    3385              : } head_builder;
    3386              : 
    3387              : #ifdef RUNNING_UNIT_TESTS
    3388              : // Test counter of failed allocations in head_builder_grow, across every server
    3389              : // of the process. It goes up before send_response returns, so before the
    3390              : // connection closes, and a test reads the difference over one request.
    3391              : static _Atomic size_t g_head_alloc_failure_count_for_tests = 0;
    3392              : // Test hook: Gives the number of response heads that couldn't grow so far.
    3393          146 : size_t chttpsvr__head_alloc_failure_count_for_tests(void) {
    3394          146 :   return atomic_load(&g_head_alloc_failure_count_for_tests);
    3395              : }
    3396              : #endif
    3397              : 
    3398              : // Grows b so it has room for needed_extra more bytes, moving it to the heap;
    3399              : // the two append functions call it when a header doesn't fit. Returns false on
    3400              : // overflow or a failed allocation, and b is left as it was then.
    3401           26 : static bool head_builder_grow(head_builder *b, size_t needed_extra) {
    3402           26 :   size_t min_cap = b->len + needed_extra;
    3403           26 :   if (min_cap < b->len) return false;
    3404           26 :   size_t new_cap = b->cap ? b->cap : 1;
    3405           52 :   while (new_cap < min_cap) {
    3406           26 :     if (new_cap > SIZE_MAX / 2) {
    3407              :       new_cap = min_cap;
    3408              :       break;
    3409              :     }
    3410           26 :     new_cap *= 2;
    3411              :   }
    3412           26 :   char *nb = (char *)ccol__mem_alloc(b->mp, new_cap);
    3413           26 :   if (!nb) {
    3414              : #ifdef RUNNING_UNIT_TESTS
    3415            1 :     atomic_fetch_add(&g_head_alloc_failure_count_for_tests, 1);
    3416              : #endif
    3417            1 :     return false;
    3418              :   }
    3419           25 :   memcpy(nb, b->buf, b->len);
    3420           25 :   if (b->heap) ccol__mem_free(b->mp, b->buf);
    3421           25 :   b->buf = nb;
    3422           25 :   b->cap = new_cap;
    3423           25 :   b->heap = true;
    3424           25 :   return true;
    3425              : }
    3426              : 
    3427              : // Appends fmt and its arguments to b, growing it as often as needed.
    3428              : // send_response builds the status line and the header fields with it. It
    3429              : // returns false only on a failed allocation or a vsnprintf encoding error. The
    3430              : // format attribute moves the format string check to every call site, where fmt
    3431              : // is a literal, and keeps Clang's -Wformat-nonliteral quiet on the inner
    3432              : // vsnprintf.
    3433         5495 : static bool __attribute__((format(printf, 2, 3))) head_builder_append(
    3434              :     head_builder *b, const char *fmt, ...) {
    3435           25 :   for (;;) {
    3436         5520 :     size_t avail = b->cap - b->len;
    3437         5520 :     va_list ap;
    3438         5520 :     va_start(ap, fmt);
    3439         5520 :     int n = vsnprintf(b->buf + b->len, avail, fmt, ap);
    3440         5520 :     va_end(ap);
    3441         5520 :     if (n < 0) return false;
    3442         5520 :     if ((size_t)n < avail) {
    3443         5494 :       b->len += (size_t)n;
    3444         5494 :       return true;
    3445              :     }
    3446           26 :     if (!head_builder_grow(b, (size_t)n + 1)) return false;
    3447              :   }
    3448              : }
    3449              : 
    3450              : // Appends n bytes of s to b without any formatting, for the prebuilt Date line
    3451              : // where vsnprintf would be wasted work. Returns false when b can't grow.
    3452         1256 : static bool head_builder_append_bytes(head_builder *b, const char *s,
    3453              :                                       size_t n) {
    3454         1256 :   if (n > b->cap - b->len && !head_builder_grow(b, n)) return false;
    3455         1256 :   memcpy(b->buf + b->len, s, n);
    3456         1256 :   b->len += n;
    3457         1256 :   return true;
    3458              : }
    3459              : 
    3460              : // Length of an RFC 9110 SS5.6.7 IMF-fixdate such as "Sun, 06 Nov 1994 08:49:37
    3461              : // GMT". The Date cache and the Date line of send_response are sized from it.
    3462              : #define CHTTPSVR_IMF_FIXDATE_LEN 29
    3463              : 
    3464              : // The last Date value a thread formatted and the second it stands for. The Date
    3465              : // header changes once a second but goes on every response, so each thread
    3466              : // formats it once a second and reuses it. The cache belongs to one thread and
    3467              : // needs no lock and no atomic.
    3468              : typedef struct {
    3469              :   int64_t sec;
    3470              :   char text[CHTTPSVR_IMF_FIXDATE_LEN + 1];
    3471              : } chttpsvr_date_cache_state;
    3472              : 
    3473              : // Each thread's Date cache. It takes the same TLS model as the library's other
    3474              : // thread-local fast paths: initial-exec, unless CMEMPOOL_DYNAMIC_TLS asks for
    3475              : // the general model (see cmempool.c).
    3476              : #if defined(CMEMPOOL_DYNAMIC_TLS) && CMEMPOOL_DYNAMIC_TLS
    3477              : static __thread chttpsvr_date_cache_state chttpsvr_date_cache = {.sec =
    3478              :                                                                      INT64_MIN};
    3479              : #else
    3480              : static __thread chttpsvr_date_cache_state chttpsvr_date_cache
    3481              :     __attribute__((tls_model("initial-exec"))) = {.sec = INT64_MIN};
    3482              : #endif
    3483              : 
    3484              : #ifdef RUNNING_UNIT_TESTS
    3485              : // Test hook: Any value other than INT64_MIN replaces the clock in
    3486              : // chttpsvr_date_now, so a test can cross a second boundary without sleeping.
    3487              : static _Atomic int64_t g_date_override_for_tests = INT64_MIN;
    3488           11 : void chttpsvr__set_date_override_for_tests(int64_t sec) {
    3489           11 :   atomic_store(&g_date_override_for_tests, sec);
    3490           11 : }
    3491              : #endif
    3492              : 
    3493              : // Writes v (0 to 99) as two decimal digits at out, for the fixed-width fields
    3494              : // of format_imf_fixdate.
    3495          425 : static void put2(char *out, int v) {
    3496          425 :   out[0] = (char)('0' + v / 10);
    3497          425 :   out[1] = (char)('0' + v % 10);
    3498              : }
    3499              : 
    3500              : // Formats sec, seconds since the epoch, as a UTC IMF-fixdate into out
    3501              : // (CHTTPSVR_IMF_FIXDATE_LEN bytes plus a NUL), for the Date header. Day and
    3502              : // month names come from fixed tables, so the process locale that strftime()
    3503              : // would read can't change the header, and gmtime_r() touches no shared state. A
    3504              : // second that time_t can't hold, or one without a four-digit year, gives the
    3505              : // epoch. It runs once a second per thread, so it stays out of line.
    3506          425 : static __attribute__((noinline, cold)) void format_imf_fixdate(int64_t sec,
    3507              :                                                                char *out) {
    3508          425 :   static const char days[7][3] = {
    3509              :       {'S', 'u', 'n'}, {'M', 'o', 'n'}, {'T', 'u', 'e'}, {'W', 'e', 'd'},
    3510              :       {'T', 'h', 'u'}, {'F', 'r', 'i'}, {'S', 'a', 't'}};
    3511          425 :   static const char months[12][3] = {
    3512              :       {'J', 'a', 'n'}, {'F', 'e', 'b'}, {'M', 'a', 'r'}, {'A', 'p', 'r'},
    3513              :       {'M', 'a', 'y'}, {'J', 'u', 'n'}, {'J', 'u', 'l'}, {'A', 'u', 'g'},
    3514              :       {'S', 'e', 'p'}, {'O', 'c', 't'}, {'N', 'o', 'v'}, {'D', 'e', 'c'}};
    3515          425 :   struct tm tm;
    3516          425 :   time_t t = (time_t)sec;
    3517          425 :   if ((int64_t)t != sec || !gmtime_r(&t, &tm) || tm.tm_year + 1900 < 0 ||
    3518              :       tm.tm_year + 1900 > 9999) {
    3519            0 :     memcpy(out, "Thu, 01 Jan 1970 00:00:00 GMT", CHTTPSVR_IMF_FIXDATE_LEN);
    3520            0 :     out[CHTTPSVR_IMF_FIXDATE_LEN] = '\0';
    3521            0 :     return;
    3522              :   }
    3523          425 :   int year = tm.tm_year + 1900;
    3524          425 :   memcpy(out, days[tm.tm_wday], 3);
    3525          425 :   out[3] = ',';
    3526          425 :   out[4] = ' ';
    3527          425 :   put2(out + 5, tm.tm_mday);
    3528          425 :   out[7] = ' ';
    3529          425 :   memcpy(out + 8, months[tm.tm_mon], 3);
    3530          425 :   out[11] = ' ';
    3531          425 :   put2(out + 12, year / 100);
    3532          425 :   put2(out + 14, year % 100);
    3533          425 :   out[16] = ' ';
    3534          425 :   put2(out + 17, tm.tm_hour);
    3535          425 :   out[19] = ':';
    3536          425 :   put2(out + 20, tm.tm_min);
    3537          425 :   out[22] = ':';
    3538          425 :   put2(out + 23, tm.tm_sec);
    3539          425 :   memcpy(out + 25, " GMT", 4);
    3540          425 :   out[CHTTPSVR_IMF_FIXDATE_LEN] = '\0';
    3541              : }
    3542              : 
    3543              : // Returns the Date value for the current second, which send_response puts on
    3544              : // every response that doesn't carry its own. It reads this thread's
    3545              : // chttpsvr_date_cache and formats it again only when the second has changed
    3546              : // (g_date_override_for_tests replaces the clock in tests). The coarse real-time
    3547              : // clock is read from the vDSO with no system call, and its resolution is far
    3548              : // finer than a second.
    3549         1256 : static const char *chttpsvr_date_now(void) {
    3550         1256 :   struct timespec ts;
    3551              : #ifdef CLOCK_REALTIME_COARSE
    3552         1256 :   clock_gettime(CLOCK_REALTIME_COARSE, &ts);
    3553              : #else
    3554              :   clock_gettime(CLOCK_REALTIME, &ts);
    3555              : #endif
    3556         1256 :   int64_t sec = (int64_t)ts.tv_sec;
    3557              : #ifdef RUNNING_UNIT_TESTS
    3558         1256 :   int64_t ov = atomic_load(&g_date_override_for_tests);
    3559         1256 :   if (ov != INT64_MIN) sec = ov;
    3560              : #endif
    3561         1256 :   chttpsvr_date_cache_state *c = &chttpsvr_date_cache;
    3562         1256 :   if (__builtin_expect(c->sec != sec, 0)) {
    3563          424 :     format_imf_fixdate(sec, c->text);
    3564          425 :     c->sec = sec;
    3565              :   }
    3566         1257 :   return c->text;
    3567              : }
    3568              : 
    3569              : // Frees b's buffer when it lives on the heap; every exit of send_response calls
    3570              : // it so a grown header block never leaks.
    3571         1259 : static void head_builder_release(head_builder *b) {
    3572         1259 :   if (b->heap) ccol__mem_free(b->mp, b->buf);
    3573         1259 : }
    3574              : 
    3575              : // Counts down against a total-duration cap, at the given instant. It exists so
    3576              : // a read or a write that waits many times is bounded in total, and not only per
    3577              : // call. On the first call it sets *deadline max_dur ms after that instant and
    3578              : // latches *deadline_set. Every call then lowers *timeout_ms_inout to the time
    3579              : // left when that is shorter (a 0 there means no per-call bound yet, so the time
    3580              : // left wins). Returns false once not a single nanosecond is left. The time left
    3581              : // rounds up to whole milliseconds and is computed in long long, so a wait never
    3582              : // ends early and a cap of UINT_MAX ms can't overflow a 32-bit long.
    3583         4137 : static inline __attribute__((always_inline)) bool shrink_timeout_at(
    3584              :     struct timespec *deadline, bool *deadline_set, unsigned max_dur,
    3585              :     struct timespec now, unsigned *timeout_ms_inout) {
    3586         4137 :   if (!*deadline_set) {
    3587         1451 :     *deadline = now;
    3588         1451 :     deadline->tv_sec += (time_t)(max_dur / 1000);
    3589         1451 :     deadline->tv_nsec += (long)(max_dur % 1000) * 1000000L;
    3590         1451 :     if (deadline->tv_nsec >= 1000000000L) {
    3591            2 :       deadline->tv_nsec -= 1000000000L;
    3592            2 :       deadline->tv_sec += 1;
    3593              :     }
    3594         1451 :     *deadline_set = true;
    3595              :   }
    3596         4137 :   long long remaining_ns = ns_between(*deadline, now);
    3597         4132 :   if (remaining_ns <= 0) return false;
    3598         4136 :   long long remaining_ms = ms_ceil_of_ns(remaining_ns);
    3599         4136 :   unsigned remaining_ms_clamped =
    3600         4136 :       (remaining_ms > (long long)UINT_MAX) ? UINT_MAX : (unsigned)remaining_ms;
    3601         4136 :   if (!*timeout_ms_inout || remaining_ms_clamped < *timeout_ms_inout)
    3602          551 :     *timeout_ms_inout = remaining_ms_clamped;
    3603              :   return true;
    3604              : }
    3605              : 
    3606              : // Runs shrink_timeout_at at the current monotonic time. check_read_deadline and
    3607              : // send_response both use it, so both total-duration caps work the same way.
    3608              : // With max_dur 0 the cap is off and it returns true without touching anything,
    3609              : // so a disabled cap costs one branch.
    3610              : static inline __attribute__((always_inline)) bool
    3611         4183 : shrink_timeout_to_deadline_inl(struct timespec *deadline, bool *deadline_set,
    3612              :                                unsigned max_dur, unsigned *timeout_ms_inout) {
    3613         4183 :   if (!max_dur) return true;
    3614         4132 :   struct timespec now;
    3615         4132 :   clock_gettime(CLOCK_MONOTONIC, &now);
    3616         4132 :   return shrink_timeout_at(deadline, deadline_set, max_dur, now,
    3617              :                            timeout_ms_inout);
    3618              : }
    3619              : 
    3620              : #ifdef RUNNING_UNIT_TESTS
    3621              : // Test hook: Returns what shrink_timeout_at decides, and the timeout it shrinks
    3622              : // to, for a deadline that is already set, so a test can check the rounding
    3623              : // without a clock.
    3624            5 : bool chttpsvr__shrink_timeout_at_for_tests(struct timespec deadline,
    3625              :                                            struct timespec now,
    3626              :                                            unsigned *timeout_ms_inout) {
    3627            5 :   bool set = true;
    3628            5 :   return shrink_timeout_at(&deadline, &set, 1, now, timeout_ms_inout);
    3629              : }
    3630              : #endif
    3631              : 
    3632              : // Out-of-line shrink_timeout_to_deadline_inl, for callers off the request
    3633              : // body's path that don't need it inlined.
    3634         1712 : static bool shrink_timeout_to_deadline(struct timespec *deadline,
    3635              :                                        bool *deadline_set, unsigned max_dur,
    3636              :                                        unsigned *timeout_ms_inout) {
    3637         1712 :   return shrink_timeout_to_deadline_inl(deadline, deadline_set, max_dur,
    3638              :                                         timeout_ms_inout);
    3639              : }
    3640              : 
    3641              : #ifdef RUNNING_UNIT_TESTS
    3642              : // Test hook: The next response_write_deadline_ok reports an expired deadline
    3643              : // whatever the clock says, then disarms itself. A rejection's small header
    3644              : // block always goes out in one write, so a test can't get a real expired
    3645              : // deadline for it any other way.
    3646              : static _Atomic bool g_force_next_response_write_deadline_expired_for_tests =
    3647              :     false;
    3648            2 : void chttpsvr__force_next_response_write_deadline_expired_for_tests(void) {
    3649            2 :   atomic_store(&g_force_next_response_write_deadline_expired_for_tests, true);
    3650            2 : }
    3651              : #endif
    3652              : 
    3653              : // Applies the write deadline of conn to one write attempt and shrinks
    3654              : // *call_timeout_ms to the time left. send_response, send_response_continue and
    3655              : // write_interim_continue all call it before each write, so a slow reader can't
    3656              : // keep a write going past its total cap. With apply_internal_ceiling false (a
    3657              : // handler's response) the cap is the server's max_response_write_duration_ms,
    3658              : // where 0 means no limit. With it true (a rejection or the interim 100 Continue
    3659              : // line) the cap is the tighter of that value and
    3660              : // CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS, so these small writes of our own are
    3661              : // bounded even when the operator turned the cap off.
    3662              : // Returns false once the deadline has passed. It reads
    3663              : // srv->max_response_write_duration_ms on every call and sets
    3664              : // conn->write_deadline and write_deadline_set on the first one. conn is never
    3665              : // NULL.
    3666         1610 : static bool response_write_deadline_ok(chttpsvr_conn *conn,
    3667              :                                        bool apply_internal_ceiling,
    3668              :                                        unsigned *call_timeout_ms) {
    3669              : #ifdef RUNNING_UNIT_TESTS
    3670         1610 :   if (atomic_exchange(&g_force_next_response_write_deadline_expired_for_tests,
    3671              :                       false))
    3672              :     return false;
    3673              : #endif
    3674         1608 :   unsigned configured = atomic_load(&conn->srv->max_response_write_duration_ms);
    3675         1608 :   unsigned effective_max_dur = configured;
    3676         1608 :   if (apply_internal_ceiling &&
    3677          310 :       (configured == 0 || configured > internal_write_ceiling_ms()))
    3678          312 :     effective_max_dur = internal_write_ceiling_ms();
    3679         1608 :   return shrink_timeout_to_deadline(&conn->write_deadline,
    3680              :                                     &conn->write_deadline_set,
    3681              :                                     effective_max_dur, call_timeout_ms);
    3682              : }
    3683              : 
    3684              : #ifdef RUNNING_UNIT_TESTS
    3685              : // Test hook: The next handler response write sends only its first n bytes and
    3686              : // then acts as if the socket were full, so a test can end a partial write
    3687              : // inside the head or the body and watch the parked rest resume. Disarms itself
    3688              : // after one use.
    3689              : static _Atomic size_t g_force_short_response_write_for_tests = 0;
    3690           15 : void chttpsvr__force_short_response_write_for_tests(size_t n) {
    3691           15 :   atomic_store(&g_force_short_response_write_for_tests, n);
    3692           15 : }
    3693              : #endif
    3694              : 
    3695              : // Serializes resp into an HTTP/1.1 response and writes the head and the body
    3696              : // together, as one writev(2) or one TLS record when they fit. task_worker sends
    3697              : // every handler response with it and conn_reject_and_close every rejection. It
    3698              : // tries the write first and waits only once the socket is full, so an ordinary
    3699              : // response costs one system call.
    3700              : // keep_alive is the only source of the Connection header, and resp->body_len
    3701              : // the only source of Content-Length where a body goes out, so the handler's
    3702              : // values for those two never reach the wire. Otherwise the response could
    3703              : // announce keep-alive while the caller closes, or a length other than what we
    3704              : // send, and a kept-alive connection would lose its framing. A 1xx or
    3705              : // out-of-range status goes out as 500. 204, 205, 304 and a HEAD request
    3706              : // (suppress_body) carry no body. A 204 has no Content-Length, a 205 always says
    3707              : // 0, and a 304 or a bodyless HEAD response carries the handler's Content-Length
    3708              : // if it set one (RFC 9110 SS8.6). A HEAD answer to a rejection (is_reject)
    3709              : // reports the length of the body its GET form would get. A Date header is added
    3710              : // unless the handler set one.
    3711              : // Returns false on an error, a timeout or a park, and the caller must then stop
    3712              : // using the connection. Every write is bounded by timeout_ms and by
    3713              : // response_write_deadline_ok on conn (is_reject switches on the internal
    3714              : // ceiling). A stream with write_nonblocking set parks the unsent rest on conn
    3715              : // instead of waiting (see send_response_park); the stack copy of the head is
    3716              : // copied there.
    3717         1259 : static bool send_response(chttp1_stream *stream, chttpsvr_resp *resp,
    3718              :                           bool keep_alive, unsigned timeout_ms,
    3719              :                           bool suppress_body, chttpsvr_conn *conn,
    3720              :                           bool is_reject) {
    3721         1259 :   char stack_buf[4096];
    3722         1259 :   head_builder hb = {.buf = stack_buf,
    3723              :                      .cap = sizeof(stack_buf),
    3724              :                      .len = 0,
    3725              :                      .heap = false,
    3726         1259 :                      .mp = resp->m_procs};
    3727              : 
    3728         2518 :   int status = (resp->status_code >= 200 && resp->status_code <= 999)
    3729              :                    ? resp->status_code
    3730         1259 :                    : 500;
    3731         2518 :   bool no_body =
    3732         1259 :       suppress_body || status == 204 || status == 304 || status == 205;
    3733         1259 :   bool handler_date = false;
    3734         1259 :   const char *handler_length = NULL;
    3735              : 
    3736         1259 :   if (!head_builder_append(&hb, "HTTP/1.1 %d %s\r\n", status,
    3737              :                            status_reason(status))) {
    3738            0 :     head_builder_release(&hb);
    3739            0 :     return false;
    3740              :   }
    3741              : 
    3742         1732 :   for (size_t i = 0; i < resp->header_count; i++) {
    3743          946 :     if (ccol_ascii_casecmp(resp->headers[i].name, "connection") == 0) continue;
    3744          469 :     if (ccol_ascii_casecmp(resp->headers[i].name, "content-length") == 0) {
    3745            4 :       handler_length = resp->headers[i].value;
    3746            4 :       continue;
    3747              :     }
    3748          465 :     if (ccol_ascii_casecmp(resp->headers[i].name, "date") == 0)
    3749            3 :       handler_date = true;
    3750          465 :     if (!head_builder_append(&hb, "%s:%s\r\n", resp->headers[i].name,
    3751              :                              resp->headers[i].value)) {
    3752            1 :       head_builder_release(&hb);
    3753            1 :       return false;
    3754              :     }
    3755              :   }
    3756              : 
    3757         1259 :   if (!handler_date) {
    3758         1256 :     char date_line[5 + CHTTPSVR_IMF_FIXDATE_LEN + 2];
    3759         1256 :     memcpy(date_line, "date:", 5);
    3760         1256 :     memcpy(date_line + 5, chttpsvr_date_now(), CHTTPSVR_IMF_FIXDATE_LEN);
    3761         1256 :     date_line[5 + CHTTPSVR_IMF_FIXDATE_LEN] = '\r';
    3762         1256 :     date_line[6 + CHTTPSVR_IMF_FIXDATE_LEN] = '\n';
    3763         1256 :     if (!head_builder_append_bytes(&hb, date_line, sizeof(date_line))) {
    3764            0 :       head_builder_release(&hb);
    3765            0 :       return false;
    3766              :     }
    3767              :   }
    3768              : 
    3769         1259 :   if (status != 204) {
    3770         1255 :     bool ok_len = true;
    3771         1255 :     bool handler_head = suppress_body && resp->body_len == 0 && !is_reject;
    3772         1255 :     if (__builtin_expect(status == 205, 0))
    3773            1 :       ok_len = head_builder_append(&hb, "content-length:0\r\n");
    3774         1254 :     else if (__builtin_expect(status != 304 && !handler_head, 1))
    3775         1250 :       ok_len =
    3776         1250 :           head_builder_append(&hb, "content-length:%zu\r\n", resp->body_len);
    3777            4 :     else if (handler_length)
    3778            2 :       ok_len =
    3779            2 :           head_builder_append(&hb, "content-length:%s\r\n", handler_length);
    3780         1253 :     if (!ok_len) {
    3781            0 :       head_builder_release(&hb);
    3782            0 :       return false;
    3783              :     }
    3784              :   }
    3785              :   {
    3786         1259 :     const char *cval = keep_alive ? "keep-alive" : "close";
    3787         1259 :     if (!head_builder_append(&hb, "connection:%s\r\n", cval)) {
    3788            0 :       head_builder_release(&hb);
    3789            0 :       return false;
    3790              :     }
    3791              :   }
    3792         1259 :   if (!head_builder_append(&hb, "\r\n")) {
    3793            0 :     head_builder_release(&hb);
    3794            0 :     return false;
    3795              :   }
    3796              : 
    3797         1259 :   size_t blen = no_body ? 0 : resp->body_len;
    3798         1259 :   size_t total = hb.len + blen;
    3799         1259 :   size_t sent = 0;
    3800         1259 :   bool ok = true;
    3801         2501 :   while (sent < total) {
    3802         1277 :     unsigned call_timeout_ms = timeout_ms;
    3803         2554 :     if (conn &&
    3804         1277 :         !response_write_deadline_ok(conn, is_reject, &call_timeout_ms)) {
    3805              :       ok = false;
    3806           34 :       break;
    3807              :     }
    3808         1276 :     size_t alen = sent < hb.len ? hb.len - sent : 0;
    3809         1276 :     size_t boff = sent > hb.len ? sent - hb.len : 0;
    3810              : #ifdef RUNNING_UNIT_TESTS
    3811         1276 :     size_t forced =
    3812         1276 :         atomic_exchange(&g_force_short_response_write_for_tests, (size_t)0);
    3813         1276 :     if (forced && stream->write_nonblocking && conn) {
    3814           10 :       size_t fa = alen < forced ? alen : forced;
    3815           10 :       size_t brest = blen - boff;
    3816           10 :       size_t fb = brest < forced - fa ? brest : forced - fa;
    3817           12 :       ssize_t fn = chttp1_stream_writev2(stream, hb.buf + (hb.len - alen), fa,
    3818            2 :                                          fb ? resp->body + boff : NULL, fb, 0);
    3819           10 :       if (fn > 0) sent += (size_t)fn;
    3820           10 :       alen = sent < hb.len ? hb.len - sent : 0;
    3821           10 :       boff = sent > hb.len ? sent - hb.len : 0;
    3822           10 :       send_response_park(conn, stream, hb.buf + (hb.len - alen), alen, boff,
    3823              :                          keep_alive, no_body, is_reject);
    3824           10 :       ok = false;
    3825           10 :       break;
    3826              :     }
    3827              : #endif
    3828         2532 :     ssize_t n = chttp1_stream_writev2(
    3829         1266 :         stream, hb.buf + (hb.len - alen), alen, blen ? resp->body + boff : NULL,
    3830              :         blen - boff, to_stream_timeout_ms(call_timeout_ms));
    3831         1265 :     if (n <= 0) {
    3832           46 :       if (n < 0 && stream->write_nonblocking && conn &&
    3833           23 :           chttp1_stream_timed_out(stream))
    3834           18 :         send_response_park(conn, stream, hb.buf + (hb.len - alen), alen, boff,
    3835              :                            keep_alive, no_body, is_reject);
    3836              :       ok = false;
    3837              :       break;
    3838              :     }
    3839         1242 :     sent += (size_t)n;
    3840              :   }
    3841         1258 :   head_builder_release(&hb);
    3842         1258 :   return ok;
    3843              : }
    3844              : 
    3845              : #ifdef RUNNING_UNIT_TESTS
    3846              : // Test hook: With 0 < n < 25, the next write_interim_continue writes exactly n
    3847              : // bytes of the line for real and then fails as if its deadline expired. Socket
    3848              : // buffering gives no reliable way to get a real short write of 25 bytes.
    3849              : // Disarms itself after one use.
    3850              : static _Atomic size_t g_force_short_interim_write_bytes_for_tests = 0;
    3851            2 : void chttpsvr__force_short_interim_write_for_tests(size_t n) {
    3852            2 :   atomic_store(&g_force_short_interim_write_bytes_for_tests, n);
    3853            2 : }
    3854              : #endif
    3855              : #ifdef RUNNING_UNIT_TESTS
    3856              : // Test hook: The next interim line written without waiting sends its first n
    3857              : // bytes (n may be 0) and then acts as if the socket were full, so a test can
    3858              : // watch the rest wait in a parked connection. SIZE_MAX means not armed.
    3859              : static _Atomic size_t g_force_interim_park_after_for_tests = SIZE_MAX;
    3860            2 : void chttpsvr__force_interim_park_after_for_tests(size_t n) {
    3861            2 :   atomic_store(&g_force_interim_park_after_for_tests, n);
    3862            2 : }
    3863              : #endif
    3864              : 
    3865              : // The interim 100 Continue response (RFC 7231 SS5.1.1) and its length, which
    3866              : // write_interim_continue sends and counts against.
    3867              : static const char interim_continue_line[] = "HTTP/1.1 100 Continue\r\n\r\n";
    3868              : #define INTERIM_CONTINUE_LEN (sizeof(interim_continue_line) - 1)
    3869              : 
    3870              : // Writes the interim 100 Continue line for an Expect: 100-continue request,
    3871              : // from task_worker for a buffered route and from chttpsvr_req_read for a
    3872              : // streaming one; the client sends the body only after it sees this line. It
    3873              : // loops on short writes like send_response, and every attempt goes through
    3874              : // response_write_deadline_ok with the internal ceiling, so a peer that reads
    3875              : // slowly can't hold a worker thread for ever.
    3876              : // Returns 1 when the whole line is out. Returns -1 when a stream with
    3877              : // write_nonblocking hit a full socket and the rest was parked on conn; the
    3878              : // caller lets go of the connection and task_resume finishes it. Returns 0 on a
    3879              : // failure or an expired deadline, also when copying the rest fails. A 0 can
    3880              : // mean a truncated line is on the wire, so the caller must write nothing more
    3881              : // and close.
    3882              : // It sets conn->wp_interim when it parks, and clears conn->write_deadline_set
    3883              : // on every exit. The deadline belongs to the response, and a leftover one would
    3884              : // charge send_response for the whole body read in between.
    3885           19 : static int write_interim_continue(chttpsvr_conn *conn, chttp1_stream *stream,
    3886              :                                   unsigned wtimeout_ms) {
    3887           19 :   const char *cont = interim_continue_line;
    3888           19 :   const size_t clen = INTERIM_CONTINUE_LEN;
    3889           19 :   size_t sent = 0;
    3890              : #ifdef RUNNING_UNIT_TESTS
    3891           19 :   size_t forced_short =
    3892           19 :       atomic_exchange(&g_force_short_interim_write_bytes_for_tests, 0);
    3893           19 :   if (forced_short > 0 && forced_short < clen) {
    3894            4 :     ssize_t n = chttp1_stream_write(stream, cont, forced_short,
    3895              :                                     to_stream_timeout_ms(wtimeout_ms));
    3896            2 :     if (n > 0) sent = (size_t)n;
    3897            2 :     conn->write_deadline_set = false;
    3898            2 :     return sent == clen;
    3899              :   }
    3900           17 :   size_t forced_park = SIZE_MAX;
    3901           17 :   if (stream->write_nonblocking)
    3902           15 :     forced_park =
    3903           15 :         atomic_exchange(&g_force_interim_park_after_for_tests, SIZE_MAX);
    3904              : #endif
    3905           32 :   while (sent < clen) {
    3906           17 :     unsigned call_timeout_ms = wtimeout_ms;
    3907           17 :     if (!response_write_deadline_ok(conn, true, &call_timeout_ms)) break;
    3908           16 :     size_t want = clen - sent;
    3909           16 :     bool would_block = false;
    3910              : #ifdef RUNNING_UNIT_TESTS
    3911           16 :     if (forced_park != SIZE_MAX) {
    3912            1 :       want = forced_park < clen ? forced_park : clen;
    3913            1 :       forced_park = SIZE_MAX;
    3914            1 :       would_block = true;
    3915              :     }
    3916              : #endif
    3917           16 :     ssize_t n = 0;
    3918           16 :     if (want)
    3919           32 :       n = chttp1_stream_write(stream, cont + sent, want,
    3920              :                               to_stream_timeout_ms(call_timeout_ms));
    3921           16 :     if (n > 0) sent += (size_t)n;
    3922           16 :     if (!would_block && n > 0) continue;
    3923            1 :     if (!would_block && n < 0 && stream->write_nonblocking &&
    3924            0 :         chttp1_stream_timed_out(stream))
    3925              :       would_block = true;
    3926            1 :     if (would_block) {
    3927            1 :       if (sent == clen) break;
    3928            1 :       send_response_park(conn, stream, cont + sent, clen - sent, 0, true, true,
    3929              :                          true);
    3930            1 :       if (conn->wp_active && conn->wp_keep_alive) {
    3931            1 :         conn->wp_interim = true;
    3932            1 :         return -1;
    3933              :       }
    3934            0 :       conn->wp_active = false;
    3935            0 :       ccol__mem_free(conn->m_procs, conn->wp_head);
    3936            0 :       conn->wp_head = NULL;
    3937              :     }
    3938              :     break;
    3939              :   }
    3940           16 :   conn->write_deadline_set = false;
    3941           16 :   return sent == clen;
    3942              : }
    3943              : 
    3944              : // Runs the next middleware of the request's chain, or the route handler once
    3945              : // the chain is used up. It's the next function every middleware receives, so a
    3946              : // middleware passes the request on by calling it. It reads and advances
    3947              : // req->conn->dispatch. A NULL route marks a rejected request (see
    3948              : // conn_reject_and_close), and reaching the end of its chain means sending the
    3949              : // rejection that resp already holds.
    3950         1339 : static void chttpsvr_next(chttpsvr_req *req, chttpsvr_resp *resp) {
    3951         1339 :   dispatch_ctx *ctx = &req->conn->dispatch;
    3952         1339 :   if (ctx->mw_idx < ctx->mw_count) {
    3953          342 :     mw_entry entry = ctx->mw_snap[ctx->mw_idx++];
    3954          342 :     entry.fn(req, resp, entry.ctx, chttpsvr_next);
    3955          342 :     return;
    3956              :   }
    3957          997 :   if (ctx->route) ctx->route->fn(req, resp, ctx->route->ctx);
    3958              : }
    3959              : 
    3960              : // Tells conn_reject_and_close whether a rejection with this status runs the
    3961              : // middleware chain first. 404, 405 and 413 are ordinary client traffic that a
    3962              : // rate limiter or an access log wants to see. A 500 comes from an allocation
    3963              : // failure, a 503 from a full worker pool, and a 501 is decided before there is
    3964              : // a request object, so none of those runs application code.
    3965           89 : static bool reject_status_runs_middleware(int status) {
    3966           89 :   return status == CHTTP_STATUS_NOT_FOUND ||
    3967           89 :          status == CHTTP_STATUS_METHOD_NOT_ALLOWED ||
    3968           89 :          status == CHTTP_STATUS_PAYLOAD_TOO_LARGE;
    3969              : }
    3970              : 
    3971              : // Copies the effective middleware chain into dispatch: The root router's chain,
    3972              : // then router's when it's a sub-router. The copy lets the chain run after
    3973              : // srv->routes_lock is released, while routes or middleware can be added. router
    3974              : // is the matched route's router, the sub-router that owns a 404 or 405 path, or
    3975              : // NULL for a rejection from the root.
    3976              : // Returns false when the chains hold more than CHTTPSVR_MAX_MW entries, which
    3977              : // the caller answers with a 500. The caller holds srv->routes_lock.
    3978              : // dispatch->route stays NULL and the caller sets it for a matched route; a NULL
    3979              : // route keeps a rejected request away from every handler.
    3980         1121 : static bool snapshot_chain(struct chttpserver *srv, chttpsvr_router *router,
    3981              :                            dispatch_ctx *dispatch) {
    3982         1121 :   int mc = 0;
    3983         1121 :   chttpsvr_mw_node *n;
    3984         1430 :   for (n = srv->root_router->mw_head; n && mc < CHTTPSVR_MAX_MW; n = n->next)
    3985          309 :     dispatch->mw_snap[mc++] = (mw_entry){n->fn, n->ctx};
    3986         1121 :   bool overflow = (n != NULL);
    3987         1121 :   if (!overflow && router && router != srv->root_router) {
    3988          183 :     for (n = router->mw_head; n && mc < CHTTPSVR_MAX_MW; n = n->next)
    3989          103 :       dispatch->mw_snap[mc++] = (mw_entry){n->fn, n->ctx};
    3990              :     overflow = (n != NULL);
    3991              :   }
    3992         1121 :   dispatch->srv = srv;
    3993         1121 :   dispatch->router = router ? router : srv->root_router;
    3994         1121 :   dispatch->route = NULL;
    3995         1121 :   dispatch->mw_idx = 0;
    3996         1121 :   dispatch->mw_count = mc;
    3997         1121 :   return !overflow;
    3998              : }
    3999              : 
    4000              : // Frees the body of the request that ended and gives back its body memory
    4001              : // reservation in the same step. The reservation lives exactly as long as the
    4002              : // buffer, so max_partial_body_memory bounds every body byte a buffered route
    4003              : // holds, the one a running handler reads included. task_finish,
    4004              : // conn_drop_request_state, conn_reset_for_request and conn_close call it. It
    4005              : // clears conn->body and releases conn's charge on the server's shared body
    4006              : // memory budget (mem_release), which can let a waiting request go ahead. A
    4007              : // Content-Length body reserves memory before its buffer exists, so the release
    4008              : // doesn't depend on the buffer.
    4009         4474 : static inline __attribute__((always_inline)) void conn_drop_body(
    4010              :     chttpsvr_conn *conn) {
    4011         4474 :   if (conn->body.buf) {
    4012          175 :     ccol__mem_free(conn->m_procs, conn->body.buf);
    4013          175 :     memset(&conn->body, 0, sizeof(conn->body));
    4014              :   }
    4015         4474 :   if (__builtin_expect(conn->mem_charged != 0 || conn->mem_exempt, 0))
    4016          122 :     mem_release(conn);
    4017              : }
    4018              : 
    4019              : // Frees what the request holds that nobody reads once its response is being
    4020              : // written: The body, the path, the query, the header fields and the path
    4021              : // parameter values. A connection calls it when it starts to wait for a slow
    4022              : // reader or to linger, because such a wait holds no thread and no memory limit
    4023              : // could cover what it keeps. Its body reservation goes back to the server's
    4024              : // budget through conn_drop_body. matched_route stays, since routes live as long
    4025              : // as the server.
    4026          205 : static __attribute__((noinline, cold)) void conn_drop_request_state(
    4027              :     chttpsvr_conn *conn) {
    4028          205 :   ccol_memmgmt_procs *mp = conn->m_procs;
    4029          205 :   conn_drop_body(conn);
    4030          205 :   ccol__mem_free(mp, conn->path);
    4031          205 :   conn->path = NULL;
    4032           39 :   ccol__mem_free(mp, conn->decoded_path);
    4033          205 :   conn->decoded_path = NULL;
    4034          205 :   ccol__mem_free(mp, conn->raw_query);
    4035          205 :   conn->raw_query = NULL;
    4036          669 :   for (size_t i = 0; i < conn->hdr_count; i++) {
    4037          464 :     ccol__mem_free(mp, conn->hdr_names[i]);
    4038          464 :     ccol__mem_free(mp, conn->hdr_values[i]);
    4039              :   }
    4040          205 :   ccol__mem_free(mp, conn->hdr_names);
    4041          205 :   ccol__mem_free(mp, conn->hdr_values);
    4042          205 :   conn->hdr_names = conn->hdr_values = NULL;
    4043          205 :   conn->hdr_count = conn->hdr_cap = 0;
    4044          205 :   free_param_values(conn->matched_param_values,
    4045          205 :                     conn->matched_route ? conn->matched_route->param_count : 0,
    4046              :                     mp);
    4047          205 :   conn->matched_param_values = NULL;
    4048          205 : }
    4049              : 
    4050              : // Resets conn for its next request: It frees the previous request's state and
    4051              : // sets every per-request field to its default. conn_create runs it for the
    4052              : // first request and the keep-alive path between every two requests; without the
    4053              : // free of the param values, every request but the last would leak them. The
    4054              : // header-phase clock and the rate floor belong to one request, so they're
    4055              : // switched off; a header clock left armed would charge the next request for the
    4056              : // keep-alive gap.
    4057              : // The parser is re-initialized in place, because a struct assignment would copy
    4058              : // its 8 KiB line buffer every time. It reads the server's max_header_bytes and
    4059              : // max_body_size: The parser's max_chunk_size_override is set to max_body_size,
    4060              : // so one huge declared chunk is refused at once instead of tying up a worker
    4061              : // while it waits for bytes that never come. A max_body_size of 0 leaves it at
    4062              : // 0, which is also "no cap" there. The body reservation goes back to the server
    4063              : // through conn_drop_body.
    4064         1950 : static void conn_reset_for_request(chttpsvr_conn *conn) {
    4065         1950 :   ccol_memmgmt_procs *mp = conn->m_procs;
    4066         1950 :   ccol__mem_free(mp, conn->path);
    4067         1950 :   conn->path = NULL;
    4068          170 :   ccol__mem_free(mp, conn->decoded_path);
    4069         1950 :   conn->decoded_path = NULL;
    4070         1950 :   ccol__mem_free(mp, conn->raw_query);
    4071         1950 :   conn->raw_query = NULL;
    4072         3115 :   for (size_t i = 0; i < conn->hdr_count; i++) {
    4073         1165 :     ccol__mem_free(mp, conn->hdr_names[i]);
    4074         1165 :     ccol__mem_free(mp, conn->hdr_values[i]);
    4075              :   }
    4076         1950 :   ccol__mem_free(mp, conn->hdr_names);
    4077         1950 :   ccol__mem_free(mp, conn->hdr_values);
    4078         1950 :   conn->hdr_names = conn->hdr_values = NULL;
    4079         1950 :   conn->hdr_count = conn->hdr_cap = 0;
    4080         1950 :   free_param_values(conn->matched_param_values,
    4081         1950 :                     conn->matched_route ? conn->matched_route->param_count : 0,
    4082              :                     mp);
    4083         1950 :   conn->matched_router = NULL;
    4084         1950 :   conn->matched_route = NULL;
    4085         1950 :   conn->matched_param_values = NULL;
    4086         1950 :   memset(&conn->dispatch, 0, sizeof(conn->dispatch));
    4087         1950 :   destroy_resp(&conn->resp, mp);
    4088         1950 :   conn->resp.status_code = CHTTP_STATUS_OK;
    4089         1950 :   conn->resp.m_procs = mp;
    4090         1950 :   conn->req_rejected = false;
    4091         1950 :   conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4092         1950 :   conn->options_star = false;
    4093         1950 :   conn->expects_continue = false;
    4094         1950 :   conn->interim_continue_sent = false;
    4095         1950 :   conn->interim_write_failed = false;
    4096         1950 :   conn_drop_body(conn);
    4097         1950 :   conn->body_bytes_seen = 0;
    4098         1950 :   conn->body_too_large = false;
    4099         1950 :   conn->body_alloc_failed = false;
    4100         1950 :   conn->transfer_aborted = false;
    4101         1950 :   conn->body_malformed = false;
    4102         1950 :   conn->read_deadline_set = false;
    4103         1950 :   conn->deadline_exceeded = false;
    4104         1950 :   conn->write_deadline_set = false;
    4105         1950 :   conn->header_phase_active = false;
    4106         1950 :   conn->rate_active = false;
    4107              : 
    4108         1950 :   const chttp1_settings *settings = conn->parser.settings;
    4109         1950 :   chttp1_parser_init_request(&conn->parser, settings);
    4110         1950 :   conn->parser.data = conn;
    4111         1950 :   size_t max_hdr_bytes = atomic_load(&conn->srv->max_header_bytes);
    4112         1950 :   if (max_hdr_bytes) {
    4113           23 :     conn->parser.max_header_count_override = 0;
    4114           23 :     conn->parser.max_total_header_bytes_override = max_hdr_bytes;
    4115              :   }
    4116         1950 :   conn->parser.max_chunk_size_override =
    4117         1950 :       (uint64_t)atomic_load(&conn->srv->max_body_size);
    4118         1950 : }
    4119              : 
    4120              : // Allocates a connection for an accepted fd, so the reactor has somewhere to
    4121              : // keep its parser and request state. It starts with one lifetime reference, the
    4122              : // application's, and runs conn_reset_for_request so even the first request gets
    4123              : // the per-request defaults; a calloc'ed status code of 0 would otherwise go out
    4124              : // as 500. Returns NULL when the allocation fails.
    4125         1288 : static chttpsvr_conn *conn_create(struct chttpserver *srv, int fd,
    4126              :                                   const chttp1_settings *settings) {
    4127         2576 :   chttpsvr_conn *conn =
    4128         1288 :       (chttpsvr_conn *)ccol__mem_calloc(srv->m_procs, 1, sizeof(*conn));
    4129         1288 :   if (!conn) return NULL;
    4130         1286 :   conn->fd = fd;
    4131         1286 :   conn->srv = srv;
    4132         1286 :   conn->m_procs = srv->m_procs;
    4133         1286 :   atomic_init(&conn->lifetime_refs, 1);
    4134         1286 :   chttp1_parser_init_request(&conn->parser, settings);
    4135         1286 :   conn->parser.data = conn;
    4136         1286 :   clock_gettime(CLOCK_MONOTONIC, &conn->last_activity);
    4137         1286 :   conn_reset_for_request(conn);
    4138         1286 :   return conn;
    4139              : }
    4140              : 
    4141              : // Frees a connection once its last lifetime reference is gone: It unlinks conn
    4142              : // from the idle and diverted lists, destroys its TLS state, closes the fd and
    4143              : // frees everything it owns. It can run on the reactor thread from
    4144              : // conn_on_removed. The decrement of srv->current_connections comes last, after
    4145              : // every access to conn: drain_and_close_all_connections takes 0 as proof that
    4146              : // every connection is done and lets the server teardown free the routers and
    4147              : // procs.
    4148         1286 : static void conn_free(chttpsvr_conn *conn) {
    4149         1286 :   if (!conn) return;
    4150         1286 :   struct chttpserver *srv = conn->srv;
    4151         1286 :   ccol_memmgmt_procs *mp = conn->m_procs;
    4152         1286 :   idle_list_remove(conn);
    4153         1286 :   diverted_list_remove(conn);
    4154         1286 :   if (conn->tls) ctls_conn_destroy(conn->tls);
    4155         1286 :   if (conn->fd >= 0) close(conn->fd);
    4156         1286 :   ccol__mem_free(mp, conn->path);
    4157          166 :   ccol__mem_free(mp, conn->decoded_path);
    4158         1286 :   ccol__mem_free(mp, conn->raw_query);
    4159         2659 :   for (size_t i = 0; i < conn->hdr_count; i++) {
    4160         1373 :     ccol__mem_free(mp, conn->hdr_names[i]);
    4161         1373 :     ccol__mem_free(mp, conn->hdr_values[i]);
    4162              :   }
    4163         1286 :   ccol__mem_free(mp, conn->hdr_names);
    4164         1286 :   ccol__mem_free(mp, conn->hdr_values);
    4165         1286 :   free_param_values(conn->matched_param_values,
    4166         1286 :                     conn->matched_route ? conn->matched_route->param_count : 0,
    4167              :                     mp);
    4168         1286 :   destroy_resp(&conn->resp, mp);
    4169         1286 :   ccol__mem_free(mp, conn->body.buf);
    4170         1286 :   ccol__mem_free(mp, conn->carry_over);
    4171         1286 :   if (conn->wp_head) ccol__mem_free(mp, conn->wp_head);
    4172         1286 :   ccol__mem_free(mp, conn);
    4173              : 
    4174         1286 :   atomic_fetch_sub(&srv->current_connections, 1);
    4175              : }
    4176              : 
    4177              : // The on_removed handler of every conn->reg registration. It exists because
    4178              : // ceventloop_remove can't promise synchronously that no dispatch touches conn
    4179              : // without a lock cycle with the server's locks, so the free waits for this
    4180              : // call. It fires once per registration, from the reactor's reclaim path. It
    4181              : // drops one conn->lifetime_refs reference and frees conn on the last one, then
    4182              : // always drops one srv->lifetime_refs reference and finishes the server's
    4183              : // destroy on the last one, so chttpsvr__destroy never has to block for it. srv
    4184              : // is read before conn may be freed.
    4185          933 : static void conn_on_removed(void *arg) {
    4186          933 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    4187          933 :   struct chttpserver *srv = conn->srv;
    4188          933 :   if (atomic_fetch_sub(&conn->lifetime_refs, 1) == 1) conn_free(conn);
    4189          933 :   if (atomic_fetch_sub(&srv->lifetime_refs, 1) == 1)
    4190            1 :     chttpsvr_finish_destroy(srv);
    4191          933 : }
    4192              : 
    4193              : // Closes conn from the application side; every path that ends a connection
    4194              : // calls it, once per connection. It unlinks conn from the idle and diverted
    4195              : // lists at once, so neither the sweep nor a shutdown drain can find it again,
    4196              : // and removes its registration from the server reactor. The free happens later
    4197              : // in conn_on_removed when an earlier registration holds a reference too. It
    4198              : // drops the body at once so a waiting request can take its memory, then drops
    4199              : // the application's lifetime reference.
    4200         1286 : static void conn_close(chttpsvr_conn *conn) {
    4201         1286 :   idle_list_remove(conn);
    4202         1286 :   diverted_list_remove(conn);
    4203              : 
    4204         1286 :   if (conn->reg) {
    4205          925 :     ceventloop_reg reg = conn->reg;
    4206          925 :     conn->reg = CEVENTLOOP_REG_NULL;
    4207          925 :     ceventloop_remove(srv_engine_bundler.reactor, reg);
    4208              :   }
    4209              : 
    4210         1286 :   conn->state = CONN_ST_CLOSING;
    4211         1286 :   conn_drop_body(conn);
    4212         1286 :   if (atomic_fetch_sub(&conn->lifetime_refs, 1) == 1) conn_free(conn);
    4213         1286 : }
    4214              : 
    4215              : // The parser callback for the request line, on the reactor thread. It records
    4216              : // the method and stores the raw path (percent-encoded as it arrived) and the
    4217              : // query on conn, which routing and the request accessors read later, and it
    4218              : // refuses request lines that this server can't serve safely. Returns 1 to stop
    4219              : // the parse when it rejects the request, always with conn->req_rejected and
    4220              : // reject_status set, because conn_feed_bytes only answers a CHTTP1_USER abort
    4221              : // with a response when they are set.
    4222              : // A major version other than 1 gets 505, and a method we don't implement gets
    4223              : // 501, since a CHTTP_ANY route would otherwise hand its handler a meaningless
    4224              : // method. "OPTIONS *" is answered by the server itself; "*" with any other
    4225              : // method is a 400. An absolute-form target is reduced to its origin-form part,
    4226              : // and an empty path there means "/". Any other path that doesn't start with "/"
    4227              : // is a 400, or "admin/secret" would reach the "/admin/secret" route while a
    4228              : // middleware guarding "/admin" let it through. A failed allocation gets 500.
    4229         1272 : static int http1_on_request_line(chttp1_parser *p, const char *method,
    4230              :                                  size_t method_len, const char *target,
    4231              :                                  size_t target_len) {
    4232         1272 :   chttpsvr_conn *conn = (chttpsvr_conn *)p->data;
    4233              : 
    4234         1272 :   if (p->http_major != 1) {
    4235            3 :     conn->req_rejected = true;
    4236            3 :     conn->reject_status = CHTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED;
    4237            3 :     return 1;
    4238              :   }
    4239              : 
    4240         1269 :   conn->method = parse_method(method, method_len);
    4241              : 
    4242         1269 :   if (conn->method == CHTTP_METHOD_UNKNOWN) {
    4243            7 :     conn->req_rejected = true;
    4244            2 :     conn->reject_status = (target_len == 1 && target[0] == '*')
    4245              :                               ? CHTTP_STATUS_BAD_REQUEST
    4246            7 :                               : CHTTP_STATUS_NOT_IMPLEMENTED;
    4247            7 :     return 1;
    4248              :   }
    4249              : 
    4250         1262 :   if (target_len == 1 && target[0] == '*') {
    4251           56 :     if (conn->method != CHTTP_OPTIONS) {
    4252            4 :       conn->req_rejected = true;
    4253            4 :       conn->reject_status = CHTTP_STATUS_BAD_REQUEST;
    4254            4 :       return 1;
    4255              :     }
    4256           52 :     char *star = (char *)ccol__mem_alloc(conn->m_procs, 2);
    4257           52 :     if (!star) {
    4258            0 :       conn->req_rejected = true;
    4259            0 :       conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4260            0 :       return 1;
    4261              :     }
    4262           52 :     star[0] = '*';
    4263           52 :     star[1] = '\0';
    4264           52 :     conn->path = star;
    4265           52 :     conn->options_star = true;
    4266           52 :     return 0;
    4267              :   }
    4268              : 
    4269         1206 :   const char *eff_target = target;
    4270         1206 :   size_t eff_target_len = target_len;
    4271         1206 :   bool was_absolute =
    4272         1206 :       strip_absolute_form(target, target_len, &eff_target, &eff_target_len);
    4273              : 
    4274         1206 :   const char *qmark = (const char *)memchr(eff_target, '?', eff_target_len);
    4275         1206 :   size_t path_raw_len = qmark ? (size_t)(qmark - eff_target) : eff_target_len;
    4276              : 
    4277         1206 :   if (path_raw_len > 0 ? eff_target[0] != '/' : !was_absolute) {
    4278            6 :     conn->req_rejected = true;
    4279            6 :     conn->reject_status = CHTTP_STATUS_BAD_REQUEST;
    4280            6 :     return 1;
    4281              :   }
    4282              : 
    4283         1200 :   bool empty_abs_path = (was_absolute && path_raw_len == 0);
    4284         1200 :   size_t path_alloc_len = empty_abs_path ? 1 : path_raw_len;
    4285         1200 :   char *path_raw = (char *)ccol__mem_alloc(conn->m_procs, path_alloc_len + 1);
    4286         1200 :   if (!path_raw) {
    4287            2 :     conn->req_rejected = true;
    4288            2 :     conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4289            2 :     return 1;
    4290              :   }
    4291         1198 :   if (empty_abs_path)
    4292            4 :     path_raw[0] = '/';
    4293              :   else
    4294         1194 :     memcpy(path_raw, eff_target, path_raw_len);
    4295         1198 :   path_raw[path_alloc_len] = '\0';
    4296         1198 :   conn->path = path_raw;
    4297              : 
    4298         1198 :   if (qmark) {
    4299          152 :     size_t qlen = eff_target_len - path_raw_len - 1;
    4300          152 :     conn->raw_query = (char *)ccol__mem_alloc(conn->m_procs, qlen + 1);
    4301          152 :     if (!conn->raw_query) {
    4302            1 :       conn->req_rejected = true;
    4303            1 :       conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4304            1 :       return 1;
    4305              :     }
    4306          151 :     memcpy(conn->raw_query, qmark + 1, qlen);
    4307          151 :     conn->raw_query[qlen] = '\0';
    4308              :   }
    4309              :   return 0;
    4310              : }
    4311              : 
    4312              : // Parser callback for one header field of the request: It copies name and value
    4313              : // into conn->hdr_names and conn->hdr_values, growing both arrays as needed.
    4314              : // chttpsvr_req_header reads those arrays later. A failed allocation sets
    4315              : // conn->req_rejected with a 500 status before returning 1, so the client gets
    4316              : // an answer instead of a silent close.
    4317              : // Only the header block reaches this function. init_parser_settings leaves
    4318              : // on_trailer NULL, so a trailer field can't land in these arrays;
    4319              : // chttpsvr_req_header scans them backwards, and a trailer there would override
    4320              : // a header that an upstream proxy set on a request we already routed.
    4321         3036 : static int http1_on_header(chttp1_parser *p, const char *name, size_t name_len,
    4322              :                            const char *value, size_t value_len) {
    4323         3036 :   chttpsvr_conn *conn = (chttpsvr_conn *)p->data;
    4324         3036 :   if (conn->hdr_count >= conn->hdr_cap) {
    4325         1283 :     size_t new_cap = doubling_growth_cap(conn->hdr_cap, sizeof(char *), 8);
    4326              :     if (new_cap == 0) {
    4327            0 :       conn->req_rejected = true;
    4328            0 :       conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4329            0 :       return 1;
    4330              :     }
    4331         1283 :     char **nn = (char **)ccol__mem_realloc(conn->m_procs, conn->hdr_names,
    4332              :                                            new_cap * sizeof(char *));
    4333         1283 :     if (!nn) {
    4334            2 :       conn->req_rejected = true;
    4335            2 :       conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4336            2 :       return 1;
    4337              :     }
    4338         1281 :     conn->hdr_names = nn;
    4339         1281 :     char **nv = (char **)ccol__mem_realloc(conn->m_procs, conn->hdr_values,
    4340              :                                            new_cap * sizeof(char *));
    4341         1281 :     if (!nv) {
    4342            2 :       conn->req_rejected = true;
    4343            2 :       conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4344            2 :       return 1;
    4345              :     }
    4346         1279 :     conn->hdr_values = nv;
    4347         1279 :     conn->hdr_cap = new_cap;
    4348              :   }
    4349         3032 :   char *n = (char *)ccol__mem_alloc(conn->m_procs, name_len + 1);
    4350         3032 :   char *v = (char *)ccol__mem_alloc(conn->m_procs, value_len + 1);
    4351         3032 :   if (!n || !v) {
    4352           29 :     ccol__mem_free(conn->m_procs, n);
    4353           29 :     ccol__mem_free(conn->m_procs, v);
    4354           29 :     conn->req_rejected = true;
    4355           29 :     conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4356           29 :     return 1;
    4357              :   }
    4358         3003 :   memcpy(n, name, name_len);
    4359         3003 :   n[name_len] = '\0';
    4360         3003 :   memcpy(v, value, value_len);
    4361         3003 :   v[value_len] = '\0';
    4362         3003 :   conn->hdr_names[conn->hdr_count] = n;
    4363         3003 :   conn->hdr_values[conn->hdr_count] = v;
    4364         3003 :   conn->hdr_count++;
    4365         3003 :   return 0;
    4366              : }
    4367              : 
    4368              : // Parser callback that runs once the request headers are complete. It decides
    4369              : // what happens to the request: It rejects (sets conn->req_rejected and
    4370              : // conn->reject_status, returns -1) a transfer coding other than chunked with
    4371              : // 501, an unmatched path or method with 404 or 405, a declared Content-Length
    4372              : // above max_body_size on a buffered route with 413, and any allocation failure
    4373              : // with 500. Otherwise it stores the matched router, route, path parameter
    4374              : // values and decoded path on conn and returns CHTTP1_HEADERS_DIVERT_BODY, so
    4375              : // every request goes to a worker.
    4376              : // It takes srv->routes_lock for reading around find_route and snapshot_chain,
    4377              : // so the middleware chain is copied under the lock and a 404, 405 or 413 runs
    4378              : // the chain of the router that owns the path. Streaming routes never get the
    4379              : // 413 here, because their handler is always called and decides the answer
    4380              : // itself. conn->divert_gate tells conn_start_diverted whether the request needs
    4381              : // the streaming pool or a body memory reservation first. The decoded path is
    4382              : // allocated before the hand-over, because chttpsvr_req_path promises a handler
    4383              : // a non-NULL pointer.
    4384         1185 : static int http1_on_headers_complete(chttp1_parser *p) {
    4385         1185 :   chttpsvr_conn *conn = (chttpsvr_conn *)p->data;
    4386         1185 :   if (conn->req_rejected) return -1;
    4387              : 
    4388         1185 :   if (chttp1_has_other_transfer_coding(p)) {
    4389            2 :     conn->req_rejected = true;
    4390            2 :     conn->reject_status = CHTTP_STATUS_NOT_IMPLEMENTED;
    4391            2 :     return -1;
    4392              :   }
    4393              : 
    4394         1183 :   struct chttpserver *srv = conn->srv;
    4395         1183 :   if (conn->options_star) {
    4396           52 :     conn->matched_router = srv->root_router;
    4397           52 :     conn->matched_route = &options_star_route;
    4398           52 :     conn->expects_continue = chttp1_expects_continue(p);
    4399           52 :     conn->divert_gate = 0;
    4400           52 :     return CHTTP1_HEADERS_DIVERT_BODY;
    4401              :   }
    4402         1131 :   ccol__rw_lock_rdlock(srv->routes_lock);
    4403         1131 :   match_result mr = find_route(srv, conn->path, conn->method);
    4404         1131 :   if (mr.result == ROUTE_MATCH_NONE || mr.result == ROUTE_MATCH_METHOD) {
    4405          104 :     bool chain_ok = snapshot_chain(srv, mr.router, &conn->dispatch);
    4406          104 :     ccol__rw_lock_unlock(srv->routes_lock);
    4407          104 :     conn->req_rejected = true;
    4408          104 :     if (!chain_ok) {
    4409            0 :       conn->dispatch.mw_count = 0;
    4410            0 :       conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4411            0 :       return -1;
    4412              :     }
    4413          104 :     if (mr.result == ROUTE_MATCH_NONE) {
    4414           94 :       conn->reject_status = CHTTP_STATUS_NOT_FOUND;
    4415              :     } else {
    4416           10 :       conn->reject_status = CHTTP_STATUS_METHOD_NOT_ALLOWED;
    4417           10 :       conn->allowed_methods = mr.allowed_methods;
    4418              :     }
    4419          104 :     return -1;
    4420              :   }
    4421         1027 :   if (mr.result == ROUTE_MATCH_OOM) {
    4422           10 :     ccol__rw_lock_unlock(srv->routes_lock);
    4423           10 :     conn->req_rejected = true;
    4424           10 :     conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4425           10 :     return -1;
    4426              :   }
    4427              : 
    4428         1017 :   dispatch_ctx *dispatch = &conn->dispatch;
    4429         1017 :   if (!snapshot_chain(srv, mr.router, dispatch)) {
    4430            2 :     ccol__rw_lock_unlock(srv->routes_lock);
    4431            2 :     dispatch->mw_count = 0;
    4432            2 :     free_param_values(mr.param_values, mr.route->param_count, srv->m_procs);
    4433            2 :     conn->req_rejected = true;
    4434            2 :     conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4435            2 :     return -1;
    4436              :   }
    4437         1015 :   dispatch->route = mr.route;
    4438         1015 :   ccol__rw_lock_unlock(srv->routes_lock);
    4439              : 
    4440         1015 :   size_t divert_gate = 0;
    4441         1015 :   if (mr.route->is_streaming) {
    4442           96 :     if (atomic_load(&srv->stream_threads) >= 0) divert_gate = SIZE_MAX;
    4443          919 :   } else if (chttp1_has_content_length(p)) {
    4444          129 :     size_t limit = atomic_load(&srv->max_body_size);
    4445          129 :     uint64_t declared = chttp1_declared_content_length(p);
    4446          129 :     if (limit && declared > (uint64_t)limit) {
    4447            4 :       free_param_values(mr.param_values, mr.route->param_count, srv->m_procs);
    4448            4 :       conn->dispatch.route = NULL;
    4449            4 :       conn->dispatch.mw_idx = 0;
    4450            4 :       conn->req_rejected = true;
    4451            4 :       conn->reject_status = CHTTP_STATUS_PAYLOAD_TOO_LARGE;
    4452            4 :       return -1;
    4453              :     }
    4454          125 :     if (declared && atomic_load(&srv->mem_cap) != SIZE_MAX)
    4455          123 :       divert_gate =
    4456              :           declared < (uint64_t)(SIZE_MAX - 1) ? (size_t)declared : SIZE_MAX - 1;
    4457              :   }
    4458              : 
    4459         1011 :   size_t plen = strlen(conn->path);
    4460         1011 :   char *dp = (char *)ccol__mem_alloc(srv->m_procs, plen + 1);
    4461         1011 :   if (dp) {
    4462         1010 :     ssize_t dlen = decode_path_unsafe(dp, conn->path);
    4463         1010 :     if (dlen >= 0) {
    4464         1010 :       dp[(size_t)dlen] = '\0';
    4465              :     } else {
    4466            0 :       ccol__mem_free(srv->m_procs, dp);
    4467              :       dp = NULL;
    4468              :     }
    4469              :   }
    4470         1010 :   if (!dp) {
    4471            1 :     free_param_values(mr.param_values, mr.route->param_count, srv->m_procs);
    4472            1 :     conn->req_rejected = true;
    4473            1 :     conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4474            1 :     return -1;
    4475              :   }
    4476              : 
    4477         1010 :   conn->matched_router = mr.router;
    4478         1010 :   conn->matched_route = mr.route;
    4479         1010 :   conn->matched_param_values = mr.param_values;
    4480         1010 :   conn->expects_continue = chttp1_expects_continue(p);
    4481         1010 :   conn->decoded_path = dp;
    4482         1010 :   conn->divert_gate = divert_gate;
    4483              : 
    4484         1010 :   return CHTTP1_HEADERS_DIVERT_BODY;
    4485              : }
    4486              : 
    4487              : // First buffer capacity of a Content-Length body: The 8 KiB that can come with
    4488              : // the headers plus one 8 KiB read window of drain_body. It is also what such a
    4489              : // body reserves before a worker reads it (see body_first_reserve).
    4490              : #define CHTTPSVR_BODY_FIRST_CAP ((size_t)16384)
    4491              : 
    4492              : // Returns the capacity the body buffer of conn grows to from cap so it holds
    4493              : // min_cap bytes. http1_on_body and drain_body_socket_read both use it, so a
    4494              : // growth and its memory reservation agree. limit is the max_body_size of the
    4495              : // request (0 for none).
    4496              : // A buffered Content-Length body that arrived whole while body memory is
    4497              : // limited gets its full declared length at once, since it holds no reservation.
    4498              : // Any other Content-Length body doubles from CHTTPSVR_BODY_FIRST_CAP up to its
    4499              : // declared length, so a client that declares a lot and sends little holds
    4500              : // little memory. Other bodies double from 8 KiB up to limit. The doubling stops
    4501              : // before it can wrap past SIZE_MAX. It reads conn->mem_charged,
    4502              : // conn->mem_exempt and srv->mem_cap.
    4503          500 : static size_t body_grow_target(const chttpsvr_conn *conn, size_t cap,
    4504              :                                size_t min_cap, size_t limit) {
    4505          500 :   if (min_cap <= cap) return cap;
    4506          498 :   size_t ceiling = limit;
    4507          498 :   size_t start = 8192;
    4508          956 :   if (!conn->matched_route->is_streaming && !conn->options_star &&
    4509          457 :       chttp1_has_content_length(&conn->parser)) {
    4510          348 :     uint64_t rest = chttp1_declared_content_length(&conn->parser);
    4511          347 :     size_t held = conn->body.len;
    4512         1042 :     size_t d =
    4513          347 :         rest < (uint64_t)(SIZE_MAX - held) ? held + (size_t)rest : SIZE_MAX;
    4514          348 :     if (d >= min_cap) {
    4515          347 :       if (conn->mem_charged == 0 && !conn->mem_exempt &&
    4516            7 :           atomic_load(&conn->srv->mem_cap) != SIZE_MAX)
    4517              :         return d;
    4518          340 :       if (!ceiling || d < ceiling) ceiling = d;
    4519              :       start = CHTTPSVR_BODY_FIRST_CAP;
    4520              :     }
    4521              :   }
    4522          491 :   size_t new_cap = cap ? cap : start;
    4523          693 :   while (new_cap < min_cap) {
    4524          202 :     if (new_cap > SIZE_MAX / 2) {
    4525              :       new_cap = min_cap;
    4526              :       break;
    4527              :     }
    4528          202 :     new_cap *= 2;
    4529              :   }
    4530          491 :   if (ceiling && new_cap > ceiling && min_cap <= ceiling) new_cap = ceiling;
    4531              :   return new_cap;
    4532              : }
    4533              : 
    4534              : static void mem_trim(chttpsvr_conn *conn, size_t keep);
    4535              : #ifdef RUNNING_UNIT_TESTS
    4536              : static void body_growth_note_for_tests(const chttpsvr_conn *conn,
    4537              :                                        size_t old_cap, size_t new_cap);
    4538              : #endif
    4539              : 
    4540              : // Parser callback for each piece of request body. It appends the bytes to
    4541              : // conn->body, which collects a buffered route's whole body or holds the bytes
    4542              : // of a streaming route that chttpsvr_req_read hasn't taken yet, and it enforces
    4543              : // max_body_size, which the parser knows nothing about. Returns 0, or 1 to stop
    4544              : // the parse: conn->body_too_large is set for a body over the limit or one whose
    4545              : // size would overflow size_t (possible on ILP32 for a long streaming body), and
    4546              : // conn->body_alloc_failed for a real allocation failure.
    4547              : // min_cap is checked for wraparound before it is compared with the capacity, or
    4548              : // a wrapped sum would skip the growth and overflow the buffer in the memcpy.
    4549              : // After a growth the body's memory reservation is trimmed to the new buffer,
    4550              : // because the old block is gone.
    4551         4291 : static int http1_on_body(chttp1_parser *p, const char *at, size_t len) {
    4552         4291 :   chttpsvr_conn *conn = (chttpsvr_conn *)p->data;
    4553         4291 :   if (len > SIZE_MAX - conn->body_bytes_seen) {
    4554            0 :     conn->body_too_large = true;
    4555            0 :     return 1;
    4556              :   }
    4557         4291 :   conn->body_bytes_seen += len;
    4558        12816 :   size_t body_limit = conn->options_star
    4559              :                           ? CHTTPSVR_OPTIONS_STAR_MAX_BODY
    4560         4291 :                           : atomic_load(&conn->srv->max_body_size);
    4561         4291 :   if (body_limit && conn->body_bytes_seen > body_limit) {
    4562            3 :     conn->body_too_large = true;
    4563            3 :     return 1;
    4564              :   }
    4565         4288 :   growbuf *b = &conn->body;
    4566         4288 :   if (conn->matched_route->is_streaming && b->pos == b->len && b->pos > 0)
    4567           56 :     b->pos = b->len = 0;
    4568         4288 :   size_t min_cap = b->len + len;
    4569         4288 :   if (min_cap < b->len) {
    4570            0 :     conn->body_too_large = true;
    4571            0 :     return 1;
    4572              :   }
    4573         4288 :   if (min_cap > b->cap) {
    4574          269 :     size_t old_cap = b->cap;
    4575          269 :     size_t new_cap = body_grow_target(conn, old_cap, min_cap, body_limit);
    4576          269 :     char *nb = (char *)ccol__mem_realloc(conn->m_procs, b->buf, new_cap);
    4577          269 :     if (!nb) {
    4578            1 :       conn->body_alloc_failed = true;
    4579            1 :       return 1;
    4580              :     }
    4581          268 :     b->buf = nb;
    4582          268 :     b->cap = new_cap;
    4583              : #ifdef RUNNING_UNIT_TESTS
    4584          268 :     body_growth_note_for_tests(conn, old_cap, new_cap);
    4585              : #endif
    4586          268 :     if (__builtin_expect(conn->mem_charged > new_cap, 0))
    4587           89 :       mem_trim(conn, new_cap);
    4588              :   }
    4589         4287 :   memcpy(b->buf + b->len, at, len);
    4590         4287 :   b->len += len;
    4591         4287 :   return 0;
    4592              : }
    4593              : 
    4594              : // Parser callback for the end of a message; the server needs nothing at that
    4595              : // point.
    4596          975 : static int http1_on_message_complete(chttp1_parser *p) {
    4597          975 :   (void)p;
    4598          975 :   return 0;
    4599              : }
    4600              : 
    4601              : // The parser callbacks every server connection shares, filled once by
    4602              : // init_parser_settings through the once flag.
    4603              : static struct {
    4604              :   chttp1_settings settings;
    4605              :   ccol__once_flag once;
    4606              : } srv_parser_bundler = {0};
    4607              : 
    4608              : // Fills srv_parser_bundler.settings with this file's callbacks; it runs once,
    4609              : // before the first connection parses a request. on_trailer stays NULL on
    4610              : // purpose, so no trailer field can reach the request's header array (see
    4611              : // http1_on_header).
    4612            6 : static void init_parser_settings(void) {
    4613            6 :   chttp1_settings_init(&srv_parser_bundler.settings);
    4614            6 :   srv_parser_bundler.settings.on_request_line = http1_on_request_line;
    4615            6 :   srv_parser_bundler.settings.on_header = http1_on_header;
    4616            6 :   srv_parser_bundler.settings.on_headers_complete = http1_on_headers_complete;
    4617            6 :   srv_parser_bundler.settings.on_body = http1_on_body;
    4618            6 :   srv_parser_bundler.settings.on_message_complete = http1_on_message_complete;
    4619            6 : }
    4620              : 
    4621              : // The pools of a server, so srv_submit can find the current pool of the same
    4622              : // kind again after a restart.
    4623              : typedef enum {
    4624              :   SRV_POOL_WORKER = 0,
    4625              :   SRV_POOL_REJECT = 1,
    4626              :   SRV_POOL_STREAM = 2
    4627              : } srv_pool_kind;
    4628              : 
    4629              : static cthrpool stream_pool_get(struct chttpserver *srv);
    4630              : 
    4631              : // Starts a new run of the streaming pool after the caller (holding srv->mutex)
    4632              : // has taken the old pool out of service. It resets the token counts and bumps
    4633              : // stream_gen, which tells every task of the earlier run to stop taking
    4634              : // requests. Both change under srv->wait_mutex, which every reader of sq_tokens
    4635              : // holds.
    4636          906 : static void stream_new_run_locked(struct chttpserver *srv) {
    4637          906 :   ccol__mutex_lock(srv->wait_mutex);
    4638          906 :   srv->sq_tokens = 0;
    4639          906 :   srv->sq_unclaimed = 0;
    4640          906 :   atomic_fetch_add(&srv->stream_gen, 1);
    4641          906 :   ccol__mutex_unlock(srv->wait_mutex);
    4642          906 : }
    4643              : 
    4644              : // Returns the current pool of kind k of srv, read under srv->mutex. The
    4645              : // streaming pool is created on demand, as for any streaming request.
    4646              : // srv_submit_retry uses it to find the pool that replaced a retired one.
    4647            3 : static cthrpool srv_current_pool(struct chttpserver *srv, srv_pool_kind k) {
    4648            3 :   if (k == SRV_POOL_STREAM) return stream_pool_get(srv);
    4649            3 :   ccol__mutex_lock(srv->mutex);
    4650            3 :   cthrpool p = k == SRV_POOL_WORKER ? srv->worker_pool : srv->reject_pool;
    4651            3 :   ccol__mutex_unlock(srv->mutex);
    4652            3 :   return p;
    4653              : }
    4654              : 
    4655              : #ifdef RUNNING_UNIT_TESTS
    4656              : // Test hook: Holds the nth worker submit of conn_start_diverted, after it read
    4657              : // the pool and before it submits, so a test can restart the server inside that
    4658              : // window. retried counts the submits that srv_submit_retry moved to a newer
    4659              : // pool.
    4660              : static struct {
    4661              :   _Atomic int countdown;
    4662              :   _Atomic bool entered;
    4663              :   _Atomic bool go;
    4664              :   _Atomic size_t retried;
    4665              : } g_divert_submit_hook;
    4666              : // Test controls of g_divert_submit_hook: Arm it for the nth next submit, read
    4667              : // the retry count, ask whether a submit is held, and let it go.
    4668            1 : void chttpsvr__arm_divert_submit_hook_for_tests(int nth) {
    4669            1 :   atomic_store(&g_divert_submit_hook.entered, false);
    4670            1 :   atomic_store(&g_divert_submit_hook.go, false);
    4671            1 :   atomic_store(&g_divert_submit_hook.countdown, nth);
    4672            1 : }
    4673            2 : size_t chttpsvr__submit_retried_for_tests(void) {
    4674            2 :   return atomic_load(&g_divert_submit_hook.retried);
    4675              : }
    4676            2 : bool chttpsvr__divert_submit_hook_entered_for_tests(void) {
    4677            2 :   return atomic_load(&g_divert_submit_hook.entered);
    4678              : }
    4679            1 : void chttpsvr__release_divert_submit_hook_for_tests(void) {
    4680            1 :   atomic_store(&g_divert_submit_hook.go, true);
    4681            1 : }
    4682              : // Counts down the armed submit and holds the one it lands on until the test
    4683              : // releases it, for at most about 20 seconds.
    4684          961 : static void divert_submit_hook_wait_if_armed(void) {
    4685          961 :   int left = atomic_load(&g_divert_submit_hook.countdown);
    4686          963 :   while (left > 0 && !atomic_compare_exchange_weak(
    4687              :                          &g_divert_submit_hook.countdown, &left, left - 1)) {
    4688          961 :   }
    4689          961 :   if (left != 1) return;
    4690            1 :   atomic_store(&g_divert_submit_hook.entered, true);
    4691            3 :   for (int i = 0; i < 20000 && !atomic_load(&g_divert_submit_hook.go); i++) {
    4692            2 :     struct timespec nap = {0, 1000000L};
    4693            2 :     nanosleep(&nap, NULL);
    4694              :   }
    4695              : }
    4696              : #endif
    4697              : 
    4698              : // The cold half of srv_submit, for a task the first pool refused. If a restart
    4699              : // replaced that pool after the caller read it, the refusal came from a retired,
    4700              : // draining pool, so the task goes to the current pool of the same kind and a
    4701              : // request that arrives during a restart isn't refused because of it. Returns
    4702              : // true once a pool took the task, and false when the current pool itself
    4703              : // refuses (a full queue) or there is none.
    4704            3 : static __attribute__((noinline, cold)) bool srv_submit_retry(
    4705              :     struct chttpserver *srv, srv_pool_kind k, cthrpool pool, void (*fn)(void *),
    4706              :     void *arg) {
    4707            3 :   for (;;) {
    4708            3 :     cthrpool cur = srv_current_pool(srv, k);
    4709            3 :     if (!cur || cur == pool) return false;
    4710            1 :     pool = cur;
    4711            1 :     if (cthrpool_try_submit(pool, fn, arg, NULL) == ccol_success) {
    4712              : #ifdef RUNNING_UNIT_TESTS
    4713            1 :       atomic_fetch_add(&g_divert_submit_hook.retried, 1);
    4714              : #endif
    4715            1 :       return true;
    4716              :     }
    4717              :   }
    4718              : }
    4719              : 
    4720              : // Submits fn(arg) to pool, which the caller read from srv under srv->mutex,
    4721              : // without blocking. If pool refuses, it retries on the current pool of kind k
    4722              : // (see srv_submit_retry). Returns whether some pool took the task.
    4723         1723 : static inline __attribute__((always_inline)) bool srv_submit(
    4724              :     struct chttpserver *srv, srv_pool_kind k, cthrpool pool, void (*fn)(void *),
    4725              :     void *arg) {
    4726         3445 :   if (__builtin_expect(
    4727         1722 :           pool && cthrpool_try_submit(pool, fn, arg, NULL) == ccol_success, 1))
    4728              :     return true;
    4729            3 :   return srv_submit_retry(srv, k, pool, fn, arg);
    4730              : }
    4731              : 
    4732              : // Decrements srv->in_flight_requests under srv->mutex and wakes every thread in
    4733              : // drain_and_close_all_connections when it reaches zero. Every increment
    4734              : // (conn_start_diverted, conn_dispatch_reject) needs exactly one call. Call it
    4735              : // only once the connection is closed through conn_close or published back to
    4736              : // the idle list; any earlier and the drain can wake, see zero and let
    4737              : // chttpsvr__destroy free srv while this thread is finishing the connection.
    4738         1733 : static void release_in_flight(struct chttpserver *srv) {
    4739         1733 :   ccol__mutex_lock(srv->mutex);
    4740         1733 :   if (--srv->in_flight_requests == 0)
    4741         1518 :     ccol__cond_var_broadcast(srv->requests_done_cv);
    4742         1733 :   ccol__mutex_unlock(srv->mutex);
    4743         1733 : }
    4744              : 
    4745              : #ifdef RUNNING_UNIT_TESTS
    4746              : // Test hook: While it's set, every pause in conn_pause_reg takes the
    4747              : // failed-pause path, and the counter counts the removals that path makes.
    4748              : static _Atomic bool g_force_pause_fail_for_tests = false;
    4749              : static _Atomic size_t g_pause_fallback_count_for_tests = 0;
    4750              : // Test controls: Turn the forced pause failure on or off, and read how many
    4751              : // removals it caused.
    4752            8 : void chttpsvr__force_pause_fail_for_tests(bool force) {
    4753            8 :   atomic_store(&g_force_pause_fail_for_tests, force);
    4754            8 : }
    4755            8 : size_t chttpsvr__pause_fallback_count_for_tests(void) {
    4756            8 :   return atomic_load(&g_pause_fallback_count_for_tests);
    4757              : }
    4758              : #endif
    4759              : 
    4760              : // Pauses the reactor registration of conn while a thread owns the connection,
    4761              : // so no readiness fires meanwhile; the caller owns conn. If the pause fails it
    4762              : // removes the registration and clears conn->reg, and the connection's next wait
    4763              : // (conn_park_arm or the keep-alive tail of task_tail) adds a registration of
    4764              : // its own. Removing a registration that's already gone does nothing, and
    4765              : // removing a live one reclaims it.
    4766         1723 : static void conn_pause_reg(chttpsvr_conn *conn) {
    4767         1723 :   if (!conn->reg) return;
    4768          960 :   bool paused;
    4769              : #ifdef RUNNING_UNIT_TESTS
    4770          960 :   if (atomic_load(&g_force_pause_fail_for_tests))
    4771              :     paused = false;
    4772              :   else
    4773              : #endif
    4774         1904 :     paused =
    4775          952 :         ceventloop_pause(srv_engine_bundler.reactor, conn->reg) == ccol_success;
    4776          952 :   if (!paused) {
    4777            8 :     ceventloop_remove(srv_engine_bundler.reactor, conn->reg);
    4778            8 :     conn->reg = CEVENTLOOP_REG_NULL;
    4779              : #ifdef RUNNING_UNIT_TESTS
    4780            8 :     atomic_fetch_add(&g_pause_fallback_count_for_tests, 1);
    4781              : #endif
    4782              :   }
    4783              : }
    4784              : 
    4785              : #ifdef RUNNING_UNIT_TESTS
    4786              : // Test hook: When set, the next rejection skips reject_pool and takes the
    4787              : // inline answer of conn_reject_via_pool, as when that pool is full. It clears
    4788              : // itself after one use.
    4789              : static _Atomic bool g_force_reject_inline_for_tests = false;
    4790              : // Test control: Arms or disarms the forced inline rejection.
    4791            2 : void chttpsvr__force_reject_inline_for_tests(bool force) {
    4792            2 :   atomic_store(&g_force_reject_inline_for_tests, force);
    4793            2 : }
    4794              : #endif
    4795              : 
    4796              : // Hands conn to reject_pool so its rejection response (status already in
    4797              : // conn->reject_status) is written there, with the middleware, and never on the
    4798              : // calling thread. Both rejection paths use it: The reactor's 404, 405 and 500
    4799              : // through conn_dispatch_reject, and the 503 or 500 of conn_start_diverted. The
    4800              : // caller must already have incremented srv->in_flight_requests.
    4801              : // When reject_pool is gone (teardown), its bounded queue is full or the submit
    4802              : // fails, it answers on the calling thread without middleware; that write never
    4803              : // waits on the peer, so it's safe on the reactor and the sweep. Only then does
    4804              : // it call release_in_flight, after the close; srv is read first because
    4805              : // conn_reject_and_close may free or park conn.
    4806          229 : static void conn_reject_via_pool(chttpsvr_conn *conn) {
    4807          229 :   struct chttpserver *srv = conn->srv;
    4808          229 :   ccol__mutex_lock(srv->mutex);
    4809          229 :   cthrpool reject_pool = srv->reject_pool;
    4810          229 :   ccol__mutex_unlock(srv->mutex);
    4811              : 
    4812          229 :   bool inline_only = false;
    4813              : #ifdef RUNNING_UNIT_TESTS
    4814          229 :   inline_only = atomic_exchange(&g_force_reject_inline_for_tests, false);
    4815              : #endif
    4816          229 :   if (!inline_only &&
    4817            0 :       srv_submit(srv, SRV_POOL_REJECT, reject_pool, reject_task, conn)) {
    4818          228 :     return;
    4819              :   }
    4820              : 
    4821            1 :   conn_reject_and_close(conn, false);
    4822            1 :   release_in_flight(srv);
    4823              : }
    4824              : 
    4825              : // Sends a connection rejected at headers-complete on the reactor thread (404,
    4826              : // 405, 500 and the like) to reject_pool, so a slow-reading client can't stall
    4827              : // the reactor with its rejection. It pauses the registration rather than
    4828              : // removing it, because a parked response or a lingering close re-arms the same
    4829              : // registration with a modify and a resume, which allocate nothing. It marks
    4830              : // conn CONN_ST_DIVERTED, puts it on the diverted list, so a shutdown or restart
    4831              : // can force it to unblock, and counts it in srv->in_flight_requests under
    4832              : // srv->mutex. conn_free takes it off the list again on every close path.
    4833          220 : static void conn_dispatch_reject(chttpsvr_conn *conn) {
    4834          220 :   idle_list_remove(conn);
    4835          220 :   conn_pause_reg(conn);
    4836          220 :   conn->state = CONN_ST_DIVERTED;
    4837          220 :   diverted_list_add(conn);
    4838          220 :   ccol__mutex_lock(conn->srv->mutex);
    4839          220 :   conn->srv->in_flight_requests++;
    4840          220 :   ccol__mutex_unlock(conn->srv->mutex);
    4841          220 :   conn_reject_via_pool(conn);
    4842          220 : }
    4843              : 
    4844              : // Hands a request whose headers are parsed to a worker. The reactor calls it
    4845              : // with the bytes it read past the headers (leftover, in its stack buffer). It
    4846              : // pauses the registration (cheaper than a remove and a re-add on every
    4847              : // keep-alive request), marks conn diverted, puts it on the diverted list and
    4848              : // counts it in srv->in_flight_requests under srv->mutex, where it also reads
    4849              : // the worker pool and the draining flag.
    4850              : // leftover is copied into conn->carry_over before the submit, because the
    4851              : // buffer dies when the callback returns and a worker may start task_worker at
    4852              : // once; writing the fields after the submit would race it and lose or leak the
    4853              : // bytes. carry_over_len is 0 whenever carry_over is NULL. A draining server
    4854              : // answers 503, a failed copy answers 500, and a full worker pool answers 503,
    4855              : // all through conn_reject_via_pool. A request with a divert gate goes to
    4856              : // conn_divert_gate first (streaming pool or body memory reservation).
    4857         1062 : static void conn_start_diverted(chttpsvr_conn *conn, const char *leftover,
    4858              :                                 size_t leftover_len) {
    4859         1062 :   idle_list_remove(conn);
    4860         1062 :   conn_pause_reg(conn);
    4861         1062 :   conn->state = CONN_ST_DIVERTED;
    4862         1062 :   diverted_list_add(conn);
    4863              : 
    4864         1062 :   ccol__mutex_lock(conn->srv->mutex);
    4865         1062 :   conn->srv->in_flight_requests++;
    4866         1062 :   cthrpool pool = conn->srv->worker_pool;
    4867         1062 :   bool draining = srv_draining(conn->srv);
    4868         1062 :   ccol__mutex_unlock(conn->srv->mutex);
    4869              : 
    4870         1062 :   if (__builtin_expect(draining, 0)) {
    4871            0 :     conn->req_rejected = true;
    4872            0 :     conn->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    4873            0 :     conn_reject_via_pool(conn);
    4874            0 :     return;
    4875              :   }
    4876              : 
    4877         1062 :   char *carry = NULL;
    4878         1062 :   bool carry_alloc_failed = false;
    4879         1062 :   if (leftover_len > 0) {
    4880          171 :     carry = (char *)ccol__mem_alloc(conn->m_procs, leftover_len);
    4881          171 :     if (carry)
    4882          170 :       memcpy(carry, leftover, leftover_len);
    4883              :     else
    4884              :       carry_alloc_failed = true;
    4885              :   }
    4886         1062 :   conn->carry_over = carry;
    4887         1062 :   conn->carry_over_len = carry ? leftover_len : 0;
    4888              : 
    4889         1062 :   if (carry_alloc_failed) {
    4890            1 :     conn->req_rejected = true;
    4891            1 :     conn->reject_status = CHTTP_STATUS_INTERNAL_ERROR;
    4892            1 :     conn_reject_via_pool(conn);
    4893            1 :     return;
    4894              :   }
    4895              : 
    4896         1268 :   if (__builtin_expect(conn->divert_gate > leftover_len, 0) &&
    4897          207 :       conn_divert_gate(conn))
    4898              :     return;
    4899              : 
    4900              : #ifdef RUNNING_UNIT_TESTS
    4901          961 :   divert_submit_hook_wait_if_armed();
    4902              : #endif
    4903          963 :   if (!srv_submit(conn->srv, SRV_POOL_WORKER, pool, task_worker, conn)) {
    4904            1 :     ccol__mem_free(conn->m_procs, carry);
    4905            1 :     conn->carry_over = NULL;
    4906            1 :     conn->carry_over_len = 0;
    4907            1 :     conn->req_rejected = true;
    4908            1 :     conn->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    4909              : 
    4910            1 :     conn_reject_via_pool(conn);
    4911            1 :     return;
    4912              :   }
    4913              : #ifdef RUNNING_UNIT_TESTS
    4914          960 :   atomic_fetch_add(&chttpsvr__worker_submits_for_tests, 1);
    4915              : #endif
    4916              : }
    4917              : 
    4918              : // Fills conn->decoded_path for a request rejected before routing set it, so a
    4919              : // middleware running for the rejection can read the target through
    4920              : // chttpsvr_req_path. A target with malformed percent-encoding is stored as it
    4921              : // came in, since that's often why no route matched and an access log should
    4922              : // show it. An allocation failure leaves the field NULL.
    4923           89 : static void conn_set_rejected_decoded_path(chttpsvr_conn *conn) {
    4924           89 :   if (conn->decoded_path || !conn->path) return;
    4925           89 :   size_t plen = strlen(conn->path);
    4926           89 :   char *dp = (char *)ccol__mem_alloc(conn->m_procs, plen + 1);
    4927           89 :   if (!dp) return;
    4928           88 :   ssize_t dlen = decode_path_unsafe(dp, conn->path);
    4929           88 :   if (dlen >= 0)
    4930           79 :     dp[(size_t)dlen] = '\0';
    4931              :   else
    4932            9 :     memcpy(dp, conn->path, plen + 1);
    4933           88 :   conn->decoded_path = dp;
    4934              : }
    4935              : 
    4936              : // Writes the Allow header value for the method mask into out (at least 64
    4937              : // bytes), in the order GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, separated
    4938              : // by ", ". The 405 response of conn_reject_and_close uses it; the longest value
    4939              : // is 44 bytes with the terminator.
    4940           10 : static void format_allow_header(unsigned mask, char *out) {
    4941           10 :   static const chttp_method order[] = {CHTTP_GET,    CHTTP_HEAD,   CHTTP_POST,
    4942              :                                        CHTTP_PUT,    CHTTP_DELETE, CHTTP_PATCH,
    4943              :                                        CHTTP_OPTIONS};
    4944           10 :   size_t n = 0;
    4945           80 :   for (size_t i = 0; i < sizeof(order) / sizeof(order[0]); i++) {
    4946           70 :     if (!(mask & (1u << order[i]))) continue;
    4947           19 :     const char *name = chttp_method_str(order[i]);
    4948           19 :     size_t len = strlen(name);
    4949           19 :     if (n) {
    4950            9 :       out[n++] = ',';
    4951            9 :       out[n++] = ' ';
    4952              :     }
    4953           19 :     memcpy(out + n, name, len);
    4954           19 :     n += len;
    4955              :   }
    4956           10 :   out[n] = '\0';
    4957           10 : }
    4958              : 
    4959              : // Writes the rejection response for conn->reject_status and ends the
    4960              : // connection. A 503 gets Retry-After and a 405 gets Allow. When run_middleware
    4961              : // is true (only from reject_task on a reject_pool thread, whose fixed size
    4962              : // bounds how much application code a flood of rejections runs) and the status
    4963              : // takes a chain, the snapshot middleware runs with no route and no body,
    4964              : // provided the decoded path could be allocated; otherwise the response goes out
    4965              : // bare.
    4966              : // The write is non-blocking with a duration ceiling. A full socket parks the
    4967              : // connection as a write park, drops the request state and leaves the diverted
    4968              : // list; if parking fails the connection closes. After a complete response it
    4969              : // lingers when request bytes may remain unread, so the kernel's reset can't
    4970              : // wipe out the response in the client, and closes otherwise.
    4971          230 : static void conn_reject_and_close(chttpsvr_conn *conn, bool run_middleware) {
    4972          230 :   chttpsvr_resp *resp = &conn->resp;
    4973          230 :   resp->status_code = conn->reject_status;
    4974          230 :   if (conn->reject_status == CHTTP_STATUS_SERVICE_UNAVAILABLE)
    4975           12 :     (void)chttpsvr_resp_set_header(resp, "retry-after",
    4976              :                                    CHTTPSVR_RETRY_AFTER_SECONDS);
    4977          230 :   if (conn->reject_status == CHTTP_STATUS_METHOD_NOT_ALLOWED &&
    4978           10 :       conn->allowed_methods) {
    4979           10 :     char allow[64];
    4980           10 :     format_allow_header(conn->allowed_methods, allow);
    4981           10 :     (void)chttpsvr_resp_set_header(resp, "allow", allow);
    4982              :   }
    4983          230 :   bool wants_middleware = run_middleware && conn->dispatch.mw_count > 0 &&
    4984           89 :                           reject_status_runs_middleware(conn->reject_status);
    4985           89 :   if (wants_middleware) conn_set_rejected_decoded_path(conn);
    4986           89 :   if (wants_middleware && conn->decoded_path) {
    4987           88 :     conn->dispatch.route = NULL;
    4988           88 :     conn->dispatch.mw_idx = 0;
    4989           88 :     chttpsvr_req req;
    4990           88 :     memset(&req, 0, sizeof(req));
    4991           88 :     req.conn = conn;
    4992           88 :     req.stream = NULL;
    4993           88 :     req.param_names = NULL;
    4994           88 :     req.m_procs = conn->m_procs;
    4995           88 :     chttpsvr_next(&req, resp);
    4996           88 :     destroy_req_scratch(&req);
    4997              :   }
    4998          230 :   chttp1_stream stream;
    4999          230 :   if (conn->tls)
    5000            1 :     chttp1_stream_prepare_tls(&stream, conn->fd, conn->tls, NULL, 0,
    5001              :                               conn->m_procs);
    5002              :   else
    5003          229 :     chttp1_stream_prepare(&stream, conn->fd, NULL, 0, conn->m_procs);
    5004          230 :   stream.fd_nonblocking = true;
    5005          230 :   stream.write_nonblocking = true;
    5006          230 :   bool sent = send_response(&stream, resp, false, 0, conn->method == CHTTP_HEAD,
    5007              :                             conn, true);
    5008          230 :   chttp1_stream_release(&stream);
    5009          230 :   if (!sent && conn->wp_active) {
    5010            6 :     conn->wp_reject = true;
    5011            6 :     conn_drop_request_state(conn);
    5012            6 :     diverted_list_remove(conn);
    5013            6 :     if (!conn_park_arm(conn, CONN_PARK_WRITE)) {
    5014            0 :       conn->wp_reject = false;
    5015            0 :       conn_end_parked_write(conn);
    5016            0 :       conn_close(conn);
    5017              :     }
    5018            6 :     return;
    5019              :   }
    5020          223 :   if (sent && conn_request_bytes_may_remain(conn))
    5021          113 :     conn_linger(conn);
    5022              :   else
    5023          111 :     conn_close(conn);
    5024              : }
    5025              : 
    5026              : #ifdef RUNNING_UNIT_TESTS
    5027              : // Test counter of rejections that ran on a reject_pool thread (the inline
    5028              : // fallback adds nothing). It's process-wide, so a test reads the difference
    5029              : // across its own window.
    5030              : static _Atomic size_t g_reject_task_run_count_for_tests = 0;
    5031              : 
    5032              : // Test hook: Makes the first stream prepare of task_worker count as failed, so
    5033              : // a test reaches the body_unavailable fallback that a real allocation failure
    5034              : // there takes. A sized allocator failure can't reach it, because
    5035              : // conn_start_diverted makes an allocation of the same size first.
    5036              : static _Atomic bool g_force_stream_prepare_fail_for_tests = false;
    5037              : // Test control: Arms or disarms the forced stream prepare failure.
    5038            2 : void chttpsvr__force_stream_prepare_fail_for_tests(bool force) {
    5039            2 :   atomic_store(&g_force_stream_prepare_fail_for_tests, force);
    5040            2 : }
    5041              : 
    5042              : // Test hook: Once armed, chttpsvr_start blocks right after it has the engine
    5043              : // reference and registered with servers_bundler, before any more reactor work,
    5044              : // so a test can land a concurrent chttpsvr_engine_stop in that exact window. It
    5045              : // fires once per arm. This and the other parking hooks below share one shape:
    5046              : // armed, entered and go under a mutex and a condition variable, set up lazily
    5047              : // through the once flag.
    5048              : static struct {
    5049              :   ccol__mutex mutex;
    5050              :   ccol__cond_var cv;
    5051              :   ccol__once_flag once;
    5052              :   bool armed;
    5053              :   bool entered;
    5054              :   bool go;
    5055              : } g_start_race_hook = {0};
    5056              : 
    5057              : // Initialises the mutex and the condition variable of g_start_race_hook; a
    5058              : // failure is fatal.
    5059            6 : static void start_race_hook_init_globals(void) {
    5060            6 :   if (ccol__mutex_init(g_start_race_hook.mutex) != 0)
    5061            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5062            6 :   if (ccol__cond_var_init(g_start_race_hook.cv) != 0)
    5063            0 :     ccol__fatal_err(
    5064              :         "chttpsvr test hook: failed to initialize condition variable");
    5065            6 : }
    5066              : 
    5067              : // Test controls of g_start_race_hook: Arm it, wait until a caller is parked in
    5068              : // it, and release the caller.
    5069            2 : void chttpsvr__arm_start_race_hook_for_tests(void) {
    5070            2 :   ccol__call_once(g_start_race_hook.once, start_race_hook_init_globals);
    5071            2 :   ccol__mutex_lock(g_start_race_hook.mutex);
    5072            2 :   g_start_race_hook.armed = true;
    5073            2 :   g_start_race_hook.entered = false;
    5074            2 :   g_start_race_hook.go = false;
    5075            2 :   ccol__mutex_unlock(g_start_race_hook.mutex);
    5076            2 : }
    5077              : 
    5078            2 : void chttpsvr__wait_start_race_hook_entered_for_tests(void) {
    5079            2 :   ccol__call_once(g_start_race_hook.once, start_race_hook_init_globals);
    5080            2 :   ccol__mutex_lock(g_start_race_hook.mutex);
    5081            4 :   while (!g_start_race_hook.entered)
    5082            2 :     ccol__cond_var_wait(g_start_race_hook.cv, g_start_race_hook.mutex);
    5083            2 :   ccol__mutex_unlock(g_start_race_hook.mutex);
    5084            2 : }
    5085              : 
    5086            2 : void chttpsvr__release_start_race_hook_for_tests(void) {
    5087            2 :   ccol__call_once(g_start_race_hook.once, start_race_hook_init_globals);
    5088            2 :   ccol__mutex_lock(g_start_race_hook.mutex);
    5089            2 :   g_start_race_hook.go = true;
    5090            2 :   ccol__cond_var_broadcast(g_start_race_hook.cv);
    5091            2 :   ccol__mutex_unlock(g_start_race_hook.mutex);
    5092            2 : }
    5093              : 
    5094              : // Stops the calling thread at this race point for a test when the hook is
    5095              : // armed. It disarms the hook, signals that it got there and waits until the
    5096              : // test releases it. chttpsvr_start calls it, so a test can run its race in a
    5097              : // fixed order.
    5098          313 : static void start_race_hook_wait_if_armed(void) {
    5099          313 :   ccol__call_once(g_start_race_hook.once, start_race_hook_init_globals);
    5100          313 :   ccol__mutex_lock(g_start_race_hook.mutex);
    5101          313 :   if (!g_start_race_hook.armed) {
    5102          311 :     ccol__mutex_unlock(g_start_race_hook.mutex);
    5103          311 :     return;
    5104              :   }
    5105            2 :   g_start_race_hook.armed = false;
    5106            2 :   g_start_race_hook.entered = true;
    5107            2 :   ccol__cond_var_broadcast(g_start_race_hook.cv);
    5108            4 :   while (!g_start_race_hook.go)
    5109            2 :     ccol__cond_var_wait(g_start_race_hook.cv, g_start_race_hook.mutex);
    5110            2 :   ccol__mutex_unlock(g_start_race_hook.mutex);
    5111              : }
    5112              : 
    5113              : // Test hook: Once armed, chttpsvr_start blocks after it set
    5114              : // contributed_to_engine and before engine_acquire, the window where
    5115              : // engine_acquire can see the engine stopping and return without waiting. A test
    5116              : // uses it to exercise the retry of the "currently stopping" branch every time.
    5117              : static struct {
    5118              :   ccol__mutex mutex;
    5119              :   ccol__cond_var cv;
    5120              :   ccol__once_flag once;
    5121              :   bool armed;
    5122              :   bool entered;
    5123              :   bool go;
    5124              : } g_engine_stopping_race_hook = {0};
    5125              : 
    5126              : // Initialises the mutex and the condition variable of
    5127              : // g_engine_stopping_race_hook; a failure is fatal.
    5128            6 : static void engine_stopping_race_hook_init_globals(void) {
    5129            6 :   if (ccol__mutex_init(g_engine_stopping_race_hook.mutex) != 0)
    5130            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5131            6 :   if (ccol__cond_var_init(g_engine_stopping_race_hook.cv) != 0)
    5132            0 :     ccol__fatal_err(
    5133              :         "chttpsvr test hook: failed to initialize condition variable");
    5134            6 : }
    5135              : 
    5136              : // Test controls of g_engine_stopping_race_hook: Arm it, wait until a caller is
    5137              : // parked in it, and release the caller.
    5138            3 : void chttpsvr__arm_engine_stopping_race_hook_for_tests(void) {
    5139            3 :   ccol__call_once(g_engine_stopping_race_hook.once,
    5140              :                   engine_stopping_race_hook_init_globals);
    5141            3 :   ccol__mutex_lock(g_engine_stopping_race_hook.mutex);
    5142            3 :   g_engine_stopping_race_hook.armed = true;
    5143            3 :   g_engine_stopping_race_hook.entered = false;
    5144            3 :   g_engine_stopping_race_hook.go = false;
    5145            3 :   ccol__mutex_unlock(g_engine_stopping_race_hook.mutex);
    5146            3 : }
    5147              : 
    5148            3 : void chttpsvr__wait_engine_stopping_race_hook_entered_for_tests(void) {
    5149            3 :   ccol__call_once(g_engine_stopping_race_hook.once,
    5150              :                   engine_stopping_race_hook_init_globals);
    5151            3 :   ccol__mutex_lock(g_engine_stopping_race_hook.mutex);
    5152            6 :   while (!g_engine_stopping_race_hook.entered)
    5153            3 :     ccol__cond_var_wait(g_engine_stopping_race_hook.cv,
    5154              :                         g_engine_stopping_race_hook.mutex);
    5155            3 :   ccol__mutex_unlock(g_engine_stopping_race_hook.mutex);
    5156            3 : }
    5157              : 
    5158            3 : void chttpsvr__release_engine_stopping_race_hook_for_tests(void) {
    5159            3 :   ccol__call_once(g_engine_stopping_race_hook.once,
    5160              :                   engine_stopping_race_hook_init_globals);
    5161            3 :   ccol__mutex_lock(g_engine_stopping_race_hook.mutex);
    5162            3 :   g_engine_stopping_race_hook.go = true;
    5163            3 :   ccol__cond_var_broadcast(g_engine_stopping_race_hook.cv);
    5164            3 :   ccol__mutex_unlock(g_engine_stopping_race_hook.mutex);
    5165            3 : }
    5166              : 
    5167              : // Stops the calling thread at this race point for a test when the hook is
    5168              : // armed. It disarms the hook, signals that it got there and waits until the
    5169              : // test releases it. chttpsvr_start calls it, so a test can run its race in a
    5170              : // fixed order.
    5171          298 : static void engine_stopping_race_hook_wait_if_armed(void) {
    5172          298 :   ccol__call_once(g_engine_stopping_race_hook.once,
    5173              :                   engine_stopping_race_hook_init_globals);
    5174          298 :   ccol__mutex_lock(g_engine_stopping_race_hook.mutex);
    5175          298 :   if (!g_engine_stopping_race_hook.armed) {
    5176          295 :     ccol__mutex_unlock(g_engine_stopping_race_hook.mutex);
    5177          295 :     return;
    5178              :   }
    5179            3 :   g_engine_stopping_race_hook.armed = false;
    5180            3 :   g_engine_stopping_race_hook.entered = true;
    5181            3 :   ccol__cond_var_broadcast(g_engine_stopping_race_hook.cv);
    5182            6 :   while (!g_engine_stopping_race_hook.go)
    5183            3 :     ccol__cond_var_wait(g_engine_stopping_race_hook.cv,
    5184              :                         g_engine_stopping_race_hook.mutex);
    5185            3 :   ccol__mutex_unlock(g_engine_stopping_race_hook.mutex);
    5186              : }
    5187              : 
    5188              : // Test hook: Once armed, chttpsvr_start blocks right after chttpsvr_resolve
    5189              : // succeeded, so its resolve pin is live, and before any other check. A test
    5190              : // uses it to place that pin ahead of the pending_resolve_count wait of a
    5191              : // concurrent quiesce_server_once, which would deadlock if chttpsvr_start then
    5192              : // waited for the quiesce while holding the pin.
    5193              : static struct {
    5194              :   ccol__mutex mutex;
    5195              :   ccol__cond_var cv;
    5196              :   ccol__once_flag once;
    5197              :   bool armed;
    5198              :   bool entered;
    5199              :   bool go;
    5200              : } g_start_resolve_race_hook = {0};
    5201              : 
    5202              : // Initialises the mutex and the condition variable of
    5203              : // g_start_resolve_race_hook; a failure is fatal.
    5204            6 : static void start_resolve_race_hook_init_globals(void) {
    5205            6 :   if (ccol__mutex_init(g_start_resolve_race_hook.mutex) != 0)
    5206            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5207            6 :   if (ccol__cond_var_init(g_start_resolve_race_hook.cv) != 0)
    5208            0 :     ccol__fatal_err(
    5209              :         "chttpsvr test hook: failed to initialize condition variable");
    5210            6 : }
    5211              : 
    5212              : // Test controls of g_start_resolve_race_hook: Arm it, wait until a caller is
    5213              : // parked in it, and release the caller.
    5214            2 : void chttpsvr__arm_start_resolve_race_hook_for_tests(void) {
    5215            2 :   ccol__call_once(g_start_resolve_race_hook.once,
    5216              :                   start_resolve_race_hook_init_globals);
    5217            2 :   ccol__mutex_lock(g_start_resolve_race_hook.mutex);
    5218            2 :   g_start_resolve_race_hook.armed = true;
    5219            2 :   g_start_resolve_race_hook.entered = false;
    5220            2 :   g_start_resolve_race_hook.go = false;
    5221            2 :   ccol__mutex_unlock(g_start_resolve_race_hook.mutex);
    5222            2 : }
    5223              : 
    5224            2 : void chttpsvr__wait_start_resolve_race_hook_entered_for_tests(void) {
    5225            2 :   ccol__call_once(g_start_resolve_race_hook.once,
    5226              :                   start_resolve_race_hook_init_globals);
    5227            2 :   ccol__mutex_lock(g_start_resolve_race_hook.mutex);
    5228            4 :   while (!g_start_resolve_race_hook.entered)
    5229            2 :     ccol__cond_var_wait(g_start_resolve_race_hook.cv,
    5230              :                         g_start_resolve_race_hook.mutex);
    5231            2 :   ccol__mutex_unlock(g_start_resolve_race_hook.mutex);
    5232            2 : }
    5233              : 
    5234            2 : void chttpsvr__release_start_resolve_race_hook_for_tests(void) {
    5235            2 :   ccol__call_once(g_start_resolve_race_hook.once,
    5236              :                   start_resolve_race_hook_init_globals);
    5237            2 :   ccol__mutex_lock(g_start_resolve_race_hook.mutex);
    5238            2 :   g_start_resolve_race_hook.go = true;
    5239            2 :   ccol__cond_var_broadcast(g_start_resolve_race_hook.cv);
    5240            2 :   ccol__mutex_unlock(g_start_resolve_race_hook.mutex);
    5241            2 : }
    5242              : 
    5243              : // Stops the calling thread at this race point for a test when the hook is
    5244              : // armed. It disarms the hook, signals that it got there and waits until the
    5245              : // test releases it. chttpsvr_start calls it, so a test can run its race in a
    5246              : // fixed order.
    5247          331 : static void start_resolve_race_hook_wait_if_armed(void) {
    5248          331 :   ccol__call_once(g_start_resolve_race_hook.once,
    5249              :                   start_resolve_race_hook_init_globals);
    5250          331 :   ccol__mutex_lock(g_start_resolve_race_hook.mutex);
    5251          331 :   if (!g_start_resolve_race_hook.armed) {
    5252          329 :     ccol__mutex_unlock(g_start_resolve_race_hook.mutex);
    5253          329 :     return;
    5254              :   }
    5255            2 :   g_start_resolve_race_hook.armed = false;
    5256            2 :   g_start_resolve_race_hook.entered = true;
    5257            2 :   ccol__cond_var_broadcast(g_start_resolve_race_hook.cv);
    5258            4 :   while (!g_start_resolve_race_hook.go)
    5259            2 :     ccol__cond_var_wait(g_start_resolve_race_hook.cv,
    5260              :                         g_start_resolve_race_hook.mutex);
    5261            2 :   ccol__mutex_unlock(g_start_resolve_race_hook.mutex);
    5262              : }
    5263              : 
    5264              : // Test hook: Once armed, chttpsvr_stop_internal blocks after it entered
    5265              : // CHTTPSVR_LC_STOPPING and unlocked raw->mutex, and before it removes and
    5266              : // closes the old listener, so a test can land a concurrent chttpsvr_start in
    5267              : // the window that state guards.
    5268              : static struct {
    5269              :   ccol__mutex mutex;
    5270              :   ccol__cond_var cv;
    5271              :   ccol__once_flag once;
    5272              :   bool armed;
    5273              :   bool entered;
    5274              :   bool go;
    5275              : } g_stop_race_hook = {0};
    5276              : 
    5277              : // Initialises the mutex and the condition variable of g_stop_race_hook; a
    5278              : // failure is fatal.
    5279            6 : static void stop_race_hook_init_globals(void) {
    5280            6 :   if (ccol__mutex_init(g_stop_race_hook.mutex) != 0)
    5281            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5282            6 :   if (ccol__cond_var_init(g_stop_race_hook.cv) != 0)
    5283            0 :     ccol__fatal_err(
    5284              :         "chttpsvr test hook: failed to initialize condition variable");
    5285            6 : }
    5286              : 
    5287              : // Test controls of g_stop_race_hook: Arm it, wait until a caller is parked in
    5288              : // it, and release the caller.
    5289            3 : void chttpsvr__arm_stop_race_hook_for_tests(void) {
    5290            3 :   ccol__call_once(g_stop_race_hook.once, stop_race_hook_init_globals);
    5291            3 :   ccol__mutex_lock(g_stop_race_hook.mutex);
    5292            3 :   g_stop_race_hook.armed = true;
    5293            3 :   g_stop_race_hook.entered = false;
    5294            3 :   g_stop_race_hook.go = false;
    5295            3 :   ccol__mutex_unlock(g_stop_race_hook.mutex);
    5296            3 : }
    5297              : 
    5298            3 : void chttpsvr__wait_stop_race_hook_entered_for_tests(void) {
    5299            3 :   ccol__call_once(g_stop_race_hook.once, stop_race_hook_init_globals);
    5300            3 :   ccol__mutex_lock(g_stop_race_hook.mutex);
    5301            6 :   while (!g_stop_race_hook.entered)
    5302            3 :     ccol__cond_var_wait(g_stop_race_hook.cv, g_stop_race_hook.mutex);
    5303            3 :   ccol__mutex_unlock(g_stop_race_hook.mutex);
    5304            3 : }
    5305              : 
    5306            3 : void chttpsvr__release_stop_race_hook_for_tests(void) {
    5307            3 :   ccol__call_once(g_stop_race_hook.once, stop_race_hook_init_globals);
    5308            3 :   ccol__mutex_lock(g_stop_race_hook.mutex);
    5309            3 :   g_stop_race_hook.go = true;
    5310            3 :   ccol__cond_var_broadcast(g_stop_race_hook.cv);
    5311            3 :   ccol__mutex_unlock(g_stop_race_hook.mutex);
    5312            3 : }
    5313              : 
    5314              : // Stops the calling thread at this race point for a test when the hook is
    5315              : // armed. It disarms the hook, signals that it got there and waits until the
    5316              : // test releases it. chttpsvr_stop_internal calls it, so a test can run its race
    5317              : // in a fixed order.
    5318          300 : static void stop_race_hook_wait_if_armed(void) {
    5319          300 :   ccol__call_once(g_stop_race_hook.once, stop_race_hook_init_globals);
    5320          300 :   ccol__mutex_lock(g_stop_race_hook.mutex);
    5321          300 :   if (!g_stop_race_hook.armed) {
    5322          297 :     ccol__mutex_unlock(g_stop_race_hook.mutex);
    5323          297 :     return;
    5324              :   }
    5325            3 :   g_stop_race_hook.armed = false;
    5326            3 :   g_stop_race_hook.entered = true;
    5327            3 :   ccol__cond_var_broadcast(g_stop_race_hook.cv);
    5328            6 :   while (!g_stop_race_hook.go)
    5329            3 :     ccol__cond_var_wait(g_stop_race_hook.cv, g_stop_race_hook.mutex);
    5330            3 :   ccol__mutex_unlock(g_stop_race_hook.mutex);
    5331              : }
    5332              : 
    5333              : // Test signal for the CHTTPSVR_LC_STOPPING wait of chttpsvr_start: It tells a
    5334              : // test that the call reached its wait, and never blocks. A parking hook would
    5335              : // be unsafe there, because the caller holds raw->mutex, which
    5336              : // chttpsvr_stop_internal needs to leave that state, so a slow release would
    5337              : // wedge both sides of the race under test.
    5338              : static struct {
    5339              :   ccol__mutex mutex;
    5340              :   ccol__cond_var cv;
    5341              :   ccol__once_flag once;
    5342              :   bool armed;
    5343              :   bool entered;
    5344              : } g_start_stopping_wait_signal = {0};
    5345              : 
    5346              : // Initialises the mutex and the condition variable of
    5347              : // g_start_stopping_wait_signal; a failure is fatal.
    5348            1 : static void start_stopping_wait_signal_init_globals(void) {
    5349            1 :   if (ccol__mutex_init(g_start_stopping_wait_signal.mutex) != 0)
    5350            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5351            1 :   if (ccol__cond_var_init(g_start_stopping_wait_signal.cv) != 0)
    5352            0 :     ccol__fatal_err(
    5353              :         "chttpsvr test hook: failed to initialize condition variable");
    5354            1 : }
    5355              : 
    5356              : // Test controls of g_start_stopping_wait_signal: Arm it, and wait until
    5357              : // chttpsvr_start has fired it.
    5358            2 : void chttpsvr__arm_start_stopping_wait_signal_for_tests(void) {
    5359            2 :   ccol__call_once(g_start_stopping_wait_signal.once,
    5360              :                   start_stopping_wait_signal_init_globals);
    5361            2 :   ccol__mutex_lock(g_start_stopping_wait_signal.mutex);
    5362            2 :   g_start_stopping_wait_signal.armed = true;
    5363            2 :   g_start_stopping_wait_signal.entered = false;
    5364            2 :   ccol__mutex_unlock(g_start_stopping_wait_signal.mutex);
    5365            2 : }
    5366              : 
    5367            2 : void chttpsvr__wait_start_stopping_wait_signal_entered_for_tests(void) {
    5368            2 :   ccol__call_once(g_start_stopping_wait_signal.once,
    5369              :                   start_stopping_wait_signal_init_globals);
    5370            2 :   ccol__mutex_lock(g_start_stopping_wait_signal.mutex);
    5371            4 :   while (!g_start_stopping_wait_signal.entered)
    5372            2 :     ccol__cond_var_wait(g_start_stopping_wait_signal.cv,
    5373              :                         g_start_stopping_wait_signal.mutex);
    5374            2 :   ccol__mutex_unlock(g_start_stopping_wait_signal.mutex);
    5375            2 : }
    5376              : 
    5377              : // Fires the test signal of this point when it is armed. It disarms the signal,
    5378              : // marks it entered and wakes the waiting test, without blocking. chttpsvr_start
    5379              : // calls it, so a test knows the thread got there.
    5380            2 : static void start_stopping_wait_signal_fire_if_armed(void) {
    5381            2 :   ccol__call_once(g_start_stopping_wait_signal.once,
    5382              :                   start_stopping_wait_signal_init_globals);
    5383            2 :   ccol__mutex_lock(g_start_stopping_wait_signal.mutex);
    5384            2 :   if (g_start_stopping_wait_signal.armed) {
    5385            2 :     g_start_stopping_wait_signal.armed = false;
    5386            2 :     g_start_stopping_wait_signal.entered = true;
    5387            2 :     ccol__cond_var_broadcast(g_start_stopping_wait_signal.cv);
    5388              :   }
    5389            2 :   ccol__mutex_unlock(g_start_stopping_wait_signal.mutex);
    5390            2 : }
    5391              : 
    5392              : // Test hook: Once armed, engine_force_stop_quiesce_all blocks after it pinned
    5393              : // the first registered server through servers_bundler_pins and unlocked
    5394              : // servers_bundler.mutex, and before quiesce_server_once. A test lands a
    5395              : // concurrent chttpsvr_destroy on that server there, where only the pin keeps
    5396              : // the server alive.
    5397              : static struct {
    5398              :   ccol__mutex mutex;
    5399              :   ccol__cond_var cv;
    5400              :   ccol__once_flag once;
    5401              :   bool armed;
    5402              :   bool entered;
    5403              :   bool go;
    5404              : } g_reaper_race_hook = {0};
    5405              : 
    5406              : // Initialises the mutex and the condition variable of g_reaper_race_hook; a
    5407              : // failure is fatal.
    5408            1 : static void reaper_race_hook_init_globals(void) {
    5409            1 :   if (ccol__mutex_init(g_reaper_race_hook.mutex) != 0)
    5410            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5411            1 :   if (ccol__cond_var_init(g_reaper_race_hook.cv) != 0)
    5412            0 :     ccol__fatal_err(
    5413              :         "chttpsvr test hook: failed to initialize condition variable");
    5414            1 : }
    5415              : 
    5416              : // Test controls of g_reaper_race_hook: Arm it, wait until a caller is parked in
    5417              : // it, and release the caller.
    5418            2 : void chttpsvr__arm_reaper_race_hook_for_tests(void) {
    5419            2 :   ccol__call_once(g_reaper_race_hook.once, reaper_race_hook_init_globals);
    5420            2 :   ccol__mutex_lock(g_reaper_race_hook.mutex);
    5421            2 :   g_reaper_race_hook.armed = true;
    5422            2 :   g_reaper_race_hook.entered = false;
    5423            2 :   g_reaper_race_hook.go = false;
    5424            2 :   ccol__mutex_unlock(g_reaper_race_hook.mutex);
    5425            2 : }
    5426              : 
    5427            2 : void chttpsvr__wait_reaper_race_hook_entered_for_tests(void) {
    5428            2 :   ccol__call_once(g_reaper_race_hook.once, reaper_race_hook_init_globals);
    5429            2 :   ccol__mutex_lock(g_reaper_race_hook.mutex);
    5430            4 :   while (!g_reaper_race_hook.entered)
    5431            2 :     ccol__cond_var_wait(g_reaper_race_hook.cv, g_reaper_race_hook.mutex);
    5432            2 :   ccol__mutex_unlock(g_reaper_race_hook.mutex);
    5433            2 : }
    5434              : 
    5435            2 : void chttpsvr__release_reaper_race_hook_for_tests(void) {
    5436            2 :   ccol__call_once(g_reaper_race_hook.once, reaper_race_hook_init_globals);
    5437            2 :   ccol__mutex_lock(g_reaper_race_hook.mutex);
    5438            2 :   g_reaper_race_hook.go = true;
    5439            2 :   ccol__cond_var_broadcast(g_reaper_race_hook.cv);
    5440            2 :   ccol__mutex_unlock(g_reaper_race_hook.mutex);
    5441            2 : }
    5442              : 
    5443              : // Stops the calling thread at this race point for a test when the hook is
    5444              : // armed. It disarms the hook, signals that it got there and waits until the
    5445              : // test releases it. engine_force_stop_quiesce_all calls it, so a test can run
    5446              : // its race in a fixed order.
    5447           25 : static void reaper_race_hook_wait_if_armed(void) {
    5448           25 :   ccol__call_once(g_reaper_race_hook.once, reaper_race_hook_init_globals);
    5449           25 :   ccol__mutex_lock(g_reaper_race_hook.mutex);
    5450           25 :   if (!g_reaper_race_hook.armed) {
    5451           23 :     ccol__mutex_unlock(g_reaper_race_hook.mutex);
    5452           23 :     return;
    5453              :   }
    5454            2 :   g_reaper_race_hook.armed = false;
    5455            2 :   g_reaper_race_hook.entered = true;
    5456            2 :   ccol__cond_var_broadcast(g_reaper_race_hook.cv);
    5457            4 :   while (!g_reaper_race_hook.go)
    5458            2 :     ccol__cond_var_wait(g_reaper_race_hook.cv, g_reaper_race_hook.mutex);
    5459            2 :   ccol__mutex_unlock(g_reaper_race_hook.mutex);
    5460              : }
    5461              : 
    5462              : // Test hook: Once armed, quiesce_server_once blocks after it won the quiesce
    5463              : // (CHTTPSVR_QS_QUIESCING, pins drained, srv->mutex unlocked) and before any
    5464              : // teardown work. A test forks there to exercise the child-side fixup of
    5465              : // chttpsvr_atfork_release_impl for a server in that state.
    5466              : static struct {
    5467              :   ccol__mutex mutex;
    5468              :   ccol__cond_var cv;
    5469              :   ccol__once_flag once;
    5470              :   bool armed;
    5471              :   bool entered;
    5472              :   bool go;
    5473              : } g_quiesce_teardown_race_hook = {0};
    5474              : 
    5475              : // Initialises the mutex and the condition variable of
    5476              : // g_quiesce_teardown_race_hook; a failure is fatal.
    5477            6 : static void quiesce_teardown_race_hook_init_globals(void) {
    5478            6 :   if (ccol__mutex_init(g_quiesce_teardown_race_hook.mutex) != 0)
    5479            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5480            6 :   if (ccol__cond_var_init(g_quiesce_teardown_race_hook.cv) != 0)
    5481            0 :     ccol__fatal_err(
    5482              :         "chttpsvr test hook: failed to initialize condition variable");
    5483            6 : }
    5484              : 
    5485              : // Test controls of g_quiesce_teardown_race_hook: Arm it, wait until a caller is
    5486              : // parked in it, and release the caller.
    5487            5 : void chttpsvr__arm_quiesce_teardown_race_hook_for_tests(void) {
    5488            5 :   ccol__call_once(g_quiesce_teardown_race_hook.once,
    5489              :                   quiesce_teardown_race_hook_init_globals);
    5490            5 :   ccol__mutex_lock(g_quiesce_teardown_race_hook.mutex);
    5491            5 :   g_quiesce_teardown_race_hook.armed = true;
    5492            5 :   g_quiesce_teardown_race_hook.entered = false;
    5493            5 :   g_quiesce_teardown_race_hook.go = false;
    5494            5 :   ccol__mutex_unlock(g_quiesce_teardown_race_hook.mutex);
    5495            5 : }
    5496              : 
    5497            5 : void chttpsvr__wait_quiesce_teardown_race_hook_entered_for_tests(void) {
    5498            5 :   ccol__call_once(g_quiesce_teardown_race_hook.once,
    5499              :                   quiesce_teardown_race_hook_init_globals);
    5500            5 :   ccol__mutex_lock(g_quiesce_teardown_race_hook.mutex);
    5501           10 :   while (!g_quiesce_teardown_race_hook.entered)
    5502            5 :     ccol__cond_var_wait(g_quiesce_teardown_race_hook.cv,
    5503              :                         g_quiesce_teardown_race_hook.mutex);
    5504            5 :   ccol__mutex_unlock(g_quiesce_teardown_race_hook.mutex);
    5505            5 : }
    5506              : 
    5507            5 : void chttpsvr__release_quiesce_teardown_race_hook_for_tests(void) {
    5508            5 :   ccol__call_once(g_quiesce_teardown_race_hook.once,
    5509              :                   quiesce_teardown_race_hook_init_globals);
    5510            5 :   ccol__mutex_lock(g_quiesce_teardown_race_hook.mutex);
    5511            5 :   g_quiesce_teardown_race_hook.go = true;
    5512            5 :   ccol__cond_var_broadcast(g_quiesce_teardown_race_hook.cv);
    5513            5 :   ccol__mutex_unlock(g_quiesce_teardown_race_hook.mutex);
    5514            5 : }
    5515              : 
    5516              : // Stops the calling thread at this race point for a test when the hook is
    5517              : // armed. It disarms the hook, signals that it got there and waits until the
    5518              : // test releases it. quiesce_server_once calls it, so a test can run its race in
    5519              : // a fixed order.
    5520          563 : static void quiesce_teardown_race_hook_wait_if_armed(void) {
    5521          563 :   ccol__call_once(g_quiesce_teardown_race_hook.once,
    5522              :                   quiesce_teardown_race_hook_init_globals);
    5523          563 :   ccol__mutex_lock(g_quiesce_teardown_race_hook.mutex);
    5524          563 :   if (!g_quiesce_teardown_race_hook.armed) {
    5525          558 :     ccol__mutex_unlock(g_quiesce_teardown_race_hook.mutex);
    5526          558 :     return;
    5527              :   }
    5528            5 :   g_quiesce_teardown_race_hook.armed = false;
    5529            5 :   g_quiesce_teardown_race_hook.entered = true;
    5530            5 :   ccol__cond_var_broadcast(g_quiesce_teardown_race_hook.cv);
    5531           10 :   while (!g_quiesce_teardown_race_hook.go)
    5532            5 :     ccol__cond_var_wait(g_quiesce_teardown_race_hook.cv,
    5533              :                         g_quiesce_teardown_race_hook.mutex);
    5534            5 :   ccol__mutex_unlock(g_quiesce_teardown_race_hook.mutex);
    5535              : }
    5536              : 
    5537              : static void timespec_add_ms(struct timespec *ts, unsigned ms);
    5538              : 
    5539              : // Test hook: Once armed, it pauses the CHTTPSVR_QS_QUIESCING backoff of
    5540              : // chttpsvr_start after it joined quiesce_waiters and released its resolve pin,
    5541              : // and before it takes raw->mutex again. A test runs a quiesce and a destroy to
    5542              : // the end around it to show raw survives; if quiesce_waiters were raised after
    5543              : // the pin release, the quiesce could free raw in that window.
    5544              : static struct {
    5545              :   ccol__mutex mutex;
    5546              :   ccol__cond_var cv;
    5547              :   ccol__once_flag once;
    5548              :   bool armed;
    5549              :   bool entered;
    5550              :   bool go;
    5551              : } g_start_quiescing_unpinned_race_hook = {0};
    5552              : 
    5553              : // Initialises the mutex and the condition variable of
    5554              : // g_start_quiescing_unpinned_race_hook; a failure is fatal. The condition
    5555              : // variable uses CLOCK_MONOTONIC, because the bounded wait of the test computes
    5556              : // its deadline on that clock.
    5557            1 : static void start_quiescing_unpinned_race_hook_init_globals(void) {
    5558            1 :   if (ccol__mutex_init(g_start_quiescing_unpinned_race_hook.mutex) != 0)
    5559            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5560            1 :   ccol__cond_var_attr cv_attr;
    5561            1 :   int cv_rc;
    5562            1 :   if (ccol__cond_var_attr_init(cv_attr) == 0) {
    5563            1 :     ccol__cond_var_attr_setclock(cv_attr, CLOCK_MONOTONIC);
    5564            1 :     cv_rc = ccol__cond_var_init_ca(g_start_quiescing_unpinned_race_hook.cv,
    5565              :                                    cv_attr);
    5566            1 :     ccol__cond_var_attr_destroy(cv_attr);
    5567              :   } else {
    5568            0 :     cv_rc = ccol__cond_var_init(g_start_quiescing_unpinned_race_hook.cv);
    5569              :   }
    5570            1 :   if (cv_rc != 0)
    5571            0 :     ccol__fatal_err(
    5572              :         "chttpsvr test hook: failed to initialize condition variable");
    5573            1 : }
    5574              : 
    5575              : // Test control: Arms g_start_quiescing_unpinned_race_hook for the next
    5576              : // chttpsvr_start that takes the backoff.
    5577            1 : void chttpsvr__arm_start_quiescing_unpinned_race_hook_for_tests(void) {
    5578            1 :   ccol__call_once(g_start_quiescing_unpinned_race_hook.once,
    5579              :                   start_quiescing_unpinned_race_hook_init_globals);
    5580            1 :   ccol__mutex_lock(g_start_quiescing_unpinned_race_hook.mutex);
    5581            1 :   g_start_quiescing_unpinned_race_hook.armed = true;
    5582            1 :   g_start_quiescing_unpinned_race_hook.entered = false;
    5583            1 :   g_start_quiescing_unpinned_race_hook.go = false;
    5584            1 :   ccol__mutex_unlock(g_start_quiescing_unpinned_race_hook.mutex);
    5585            1 : }
    5586              : 
    5587              : // Test control of g_start_quiescing_unpinned_race_hook: Waits until a paused
    5588              : // chttpsvr_start() has reached the hook. Returns true once it has, and false
    5589              : // after 10 seconds, so a regression that never reaches the hook fails the test
    5590              : // instead of hanging the whole binary (the call runs on the main test thread).
    5591              : // The test reaches the hook only after a reaper has claimed the server, which
    5592              : // it learns from chttpsvr__wait_quiesce_claimed_signal_entered_for_tests.
    5593            1 : bool chttpsvr__wait_start_quiescing_unpinned_race_hook_entered_for_tests(void) {
    5594            1 :   ccol__call_once(g_start_quiescing_unpinned_race_hook.once,
    5595              :                   start_quiescing_unpinned_race_hook_init_globals);
    5596            1 :   struct timespec deadline;
    5597            1 :   clock_gettime(CLOCK_MONOTONIC, &deadline);
    5598            2 :   timespec_add_ms(&deadline, 10000);
    5599            1 :   ccol__mutex_lock(g_start_quiescing_unpinned_race_hook.mutex);
    5600            1 :   bool timed_out = false;
    5601            2 :   while (!g_start_quiescing_unpinned_race_hook.entered && !timed_out) {
    5602            1 :     timed_out =
    5603            1 :         ccol__cond_var_timedwait(g_start_quiescing_unpinned_race_hook.cv,
    5604              :                                  g_start_quiescing_unpinned_race_hook.mutex,
    5605              :                                  deadline) == ETIMEDOUT;
    5606              :   }
    5607            1 :   bool entered = g_start_quiescing_unpinned_race_hook.entered;
    5608            1 :   ccol__mutex_unlock(g_start_quiescing_unpinned_race_hook.mutex);
    5609            1 :   return entered;
    5610              : }
    5611              : 
    5612              : // Test control of g_start_quiescing_unpinned_race_hook: Lets the paused
    5613              : // chttpsvr_start() go on.
    5614            1 : void chttpsvr__release_start_quiescing_unpinned_race_hook_for_tests(void) {
    5615            1 :   ccol__call_once(g_start_quiescing_unpinned_race_hook.once,
    5616              :                   start_quiescing_unpinned_race_hook_init_globals);
    5617            1 :   ccol__mutex_lock(g_start_quiescing_unpinned_race_hook.mutex);
    5618            1 :   g_start_quiescing_unpinned_race_hook.go = true;
    5619            1 :   ccol__cond_var_broadcast(g_start_quiescing_unpinned_race_hook.cv);
    5620            1 :   ccol__mutex_unlock(g_start_quiescing_unpinned_race_hook.mutex);
    5621            1 : }
    5622              : 
    5623              : // Holds chttpsvr_start() at the hook when a test armed it. It fires once, tells
    5624              : // the waiting test it got there, and waits under the hook mutex until the test
    5625              : // releases it.
    5626            3 : static void start_quiescing_unpinned_race_hook_wait_if_armed(void) {
    5627            3 :   ccol__call_once(g_start_quiescing_unpinned_race_hook.once,
    5628              :                   start_quiescing_unpinned_race_hook_init_globals);
    5629            3 :   ccol__mutex_lock(g_start_quiescing_unpinned_race_hook.mutex);
    5630            3 :   if (!g_start_quiescing_unpinned_race_hook.armed) {
    5631            2 :     ccol__mutex_unlock(g_start_quiescing_unpinned_race_hook.mutex);
    5632            2 :     return;
    5633              :   }
    5634            1 :   g_start_quiescing_unpinned_race_hook.armed = false;
    5635            1 :   g_start_quiescing_unpinned_race_hook.entered = true;
    5636            1 :   ccol__cond_var_broadcast(g_start_quiescing_unpinned_race_hook.cv);
    5637            2 :   while (!g_start_quiescing_unpinned_race_hook.go)
    5638            1 :     ccol__cond_var_wait(g_start_quiescing_unpinned_race_hook.cv,
    5639              :                         g_start_quiescing_unpinned_race_hook.mutex);
    5640            1 :   ccol__mutex_unlock(g_start_quiescing_unpinned_race_hook.mutex);
    5641              : }
    5642              : 
    5643              : // Test hook: Once armed, the next quiesce_server_once() pass that claims a
    5644              : // server signals right after it sets quiesce_state to CHTTPSVR_QS_QUIESCING. It
    5645              : // only signals and never blocks. It fires while the pass holds srv->mutex, so
    5646              : // its mutex is a leaf lock. A test that pauses a chttpsvr_start() with its pin
    5647              : // held uses it to know the reaper claimed the server before it releases the
    5648              : // paused call.
    5649              : static struct {
    5650              :   ccol__mutex mutex;
    5651              :   ccol__cond_var cv;
    5652              :   ccol__once_flag once;
    5653              :   bool armed;
    5654              :   bool entered;
    5655              : } g_quiesce_claimed_signal = {0};
    5656              : 
    5657              : // Creates the mutex and condition variable of g_quiesce_claimed_signal. The
    5658              : // condition variable uses CLOCK_MONOTONIC, because the bounded wait computes
    5659              : // its deadline on that clock.
    5660            6 : static void quiesce_claimed_signal_init_globals(void) {
    5661            6 :   if (ccol__mutex_init(g_quiesce_claimed_signal.mutex) != 0)
    5662            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5663            6 :   ccol__cond_var_attr cv_attr;
    5664            6 :   int cv_rc;
    5665            6 :   if (ccol__cond_var_attr_init(cv_attr) == 0) {
    5666            6 :     ccol__cond_var_attr_setclock(cv_attr, CLOCK_MONOTONIC);
    5667            6 :     cv_rc = ccol__cond_var_init_ca(g_quiesce_claimed_signal.cv, cv_attr);
    5668            6 :     ccol__cond_var_attr_destroy(cv_attr);
    5669              :   } else {
    5670            0 :     cv_rc = ccol__cond_var_init(g_quiesce_claimed_signal.cv);
    5671              :   }
    5672            6 :   if (cv_rc != 0)
    5673            0 :     ccol__fatal_err(
    5674              :         "chttpsvr test hook: failed to initialize condition variable");
    5675            6 : }
    5676              : 
    5677              : // Test control: Arms g_quiesce_claimed_signal for the next pass that claims a
    5678              : // server.
    5679            3 : void chttpsvr__arm_quiesce_claimed_signal_for_tests(void) {
    5680            3 :   ccol__call_once(g_quiesce_claimed_signal.once,
    5681              :                   quiesce_claimed_signal_init_globals);
    5682            3 :   ccol__mutex_lock(g_quiesce_claimed_signal.mutex);
    5683            3 :   g_quiesce_claimed_signal.armed = true;
    5684            3 :   g_quiesce_claimed_signal.entered = false;
    5685            3 :   ccol__mutex_unlock(g_quiesce_claimed_signal.mutex);
    5686            3 : }
    5687              : 
    5688              : // Test control: Waits up to 10 seconds for the armed signal to fire and returns
    5689              : // whether it did. It disarms the hook on the way out, so a missed signal can't
    5690              : // fire later in an unrelated pass.
    5691            3 : bool chttpsvr__wait_quiesce_claimed_signal_entered_for_tests(void) {
    5692            3 :   ccol__call_once(g_quiesce_claimed_signal.once,
    5693              :                   quiesce_claimed_signal_init_globals);
    5694            3 :   struct timespec deadline;
    5695            3 :   clock_gettime(CLOCK_MONOTONIC, &deadline);
    5696            6 :   timespec_add_ms(&deadline, 10000);
    5697            3 :   ccol__mutex_lock(g_quiesce_claimed_signal.mutex);
    5698            3 :   bool timed_out = false;
    5699            6 :   while (!g_quiesce_claimed_signal.entered && !timed_out) {
    5700            3 :     timed_out = ccol__cond_var_timedwait(g_quiesce_claimed_signal.cv,
    5701              :                                          g_quiesce_claimed_signal.mutex,
    5702              :                                          deadline) == ETIMEDOUT;
    5703              :   }
    5704            3 :   bool entered = g_quiesce_claimed_signal.entered;
    5705            3 :   g_quiesce_claimed_signal.armed = false;
    5706            3 :   ccol__mutex_unlock(g_quiesce_claimed_signal.mutex);
    5707            3 :   return entered;
    5708              : }
    5709              : 
    5710              : // Fires g_quiesce_claimed_signal once if a test armed it; called by
    5711              : // quiesce_server_once() right after it claims a server.
    5712          563 : static void quiesce_claimed_signal_fire_if_armed(void) {
    5713          563 :   ccol__call_once(g_quiesce_claimed_signal.once,
    5714              :                   quiesce_claimed_signal_init_globals);
    5715          563 :   ccol__mutex_lock(g_quiesce_claimed_signal.mutex);
    5716          563 :   if (g_quiesce_claimed_signal.armed) {
    5717            3 :     g_quiesce_claimed_signal.armed = false;
    5718            3 :     g_quiesce_claimed_signal.entered = true;
    5719            3 :     ccol__cond_var_broadcast(g_quiesce_claimed_signal.cv);
    5720              :   }
    5721          563 :   ccol__mutex_unlock(g_quiesce_claimed_signal.mutex);
    5722          563 : }
    5723              : 
    5724              : // Test hook that blocks listener_on_readable() at one of two points picked by
    5725              : // the arm call: Right after it pins srv through listener_dispatch_pins, or at
    5726              : // its very first statement, before the pin. A test lands a concurrent
    5727              : // chttpsvr_destroy() while a listener dispatch is really in flight and checks
    5728              : // whether the destroy waits for the pin. It has the shape of
    5729              : // g_reaper_race_hook.
    5730              : static struct {
    5731              :   ccol__mutex mutex;
    5732              :   ccol__cond_var cv;
    5733              :   ccol__once_flag once;
    5734              :   bool armed;
    5735              :   bool at_entry;
    5736              :   bool entered;
    5737              :   bool go;
    5738              : } g_listener_dispatch_race_hook = {0};
    5739              : 
    5740              : // Creates the mutex and condition variable of g_listener_dispatch_race_hook.
    5741            6 : static void listener_dispatch_race_hook_init_globals(void) {
    5742            6 :   if (ccol__mutex_init(g_listener_dispatch_race_hook.mutex) != 0)
    5743            0 :     ccol__fatal_err("chttpsvr test hook: failed to initialize mutex");
    5744            6 :   if (ccol__cond_var_init(g_listener_dispatch_race_hook.cv) != 0)
    5745            0 :     ccol__fatal_err(
    5746              :         "chttpsvr test hook: failed to initialize condition variable");
    5747            6 : }
    5748              : 
    5749              : // Arms g_listener_dispatch_race_hook for one dispatch, at the entry point when
    5750              : // at_entry is true and after the pin otherwise.
    5751            4 : static void listener_dispatch_race_hook_arm(bool at_entry) {
    5752            4 :   ccol__call_once(g_listener_dispatch_race_hook.once,
    5753              :                   listener_dispatch_race_hook_init_globals);
    5754            4 :   ccol__mutex_lock(g_listener_dispatch_race_hook.mutex);
    5755            4 :   g_listener_dispatch_race_hook.armed = true;
    5756            4 :   g_listener_dispatch_race_hook.at_entry = at_entry;
    5757            4 :   g_listener_dispatch_race_hook.entered = false;
    5758            4 :   g_listener_dispatch_race_hook.go = false;
    5759            4 :   ccol__mutex_unlock(g_listener_dispatch_race_hook.mutex);
    5760            4 : }
    5761              : 
    5762              : // Test controls of g_listener_dispatch_race_hook: Arm it after the pin or at
    5763              : // the entry, wait until a dispatch is held, and release it.
    5764            1 : void chttpsvr__arm_listener_dispatch_race_hook_for_tests(void) {
    5765            1 :   listener_dispatch_race_hook_arm(false);
    5766            1 : }
    5767              : 
    5768            3 : void chttpsvr__arm_listener_dispatch_entry_race_hook_for_tests(void) {
    5769            3 :   listener_dispatch_race_hook_arm(true);
    5770            3 : }
    5771              : 
    5772            4 : void chttpsvr__wait_listener_dispatch_race_hook_entered_for_tests(void) {
    5773            4 :   ccol__call_once(g_listener_dispatch_race_hook.once,
    5774              :                   listener_dispatch_race_hook_init_globals);
    5775            4 :   ccol__mutex_lock(g_listener_dispatch_race_hook.mutex);
    5776            8 :   while (!g_listener_dispatch_race_hook.entered)
    5777            4 :     ccol__cond_var_wait(g_listener_dispatch_race_hook.cv,
    5778              :                         g_listener_dispatch_race_hook.mutex);
    5779            4 :   ccol__mutex_unlock(g_listener_dispatch_race_hook.mutex);
    5780            4 : }
    5781              : 
    5782            4 : void chttpsvr__release_listener_dispatch_race_hook_for_tests(void) {
    5783            4 :   ccol__call_once(g_listener_dispatch_race_hook.once,
    5784              :                   listener_dispatch_race_hook_init_globals);
    5785            4 :   ccol__mutex_lock(g_listener_dispatch_race_hook.mutex);
    5786            4 :   g_listener_dispatch_race_hook.go = true;
    5787            4 :   ccol__cond_var_broadcast(g_listener_dispatch_race_hook.cv);
    5788            4 :   ccol__mutex_unlock(g_listener_dispatch_race_hook.mutex);
    5789            4 : }
    5790              : 
    5791              : // Holds listener_on_readable() when the hook is armed for this point (at_entry
    5792              : // tells which one the caller is at). It fires once and waits under the hook
    5793              : // mutex until the test releases it.
    5794         2286 : static void listener_dispatch_race_hook_wait_if_armed(bool at_entry) {
    5795         2286 :   ccol__call_once(g_listener_dispatch_race_hook.once,
    5796              :                   listener_dispatch_race_hook_init_globals);
    5797         2286 :   ccol__mutex_lock(g_listener_dispatch_race_hook.mutex);
    5798         2286 :   if (!g_listener_dispatch_race_hook.armed ||
    5799            5 :       g_listener_dispatch_race_hook.at_entry != at_entry) {
    5800         2282 :     ccol__mutex_unlock(g_listener_dispatch_race_hook.mutex);
    5801         2282 :     return;
    5802              :   }
    5803            4 :   g_listener_dispatch_race_hook.armed = false;
    5804            4 :   g_listener_dispatch_race_hook.entered = true;
    5805            4 :   ccol__cond_var_broadcast(g_listener_dispatch_race_hook.cv);
    5806            8 :   while (!g_listener_dispatch_race_hook.go)
    5807            4 :     ccol__cond_var_wait(g_listener_dispatch_race_hook.cv,
    5808              :                         g_listener_dispatch_race_hook.mutex);
    5809            4 :   ccol__mutex_unlock(g_listener_dispatch_race_hook.mutex);
    5810              : }
    5811              : #endif
    5812              : 
    5813              : // Task of reject_pool: Sends a rejection and closes the connection on one of
    5814              : // that pool's threads, so a slow client can't stall the reactor. It releases
    5815              : // the request's in_flight_requests slot only after the close completed (see
    5816              : // release_in_flight). srv is read first, because conn_reject_and_close frees
    5817              : // conn.
    5818          228 : static void reject_task(void *arg) {
    5819          228 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    5820          228 :   struct chttpserver *srv = conn->srv;
    5821          228 :   chttpsvr_mark_worker_thread(srv);
    5822          228 :   conn_reject_and_close(conn, true);
    5823              : #ifdef RUNNING_UNIT_TESTS
    5824          228 :   atomic_fetch_add(&g_reject_task_run_count_for_tests, 1);
    5825              : #endif
    5826          228 :   release_in_flight(srv);
    5827          228 : }
    5828              : 
    5829              : // Feeds n new bytes into conn->parser and acts on the result. conn_pump calls
    5830              : // it for bytes it read, and the keep-alive tail of task_worker calls it for the
    5831              : // bytes of a pipelined request that are already off the wire, so no readiness
    5832              : // event would bring them back. buf only needs to live for the call.
    5833              : // It returns true when the parser needs more header bytes, and false when conn
    5834              : // has been handed on (diverted to a worker, or sent to the reject path); the
    5835              : // caller must not touch conn after false. A routing rejection (CHTTP1_USER)
    5836              : // keeps the status http1_on_headers_complete chose, and a syntax error gets
    5837              : // 400, because nothing after a syntax error can be framed as a request. Either
    5838              : // way the answer goes through conn_dispatch_reject, so a slow reader never
    5839              : // stalls the reactor, and the connection closes. It also arms the header-phase
    5840              : // budget at the first byte of the request and refreshes conn->last_activity.
    5841         1366 : static bool conn_feed_bytes(chttpsvr_conn *conn, const char *buf, size_t n) {
    5842         1366 :   clock_gettime(CLOCK_MONOTONIC, &conn->last_activity);
    5843         1366 :   conn_header_phase_arm(conn, &conn->last_activity);
    5844         1366 :   chttp1_errno r = chttp1_parser_execute(&conn->parser, buf, n);
    5845              : 
    5846         1366 :   if (r == CHTTP1_OK) return true;
    5847              : 
    5848         1271 :   if (r == CHTTP1_HEADERS_ONLY || r == CHTTP1_PAUSED) {
    5849         1062 :     size_t consumed = chttp1_parser_consumed(&conn->parser);
    5850         1062 :     const char *leftover = buf + consumed;
    5851         1062 :     size_t leftover_len = n - consumed;
    5852              : 
    5853         1062 :     conn_start_diverted(conn, leftover, leftover_len);
    5854         1062 :     return false;
    5855              :   }
    5856              : 
    5857          209 :   if (!conn->req_rejected) {
    5858           30 :     conn->req_rejected = true;
    5859           30 :     conn->reject_status = CHTTP_STATUS_BAD_REQUEST;
    5860              :   }
    5861          209 :   conn_dispatch_reject(conn);
    5862          209 :   return false;
    5863              : }
    5864              : 
    5865              : // Drives the reactor-owned part of a connection: The TLS handshake if there is
    5866              : // one, then the reads of the header block, until the request is diverted to a
    5867              : // worker or rejected. A parked connection goes to conn_linger_step or
    5868              : // conn_resume_parked instead. The handshake arms the header-phase budget, so a
    5869              : // peer that drips handshake bytes can't escape it.
    5870              : // Whenever the socket has nothing (or the handshake wants more), it sets the
    5871              : // registration to the direction it needs and puts conn back in the idle list,
    5872              : // so the sweep and a destroy can see it and the next dispatch can claim it. On
    5873              : // TLS the direction can be write even for a read, because OpenSSL may have to
    5874              : // send first (see ctls_conn_wants_write). A new registration adds one to
    5875              : // conn->lifetime_refs and srv->lifetime_refs at once, for the on_removed it
    5876              : // fires later. A failed modify closes the connection, since a wrong interest
    5877              : // would strand it. EINTR retries the read; an error or EOF closes the
    5878              : // connection.
    5879       155846 : static void conn_pump(chttpsvr_conn *conn) {
    5880       155846 :   if (__builtin_expect(conn->park != CONN_PARK_NONE, 0)) {
    5881       153730 :     if (conn->park == CONN_PARK_LINGER)
    5882       153289 :       conn_linger_step(conn);
    5883              :     else
    5884          441 :       conn_resume_parked(conn);
    5885       153730 :     return;
    5886              :   }
    5887         2116 :   if (conn->state == CONN_ST_TLS_HANDSHAKE) {
    5888           87 :     if (!conn->header_phase_active) {
    5889           29 :       struct timespec hs_now;
    5890           29 :       clock_gettime(CLOCK_MONOTONIC, &hs_now);
    5891           58 :       conn_header_phase_arm(conn, &hs_now);
    5892              :     }
    5893           87 :     ctls_handshake_result r = ctls_conn_handshake_step(conn->tls);
    5894           87 :     if (r == CTLS_HANDSHAKE_ERROR) {
    5895            6 :       SRV_ENGINE_LOG(clog_warn, "TLS handshake failed fd=%d", conn->fd);
    5896            6 :       conn_close(conn);
    5897            6 :       return;
    5898              :     }
    5899           81 :     if (r == CTLS_HANDSHAKE_WANT_READ || r == CTLS_HANDSHAKE_WANT_WRITE) {
    5900           58 :       cselect_dir want =
    5901           58 :           (r == CTLS_HANDSHAKE_WANT_WRITE) ? cselect_write : cselect_read;
    5902           58 :       if (conn->reg) {
    5903           29 :         if (conn_reg_modify(conn, want) != ccol_success) {
    5904            0 :           conn_close(conn);
    5905            0 :           return;
    5906              :         }
    5907              :       } else {
    5908           29 :         char *err = NULL;
    5909           58 :         conn->reg = ceventloop_add(
    5910           29 :             srv_engine_bundler.reactor, cselectable_fd(conn->fd, want),
    5911           29 :             (ceventloop_handlers){.on_readable = conn_on_readable,
    5912              :                                   .on_writable = conn_on_writable,
    5913              :                                   .on_error = conn_on_error,
    5914              :                                   .on_removed = conn_on_removed},
    5915              :             conn, &err);
    5916           29 :         if (!conn->reg) {
    5917            0 :           conn_close(conn);
    5918            0 :           return;
    5919              :         }
    5920           29 :         conn->reg_dir = (uint8_t)want;
    5921           29 :         atomic_fetch_add(&conn->lifetime_refs, 1);
    5922           29 :         atomic_fetch_add(&conn->srv->lifetime_refs, 1);
    5923              :       }
    5924           58 :       idle_list_add(conn);
    5925           58 :       return;
    5926              :     }
    5927           23 :     conn->state = CONN_ST_READING_HEADERS;
    5928           23 :     if (conn->reg) {
    5929           23 :       if (conn_reg_modify(conn, cselect_read) != ccol_success) {
    5930            0 :         conn_close(conn);
    5931            0 :         return;
    5932              :       }
    5933              :     }
    5934              :   }
    5935              : 
    5936         2144 :   for (;;) {
    5937         2144 :     char buf[8192];
    5938         2144 :     ssize_t n;
    5939         2144 :     if (conn->tls)
    5940           45 :       n = ctls_conn_read(conn->tls, buf, sizeof(buf));
    5941              :     else
    5942         2099 :       n = read(conn->fd, buf, sizeof(buf));
    5943              : 
    5944         2144 :     if (n < 0) {
    5945          600 :       if (errno == EINTR) continue;
    5946          600 :       if (errno == EWOULDBLOCK || errno == EAGAIN) {
    5947          599 :         cselect_dir want = cselect_read;
    5948          599 :         if (conn->tls && ctls_conn_wants_write(conn->tls)) want = cselect_write;
    5949          599 :         if (!conn->reg) {
    5950          510 :           char *err = NULL;
    5951         1020 :           conn->reg = ceventloop_add(
    5952          510 :               srv_engine_bundler.reactor, cselectable_fd(conn->fd, want),
    5953          510 :               (ceventloop_handlers){.on_readable = conn_on_readable,
    5954              :                                     .on_writable = conn_on_writable,
    5955              :                                     .on_error = conn_on_error,
    5956              :                                     .on_removed = conn_on_removed},
    5957              :               conn, &err);
    5958          510 :           if (!conn->reg) {
    5959            0 :             conn_close(conn);
    5960            0 :             return;
    5961              :           }
    5962          510 :           conn->reg_dir = (uint8_t)want;
    5963          510 :           atomic_fetch_add(&conn->lifetime_refs, 1);
    5964          510 :           atomic_fetch_add(&conn->srv->lifetime_refs, 1);
    5965              :         } else {
    5966           89 :           if (conn_reg_modify(conn, want) != ccol_success) {
    5967            0 :             conn_close(conn);
    5968            0 :             return;
    5969              :           }
    5970              :         }
    5971          599 :         idle_list_add(conn);
    5972          599 :         return;
    5973              :       }
    5974            1 :       conn_close(conn);
    5975            1 :       return;
    5976              :     }
    5977         1544 :     if (n == 0) {
    5978          269 :       conn_close(conn);
    5979          269 :       return;
    5980              :     }
    5981              : 
    5982         1275 :     if (!conn_feed_bytes(conn, buf, (size_t)n)) return;
    5983              :   }
    5984              : }
    5985              : 
    5986              : // Reactor callbacks of a connection. Each one first claims conn out of the idle
    5987              : // list with idle_list_try_claim, which keeps a dispatch and a concurrent closer
    5988              : // (idle sweep or destroy) from using the same connection. A failed claim means
    5989              : // someone else owns it, or its idle_list_add hasn't run yet and level-triggered
    5990              : // epoll reports it again, so the callback returns without touching it. Readable
    5991              : // and writable events pump the connection, an error closes it.
    5992       154492 : static void conn_on_readable(ceventloop loop, ceventloop_reg reg,
    5993              :                              cselectable *sel, void *arg) {
    5994       154492 :   (void)loop;
    5995       154492 :   (void)reg;
    5996       154492 :   (void)sel;
    5997       154492 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    5998       154492 :   if (!idle_list_try_claim(conn)) return;
    5999       154427 :   conn_pump(conn);
    6000              : }
    6001              : 
    6002          133 : static void conn_on_writable(ceventloop loop, ceventloop_reg reg,
    6003              :                              cselectable *sel, void *arg) {
    6004          133 :   (void)loop;
    6005          133 :   (void)reg;
    6006          133 :   (void)sel;
    6007          133 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    6008          133 :   if (!idle_list_try_claim(conn)) return;
    6009          133 :   conn_pump(conn);
    6010              : }
    6011              : 
    6012            0 : static void conn_on_error(ceventloop loop, ceventloop_reg reg, cselectable *sel,
    6013              :                           void *arg) {
    6014            0 :   (void)loop;
    6015            0 :   (void)reg;
    6016            0 :   (void)sel;
    6017            0 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    6018            0 :   if (!idle_list_try_claim(conn)) return;
    6019            0 :   conn_close(conn);
    6020              : }
    6021              : 
    6022              : // Slow clients. A worker never waits on a client's socket for a buffered route:
    6023              : // a body read or a response write that would block parks the connection with no
    6024              : // thread, a rate floor and gap limits close slow peers, body memory has a
    6025              : // shared limit with a FIFO wait list, and streaming handlers run on their own
    6026              : // bounded pool fed by a bounded queue. The sweep enforces every limit, and a
    6027              : // teardown closes or answers every wait.
    6028              : //
    6029              : // The largest SO_RCVLOWAT a parked body asks for, which bounds how much the
    6030              : // kernel buffers before it wakes the reactor.
    6031              : #define CHTTPSVR_RCVLOWAT_LIMIT 16384
    6032              : 
    6033              : #ifdef RUNNING_UNIT_TESTS
    6034              : // Test hooks for the slow-client code: A clock offset that only slow_clock adds
    6035              : // (so a test can expire a limit without sleeping), process-wide counts of
    6036              : // resume dispatches and parks (also per kind of park), and a switch that turns
    6037              : // SO_RCVLOWAT off. The functions below read or set them.
    6038              : static _Atomic long long g_slow_clock_offset_ms_for_tests = 0;
    6039              : static _Atomic size_t g_resume_dispatch_count_for_tests = 0;
    6040              : static _Atomic size_t g_park_count_for_tests = 0;
    6041              : static _Atomic size_t g_park_kind_count_for_tests[8];
    6042           23 : size_t chttpsvr__park_kind_count_for_tests(int kind) {
    6043           23 :   return kind >= 0 && kind < 8 ? atomic_load(&g_park_kind_count_for_tests[kind])
    6044           23 :                                : 0;
    6045              : }
    6046              : static _Atomic bool g_rcvlowat_disabled_for_tests = false;
    6047           17 : void chttpsvr__advance_slow_clock_for_tests(long long ms) {
    6048           17 :   atomic_fetch_add(&g_slow_clock_offset_ms_for_tests, ms);
    6049           17 : }
    6050           11 : size_t chttpsvr__resume_dispatch_count_for_tests(void) {
    6051           11 :   return atomic_load(&g_resume_dispatch_count_for_tests);
    6052              : }
    6053           10 : size_t chttpsvr__park_count_for_tests(void) {
    6054           10 :   return atomic_load(&g_park_count_for_tests);
    6055              : }
    6056            3 : void chttpsvr__set_rcvlowat_enabled_for_tests(bool enabled) {
    6057            3 :   atomic_store(&g_rcvlowat_disabled_for_tests, !enabled);
    6058            3 : }
    6059              : 
    6060              : // Test hook that holds a streaming-pool task just before it claims the next
    6061              : // queued request (armed_at 1) or just after (armed_at 2), so a test can run the
    6062              : // sweep in that window and see that exactly one of the two answers the request.
    6063              : // release_gen is bumped by every release, and a held task waits for it to
    6064              : // change, so an arm made after a release never takes the release back from a
    6065              : // task that hasn't woken yet.
    6066              : static struct {
    6067              :   ccol__mutex mutex;
    6068              :   ccol__cond_var cv;
    6069              :   ccol__once_flag once;
    6070              :   int armed_at;
    6071              :   bool entered;
    6072              :   unsigned release_gen;
    6073              : } g_stream_claim_hook = {0};
    6074              : // Creates the mutex and condition variable of g_stream_claim_hook.
    6075            2 : static void stream_claim_hook_init_globals(void) {
    6076            4 :   if (ccol__mutex_init(g_stream_claim_hook.mutex) != 0 ||
    6077            2 :       ccol__cond_var_init(g_stream_claim_hook.cv) != 0)
    6078            0 :     ccol__fatal_err("chttpsvr: stream claim hook init failed");
    6079            2 : }
    6080              : // Test controls of g_stream_claim_hook: Arm it at a point, wait up to
    6081              : // timeout_ms for a task to be held there (returns whether one was), and release
    6082              : // it.
    6083            6 : void chttpsvr__arm_stream_claim_hook_for_tests(int where) {
    6084            6 :   ccol__call_once(g_stream_claim_hook.once, stream_claim_hook_init_globals);
    6085            6 :   ccol__mutex_lock(g_stream_claim_hook.mutex);
    6086            6 :   g_stream_claim_hook.armed_at = where;
    6087            6 :   g_stream_claim_hook.entered = false;
    6088            6 :   ccol__mutex_unlock(g_stream_claim_hook.mutex);
    6089            6 : }
    6090            3 : bool chttpsvr__wait_stream_claim_hook_entered_for_tests(unsigned timeout_ms) {
    6091            3 :   ccol__call_once(g_stream_claim_hook.once, stream_claim_hook_init_globals);
    6092            3 :   struct timespec deadline;
    6093            3 :   clock_gettime(CLOCK_REALTIME, &deadline);
    6094            6 :   timespec_add_ms(&deadline, timeout_ms);
    6095            3 :   ccol__mutex_lock(g_stream_claim_hook.mutex);
    6096            6 :   while (!g_stream_claim_hook.entered)
    6097            3 :     if (ccol__cond_var_timedwait(g_stream_claim_hook.cv,
    6098              :                                  g_stream_claim_hook.mutex,
    6099              :                                  deadline) == ETIMEDOUT)
    6100              :       break;
    6101            3 :   bool entered = g_stream_claim_hook.entered;
    6102            3 :   ccol__mutex_unlock(g_stream_claim_hook.mutex);
    6103            3 :   return entered;
    6104              : }
    6105            3 : void chttpsvr__release_stream_claim_hook_for_tests(void) {
    6106            3 :   ccol__call_once(g_stream_claim_hook.once, stream_claim_hook_init_globals);
    6107            3 :   ccol__mutex_lock(g_stream_claim_hook.mutex);
    6108            3 :   g_stream_claim_hook.release_gen++;
    6109            3 :   ccol__cond_var_broadcast(g_stream_claim_hook.cv);
    6110            3 :   ccol__mutex_unlock(g_stream_claim_hook.mutex);
    6111            3 : }
    6112              : // Holds the calling streaming task when the hook is armed at where, until the
    6113              : // next release.
    6114          257 : static void stream_claim_hook_wait_if_armed(int where) {
    6115          257 :   ccol__call_once(g_stream_claim_hook.once, stream_claim_hook_init_globals);
    6116          257 :   ccol__mutex_lock(g_stream_claim_hook.mutex);
    6117          257 :   if (g_stream_claim_hook.armed_at == where) {
    6118            3 :     unsigned gen = g_stream_claim_hook.release_gen;
    6119            3 :     g_stream_claim_hook.armed_at = 0;
    6120            3 :     g_stream_claim_hook.entered = true;
    6121            3 :     ccol__cond_var_broadcast(g_stream_claim_hook.cv);
    6122            6 :     while (g_stream_claim_hook.release_gen == gen)
    6123            3 :       ccol__cond_var_wait(g_stream_claim_hook.cv, g_stream_claim_hook.mutex);
    6124              :   }
    6125          257 :   ccol__mutex_unlock(g_stream_claim_hook.mutex);
    6126          257 : }
    6127              : #endif
    6128              : 
    6129              : // Reads the clock of every slow-client limit: CLOCK_MONOTONIC, plus the test
    6130              : // offset in a test build.
    6131         3879 : static void slow_clock(struct timespec *ts) {
    6132         3879 :   clock_gettime(CLOCK_MONOTONIC, ts);
    6133              : #ifdef RUNNING_UNIT_TESTS
    6134         3879 :   long long off = atomic_load(&g_slow_clock_offset_ms_for_tests);
    6135         3879 :   if (off > 0) timespec_add_ms(ts, (unsigned)off);
    6136              : #endif
    6137         3879 : }
    6138              : 
    6139              : // Whole milliseconds from then to now, rounded down and signed (negative when
    6140              : // another thread stamped then after now was read). A limit of n ms compared
    6141              : // with >= is reached when n ms have passed, never sooner.
    6142         1071 : static long long ms_since(struct timespec now, struct timespec then) {
    6143         1071 :   return ns_between(now, then) / 1000000LL;
    6144              : }
    6145              : 
    6146              : // The same span rounded up. Waits taken off a client's clock and the time left
    6147              : // before a deadline use it, so a client is never charged for a fraction of a
    6148              : // millisecond it didn't use.
    6149          929 : static long long ms_since_ceil(struct timespec now, struct timespec then) {
    6150            3 :   return ms_ceil_of_ns(ns_between(now, then));
    6151              : }
    6152              : 
    6153              : #ifdef RUNNING_UNIT_TESTS
    6154              : // Test access to ms_since and ms_since_ceil.
    6155            4 : long long chttpsvr__ms_since_for_tests(struct timespec now,
    6156              :                                        struct timespec then, bool ceil) {
    6157            4 :   return ceil ? ms_since_ceil(now, then) : ms_since(now, then);
    6158              : }
    6159              : #endif
    6160              : 
    6161              : // Moves *ts ms milliseconds earlier.
    6162            2 : static void timespec_sub_ms(struct timespec *ts, long long ms) {
    6163            2 :   ts->tv_sec -= (time_t)(ms / 1000);
    6164            2 :   ts->tv_nsec -= (long)(ms % 1000) * 1000000L;
    6165            2 :   if (ts->tv_nsec < 0) {
    6166            0 :     ts->tv_nsec += 1000000000L;
    6167            0 :     ts->tv_sec -= 1;
    6168              :   }
    6169              : }
    6170              : 
    6171              : // Whether now is at or past when.
    6172       153756 : static bool timespec_reached(struct timespec now, struct timespec when) {
    6173       153755 :   return now.tv_sec > when.tv_sec ||
    6174        10620 :          (now.tv_sec == when.tv_sec && now.tv_nsec >= when.tv_nsec);
    6175              : }
    6176              : 
    6177              : // Sets SO_RCVLOWAT on a connection that parks with an incomplete body, so the
    6178              : // reactor wakes once a useful amount of body is queued and not for every small
    6179              : // segment. The mark is the number of body bytes the framing still guarantees
    6180              : // (chttp1_body_bytes_still_expected), capped at CHTTPSVR_RCVLOWAT_LIMIT, so a
    6181              : // client that follows its framing always reaches it. It is 1 on a chunk-size
    6182              : // line or in trailers, and 1 when OpenSSL holds part of a record, because the
    6183              : // rest of that record needs fewer socket bytes than the plaintext it completes.
    6184              : // It is also at most half of the receive buffer (read once into
    6185              : // conn->rcvlowat_cap), because a buffer queues a bit less than its size and a
    6186              : // mark at the size is never reached. conn->rcvlowat caches the value set, so an
    6187              : // unchanged mark costs no system call.
    6188          322 : static void conn_set_rcvlowat(chttpsvr_conn *conn) {
    6189          322 :   int want = 1;
    6190              : #ifdef RUNNING_UNIT_TESTS
    6191          322 :   if (atomic_load(&g_rcvlowat_disabled_for_tests)) want = 0;
    6192              : #endif
    6193          322 :   if (want && !(conn->tls && ctls_conn_has_pending_input(conn->tls))) {
    6194          120 :     uint64_t rem = chttp1_body_bytes_still_expected(&conn->parser);
    6195          120 :     if (rem > 1)
    6196          108 :       want = rem < (uint64_t)CHTTPSVR_RCVLOWAT_LIMIT ? (int)rem
    6197          108 :                                                      : CHTTPSVR_RCVLOWAT_LIMIT;
    6198              :   }
    6199          322 :   if (want > 1) {
    6200          108 :     if (conn->rcvlowat_cap == 0) {
    6201          106 :       int rcvbuf = 0;
    6202          106 :       socklen_t len = sizeof(rcvbuf);
    6203          106 :       conn->rcvlowat_cap =
    6204          106 :           getsockopt(conn->fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len) == 0 &&
    6205          106 :                   rcvbuf / 2 > 1
    6206              :               ? rcvbuf / 2
    6207          212 :               : 1;
    6208              :     }
    6209          108 :     if (want > conn->rcvlowat_cap) want = conn->rcvlowat_cap;
    6210              :   }
    6211          322 :   if (want <= 1) {
    6212          214 :     if (conn->rcvlowat > 1) {
    6213            1 :       int one = 1;
    6214            1 :       (void)setsockopt(conn->fd, SOL_SOCKET, SO_RCVLOWAT, &one, sizeof(one));
    6215            1 :       conn->rcvlowat = 1;
    6216              :     }
    6217          214 :     return;
    6218              :   }
    6219          213 :   if (want != conn->rcvlowat &&
    6220          106 :       setsockopt(conn->fd, SOL_SOCKET, SO_RCVLOWAT, &want, sizeof(want)) == 0)
    6221          105 :     conn->rcvlowat = want;
    6222              : }
    6223              : 
    6224              : // Puts the mark back to 1 once the body is done, so the next request or a write
    6225              : // park wakes on its first byte.
    6226          375 : static void conn_reset_rcvlowat(chttpsvr_conn *conn) {
    6227          375 :   if (conn->rcvlowat > 1) {
    6228           99 :     int one = 1;
    6229           99 :     (void)setsockopt(conn->fd, SOL_SOCKET, SO_RCVLOWAT, &one, sizeof(one));
    6230           99 :     conn->rcvlowat = 1;
    6231              :   }
    6232          375 : }
    6233              : 
    6234              : // Starts the phase the rate floor measures (a body read or a response write) at
    6235              : // the current slow_clock, with bytes_so_far already counted.
    6236          189 : static void rate_window_start(chttpsvr_conn *conn, uint64_t bytes_so_far) {
    6237          189 :   slow_clock(&conn->rate_start);
    6238          189 :   conn->last_progress = conn->rate_start;
    6239          189 :   conn->rate_bytes = bytes_so_far;
    6240          189 :   conn->rate_paused_ms = 0;
    6241          189 :   conn->rate_queued = 0;
    6242          189 :   conn->rate_active = true;
    6243          160 : }
    6244              : 
    6245              : // The time of the current phase that counts against the client: Time since its
    6246              : // start minus the time the server held it back.
    6247          550 : static long long rate_elapsed_ms(const chttpsvr_conn *conn,
    6248              :                                  struct timespec now) {
    6249          550 :   return ms_since(now, conn->rate_start) - conn->rate_paused_ms;
    6250              : }
    6251              : 
    6252              : // How long a phase that moved bytes stays above a floor of rate bytes per
    6253              : // second: The grace period or the time those bytes buy, whichever is longer.
    6254              : // Saturates instead of overflowing.
    6255          550 : static long long rate_allowed_ms(unsigned rate, unsigned grace,
    6256              :                                  uint64_t bytes) {
    6257         1100 :   uint64_t bought =
    6258         1100 :       bytes > UINT64_MAX / 1000u ? UINT64_MAX : bytes * 1000u / rate;
    6259          550 :   if (bought > (uint64_t)LLONG_MAX) bought = (uint64_t)LLONG_MAX;
    6260          550 :   return (long long)bought > (long long)grace ? (long long)bought
    6261          550 :                                               : (long long)grace;
    6262              : }
    6263              : 
    6264              : // Whether conn's current phase is below srv's rate floor, counting extra_bytes
    6265              : // on top of the bytes it moved. A floor of UINT_MAX or no active phase never
    6266              : // is.
    6267          358 : static bool rate_below_floor(struct chttpserver *srv, const chttpsvr_conn *conn,
    6268              :                              struct timespec now, uint64_t extra_bytes) {
    6269          358 :   unsigned rate = atomic_load(&srv->min_rate_bps);
    6270          358 :   if (rate == UINT_MAX || !conn->rate_active) return false;
    6271          315 :   unsigned grace = atomic_load(&srv->rate_grace_ms);
    6272          630 :   return rate_elapsed_ms(conn, now) >
    6273          630 :          rate_allowed_ms(rate, grace, conn->rate_bytes + extra_bytes);
    6274              : }
    6275              : 
    6276              : // The rate floor inside a streaming handler's blocking read. The first call
    6277              : // starts the phase. Returns false when the body is already below the floor;
    6278              : // otherwise it shrinks *timeout_ms_inout to the moment the floor would be
    6279              : // crossed if no more bytes came (0 there means no bound yet, as in
    6280              : // shrink_timeout_to_deadline).
    6281          104 : static bool rate_floor_shrink(chttpsvr_conn *conn, unsigned *timeout_ms_inout) {
    6282          104 :   struct chttpserver *srv = conn->srv;
    6283          104 :   unsigned rate = atomic_load(&srv->min_rate_bps);
    6284          104 :   if (rate == UINT_MAX) return true;
    6285           96 :   if (!conn->rate_active) rate_window_start(conn, 0);
    6286           96 :   struct timespec now;
    6287           96 :   slow_clock(&now);
    6288           96 :   long long left = rate_allowed_ms(rate, atomic_load(&srv->rate_grace_ms),
    6289           96 :                                    conn->rate_bytes) -
    6290           96 :                    rate_elapsed_ms(conn, now) + 1;
    6291           96 :   if (left <= 0) return false;
    6292           96 :   unsigned left_ms = left > (long long)UINT_MAX ? UINT_MAX : (unsigned)left;
    6293           96 :   if (!*timeout_ms_inout || left_ms < *timeout_ms_inout)
    6294           45 :     *timeout_ms_inout = left_ms;
    6295              :   return true;
    6296              : }
    6297              : 
    6298              : // Returns how many bytes conn's send queue still holds (not sent, or not
    6299              : // acknowledged by the peer), read through SIOCOUTQ, FIONWRITE or SO_NWRITE
    6300              : // depending on the system, or SIZE_MAX when the kernel doesn't report it.
    6301          278 : static size_t conn_send_queue(const chttpsvr_conn *conn) {
    6302              : #ifdef RUNNING_UNIT_TESTS
    6303          278 :   parked_query_note_for_tests();
    6304              : #endif
    6305          278 :   int outq = 0;
    6306              : #if defined(SIOCOUTQ)
    6307          278 :   if (ioctl(conn->fd, SIOCOUTQ, &outq) != 0 || outq < 0) return SIZE_MAX;
    6308              : #elif defined(FIONWRITE)
    6309              :   if (ioctl(conn->fd, FIONWRITE, &outq) != 0 || outq < 0) return SIZE_MAX;
    6310              : #elif defined(SO_NWRITE)
    6311              :   socklen_t len = sizeof(outq);
    6312              :   if (getsockopt(conn->fd, SOL_SOCKET, SO_NWRITE, &outq, &len) != 0 || outq < 0)
    6313              :     return SIZE_MAX;
    6314              : #else
    6315              :   (void)conn;
    6316              :   return SIZE_MAX;
    6317              : #endif
    6318          278 :   return (size_t)outq;
    6319              : }
    6320              : 
    6321              : // Judges the gap and the rate floor of a parked response. The reactor only
    6322              : // wakes such a connection when a large part of the send buffer has drained, so
    6323              : // the wakeup doesn't measure a steady reader's progress; the send queue does. A
    6324              : // queue that shrank since the park or the last tick resets the gap (it updates
    6325              : // c->wp_outq and c->last_progress). For TCP the floor counts the bytes that
    6326              : // reached the reader (accepted minus queued). For unix:// the kernel reports
    6327              : // buffer memory instead of bytes, so the floor counts accepted bytes there.
    6328              : // gap_hit says whether the gap had run out before the queue was read. The
    6329              : // caller owns c, and calls it with no lock held (see
    6330              : // parked_needs_kernel_query).
    6331          142 : static bool parked_write_expired(struct chttpserver *srv, chttpsvr_conn *c,
    6332              :                                  struct timespec now_slow, bool gap_hit) {
    6333          142 :   unsigned rate = atomic_load(&srv->min_rate_bps);
    6334          142 :   bool rate_on = rate != UINT_MAX && c->rate_active;
    6335          142 :   if (!gap_hit && !rate_on) return false;
    6336          140 :   size_t outq = conn_send_queue(c);
    6337          140 :   if (outq == SIZE_MAX) return gap_hit || rate_below_floor(srv, c, now_slow, 0);
    6338          140 :   if (outq < c->wp_outq) {
    6339          126 :     c->wp_outq = outq;
    6340          126 :     c->last_progress = now_slow;
    6341          126 :     gap_hit = false;
    6342              :   }
    6343          140 :   if (!rate_on) return gap_hit;
    6344          140 :   if (atomic_load(&srv->is_unix_socket))
    6345            0 :     return gap_hit || rate_below_floor(srv, c, now_slow, 0);
    6346          280 :   uint64_t delivered =
    6347          140 :       c->rate_bytes > (uint64_t)outq ? c->rate_bytes - (uint64_t)outq : 0;
    6348          280 :   return gap_hit ||
    6349          139 :          rate_elapsed_ms(c, now_slow) >
    6350          278 :              rate_allowed_ms(rate, atomic_load(&srv->rate_grace_ms), delivered);
    6351              : }
    6352              : 
    6353              : // Whether parked_expired would have to ask the kernel about c before deciding:
    6354              : // a parked response with the gap hit or the rate floor on, or a parked body
    6355              : // that looks stalled while bytes may sit below its low-water mark. The sweep
    6356              : // calls it with srv->idle_mutex held, and it makes no system call. A connection
    6357              : // it returns true for is claimed and judged after the unlock, so kernel queries
    6358              : // never run under the lock every dispatch and park takes.
    6359           43 : static bool parked_needs_kernel_query(struct chttpserver *srv,
    6360              :                                       const chttpsvr_conn *c,
    6361              :                                       struct timespec now,
    6362              :                                       struct timespec now_slow) {
    6363           43 :   unsigned gap;
    6364           43 :   if (c->park == CONN_PARK_BODY) {
    6365           26 :     if (c->read_deadline_set && timespec_reached(now, c->read_deadline))
    6366              :       return false;
    6367           26 :     if (c->rcvlowat <= 1) return false;
    6368           25 :     gap = atomic_load(&srv->stream_read_timeout_ms);
    6369           17 :   } else if (c->park == CONN_PARK_WRITE) {
    6370           12 :     if (c->write_deadline_set && timespec_reached(now, c->write_deadline))
    6371              :       return false;
    6372           10 :     gap = atomic_load(&srv->response_write_timeout_ms);
    6373              :   } else {
    6374              :     return false;
    6375              :   }
    6376           35 :   bool gap_hit = gap && ms_since(now_slow, c->last_progress) >= (long long)gap;
    6377           35 :   if (c->park == CONN_PARK_WRITE)
    6378           20 :     return gap_hit ||
    6379            9 :            (atomic_load(&srv->min_rate_bps) != UINT_MAX && c->rate_active);
    6380           33 :   return gap_hit || rate_below_floor(srv, c, now_slow, c->rate_queued);
    6381              : }
    6382              : 
    6383              : // Whether a parked connection broke one of its limits. A parked body answers to
    6384              : // the gap since its last byte, its total read deadline and the rate floor; a
    6385              : // parked response to its gap, total write deadline and rate floor; a lingering
    6386              : // connection to its linger deadline. The deadlines use now (CLOCK_MONOTONIC),
    6387              : // the gap and floor use now_slow. For a body with a low-water mark above 1,
    6388              : // bytes waiting below the mark count as progress (FIONREAD). The caller owns c
    6389              : // (it claimed it, or it's the sweep under srv->idle_mutex with
    6390              : // parked_needs_kernel_query false) and may update its rate state.
    6391          489 : static bool parked_expired(struct chttpserver *srv, chttpsvr_conn *c,
    6392              :                            struct timespec now, struct timespec now_slow) {
    6393          489 :   unsigned gap;
    6394          489 :   if (c->park == CONN_PARK_BODY) {
    6395          340 :     if (c->read_deadline_set && timespec_reached(now, c->read_deadline))
    6396              :       return true;
    6397          340 :     gap = atomic_load(&srv->stream_read_timeout_ms);
    6398          149 :   } else if (c->park == CONN_PARK_WRITE) {
    6399          144 :     if (c->write_deadline_set && timespec_reached(now, c->write_deadline))
    6400              :       return true;
    6401          142 :     gap = atomic_load(&srv->response_write_timeout_ms);
    6402            5 :   } else if (c->park == CONN_PARK_LINGER) {
    6403            9 :     return timespec_reached(now, c->linger_deadline);
    6404              :   } else {
    6405              :     return false;
    6406              :   }
    6407          482 :   bool gap_hit = gap && ms_since(now_slow, c->last_progress) >= (long long)gap;
    6408          482 :   if (c->park == CONN_PARK_WRITE)
    6409          142 :     return parked_write_expired(srv, c, now_slow, gap_hit);
    6410          340 :   bool rate_hit = rate_below_floor(srv, c, now_slow, c->rate_queued);
    6411          340 :   if ((gap_hit || rate_hit) && c->rcvlowat > 1) {
    6412              : #ifdef RUNNING_UNIT_TESTS
    6413            8 :     parked_query_note_for_tests();
    6414              : #endif
    6415            8 :     int queued = 0;
    6416            8 :     if (ioctl(c->fd, FIONREAD, &queued) == 0 && queued > 0 &&
    6417            0 :         (size_t)queued > c->rate_queued) {
    6418            0 :       c->rate_queued = (size_t)queued;
    6419            0 :       c->last_progress = now_slow;
    6420            0 :       gap_hit = false;
    6421            0 :       rate_hit = rate_below_floor(srv, c, now_slow, c->rate_queued);
    6422              :     }
    6423              :   }
    6424          340 :   return gap_hit || rate_hit;
    6425              : }
    6426              : 
    6427              : // Records, on both clocks, when conn leaves a wait for the worker pool, so
    6428              : // conn_uncharge_queue_wait can take the time in the pool queue off its limits.
    6429          447 : static void conn_stamp_claim(chttpsvr_conn *conn) {
    6430          447 :   clock_gettime(CLOCK_MONOTONIC, &conn->claim_mono);
    6431          447 :   slow_clock(&conn->claim_slow);
    6432              : }
    6433              : 
    6434              : // Takes the time conn spent in the worker pool's queue since its claim off
    6435              : // every limit of the phase it resumes: The rate floor, the gap and the total
    6436              : // read or write deadline. A client whose bytes already arrived is never charged
    6437              : // for how long the server took to get to them.
    6438          446 : static void conn_uncharge_queue_wait(chttpsvr_conn *conn, struct timespec now,
    6439              :                                      struct timespec now_slow) {
    6440          446 :   long long waited = ms_since_ceil(now_slow, conn->claim_slow);
    6441          446 :   if (waited > 0) {
    6442          446 :     unsigned w = waited > (long long)UINT_MAX ? UINT_MAX : (unsigned)waited;
    6443          446 :     conn->rate_paused_ms += waited;
    6444          892 :     timespec_add_ms(&conn->last_progress, w);
    6445              :   }
    6446          446 :   long long waited_mono = ms_since_ceil(now, conn->claim_mono);
    6447          446 :   if (waited_mono > 0) {
    6448          446 :     unsigned w =
    6449          446 :         waited_mono > (long long)UINT_MAX ? UINT_MAX : (unsigned)waited_mono;
    6450          446 :     if (conn->read_deadline_set) timespec_add_ms(&conn->read_deadline, w);
    6451          446 :     if (conn->write_deadline_set) timespec_add_ms(&conn->write_deadline, w);
    6452              :   }
    6453          446 : }
    6454              : 
    6455              : // Whether need more bytes fit under srv's body memory limit. mem_in_use can be
    6456              : // above the limit while a connection runs past it under the progress rule,
    6457              : // hence the guarded subtraction. The caller holds srv->wait_mutex.
    6458          242 : static bool mem_fits_locked(struct chttpserver *srv, size_t need) {
    6459          242 :   size_t cap = atomic_load(&srv->mem_cap);
    6460          242 :   return srv->mem_in_use <= cap && need <= cap - srv->mem_in_use;
    6461              : }
    6462              : 
    6463              : #ifdef RUNNING_UNIT_TESTS
    6464              : // Test hook: The highest mem_in_use any server reached since the last reset,
    6465              : // for the test of the progress rule's bound.
    6466              : static _Atomic size_t g_mem_peak_for_tests = 0;
    6467            3 : size_t chttpsvr__mem_peak_for_tests(void) {
    6468            3 :   return atomic_load(&g_mem_peak_for_tests);
    6469              : }
    6470            3 : void chttpsvr__mem_peak_reset_for_tests(void) {
    6471            3 :   atomic_store(&g_mem_peak_for_tests, 0);
    6472            3 : }
    6473              : #endif
    6474              : 
    6475              : #ifdef RUNNING_UNIT_TESTS
    6476              : // Test hook: Since the last reset, the most a reserved body buffer ever held
    6477              : // beyond its reservation, with the old and new blocks of a growth counted
    6478              : // together. body_growth_note_for_tests updates it at each growth.
    6479              : static _Atomic size_t g_body_overshoot_for_tests = 0;
    6480            3 : size_t chttpsvr__body_overshoot_for_tests(void) {
    6481            3 :   return atomic_load(&g_body_overshoot_for_tests);
    6482              : }
    6483            2 : void chttpsvr__body_overshoot_reset_for_tests(void) {
    6484            2 :   atomic_store(&g_body_overshoot_for_tests, 0);
    6485            2 : }
    6486          268 : static void body_growth_note_for_tests(const chttpsvr_conn *conn,
    6487              :                                        size_t old_cap, size_t new_cap) {
    6488          268 :   if (conn->mem_charged == 0 || conn->mem_exempt) return;
    6489          201 :   size_t held = old_cap + new_cap;
    6490          201 :   if (held <= conn->mem_charged) return;
    6491            0 :   size_t over = held - conn->mem_charged;
    6492            0 :   size_t prev = atomic_load(&g_body_overshoot_for_tests);
    6493            0 :   while (over > prev && !atomic_compare_exchange_weak(
    6494              :                             &g_body_overshoot_for_tests, &prev, over)) {
    6495            0 :   }
    6496              : }
    6497              : #endif
    6498              : 
    6499              : // Charges need bytes of body memory to c, counting c as a holder at its first
    6500              : // charge. A charge above the whole limit counts as the limit, since such a
    6501              : // request can only run under the progress rule anyway, and the sum saturates so
    6502              : // mem_in_use never wraps (with max_body_size 0 a body can declare almost
    6503              : // SIZE_MAX bytes). The caller holds srv->wait_mutex.
    6504          222 : static void mem_grant_locked(struct chttpserver *srv, chttpsvr_conn *c,
    6505              :                              size_t need) {
    6506          222 :   size_t cap = atomic_load(&srv->mem_cap);
    6507          222 :   if (need > cap) need = cap;
    6508          222 :   if (need > SIZE_MAX - srv->mem_in_use) need = SIZE_MAX - srv->mem_in_use;
    6509          222 :   if (need == 0) return;
    6510          222 :   if (c->mem_charged == 0) srv->mem_holders++;
    6511          222 :   c->mem_charged += need;
    6512          222 :   srv->mem_in_use += need;
    6513              : #ifdef RUNNING_UNIT_TESTS
    6514          222 :   size_t peak = atomic_load(&g_mem_peak_for_tests);
    6515          285 :   while (srv->mem_in_use > peak &&
    6516           63 :          !atomic_compare_exchange_weak(&g_mem_peak_for_tests, &peak,
    6517              :                                        srv->mem_in_use)) {
    6518          222 :   }
    6519              : #endif
    6520              : }
    6521              : 
    6522              : // Reserves need more bytes for conn if they fit right now, and returns whether
    6523              : // it did. A reservation never jumps ahead of a request already waiting, so
    6524              : // small requests can't starve a big one; a connection exempt under the progress
    6525              : // rule always gets it. Takes srv->wait_mutex. Its owner holds conn.
    6526          227 : static bool mem_try_reserve(struct chttpserver *srv, chttpsvr_conn *conn,
    6527              :                             size_t need) {
    6528          227 :   ccol__mutex_lock(srv->wait_mutex);
    6529          227 :   bool ok = conn->mem_exempt || (!srv->mem_head && mem_fits_locked(srv, need));
    6530          212 :   if (ok) mem_grant_locked(srv, conn, need);
    6531          227 :   ccol__mutex_unlock(srv->wait_mutex);
    6532          227 :   return ok;
    6533              : }
    6534              : 
    6535              : // Puts conn at the tail of the memory-wait list with park set to kind and need
    6536              : // bytes wanted. It's the owner's last touch of conn, because from the unlock of
    6537              : // srv->wait_mutex on an admission on another thread may take it.
    6538           15 : static void mem_wait_enqueue(struct chttpserver *srv, chttpsvr_conn *conn,
    6539              :                              size_t need, uint8_t kind) {
    6540           15 :   slow_clock(&conn->mem_wait_start);
    6541           15 :   conn->park = kind;
    6542           15 :   conn->mem_need = need;
    6543           15 :   ccol__mutex_lock(srv->wait_mutex);
    6544           15 :   conn->mem_prev = srv->mem_tail;
    6545           15 :   conn->mem_next = NULL;
    6546           15 :   if (srv->mem_tail)
    6547            1 :     srv->mem_tail->mem_next = conn;
    6548              :   else
    6549           14 :     srv->mem_head = conn;
    6550           15 :   srv->mem_tail = conn;
    6551           15 :   conn->in_mem_wait = true;
    6552           15 :   srv->mem_waiting++;
    6553           15 :   if (conn->mem_charged) srv->mem_blocked++;
    6554           15 :   ccol__mutex_unlock(srv->wait_mutex);
    6555           15 : }
    6556              : 
    6557              : // Unlinks c from the memory-wait list, which is what claims it, and updates the
    6558              : // waiter counts. The caller holds srv->wait_mutex.
    6559           15 : static void mem_wait_unlink_locked(struct chttpserver *srv, chttpsvr_conn *c) {
    6560           15 :   if (c->mem_prev) c->mem_prev->mem_next = c->mem_next;
    6561           15 :   if (c->mem_next) c->mem_next->mem_prev = c->mem_prev;
    6562           15 :   if (srv->mem_head == c) srv->mem_head = c->mem_next;
    6563           15 :   if (srv->mem_tail == c) srv->mem_tail = c->mem_prev;
    6564           15 :   c->mem_prev = c->mem_next = NULL;
    6565           15 :   c->in_mem_wait = false;
    6566           15 :   srv->mem_waiting--;
    6567           15 :   if (c->mem_charged) srv->mem_blocked--;
    6568           15 : }
    6569              : 
    6570              : static void mem_admit(struct chttpserver *srv);
    6571              : 
    6572              : // Gives back conn's whole body memory reservation and ends its progress-rule
    6573              : // exemption, then admits whatever the freed memory allows. conn_drop_body calls
    6574              : // it as it frees the body (handler returned, request refused or connection
    6575              : // closing). Takes srv->wait_mutex, and runs mem_admit after the unlock.
    6576          122 : static __attribute__((noinline, cold)) void mem_release(chttpsvr_conn *conn) {
    6577          122 :   struct chttpserver *srv = conn->srv;
    6578          122 :   ccol__mutex_lock(srv->wait_mutex);
    6579          122 :   if (conn->mem_charged) {
    6580          122 :     srv->mem_in_use -= conn->mem_charged;
    6581          122 :     srv->mem_holders--;
    6582          122 :     conn->mem_charged = 0;
    6583              :   }
    6584          122 :   if (conn->mem_exempt) {
    6585            5 :     conn->mem_exempt = false;
    6586            5 :     srv->mem_exempt_active = false;
    6587              :   }
    6588          122 :   bool waiters = srv->mem_head != NULL;
    6589          122 :   ccol__mutex_unlock(srv->wait_mutex);
    6590          122 :   if (waiters) mem_admit(srv);
    6591          122 : }
    6592              : 
    6593              : // Gives back the part of conn's reservation above keep bytes, which a body
    6594              : // doesn't need once a growth freed the old block or while it's parked, and
    6595              : // admits waiters if that freed anything. conn's owner calls it.
    6596           98 : static __attribute__((noinline, cold)) void mem_trim(chttpsvr_conn *conn,
    6597              :                                                      size_t keep) {
    6598           98 :   struct chttpserver *srv = conn->srv;
    6599           98 :   ccol__mutex_lock(srv->wait_mutex);
    6600           98 :   bool freed = false;
    6601           98 :   if (conn->mem_charged > keep) {
    6602           98 :     srv->mem_in_use -= conn->mem_charged - keep;
    6603           98 :     if (keep == 0) srv->mem_holders--;
    6604           98 :     conn->mem_charged = keep;
    6605           98 :     freed = true;
    6606              :   }
    6607           98 :   bool waiters = freed && srv->mem_head != NULL;
    6608           98 :   ccol__mutex_unlock(srv->wait_mutex);
    6609           98 :   if (waiters) mem_admit(srv);
    6610           98 : }
    6611              : 
    6612              : // Once conn's body stopped arriving, trims its reservation to what the buffer
    6613              : // really holds, because a short read leaves a reserved growth unused. A
    6614              : // connection running under the progress rule may hold more and keeps it.
    6615          892 : static inline __attribute__((always_inline)) void mem_settle(
    6616              :     chttpsvr_conn *conn) {
    6617          892 :   if (__builtin_expect(conn->mem_charged > conn->body.cap, 0))
    6618            4 :     mem_trim(conn, conn->body.cap);
    6619              : }
    6620              : 
    6621              : // Hands a waiter that mem_admit admitted to the worker pool. A request that
    6622              : // waited before its body started goes to task_worker as if it had just
    6623              : // diverted; a body that waited for more memory goes to task_resume, with the
    6624              : // wait taken off its rate floor, gap and read deadline, since the wait was the
    6625              : // server's time. It puts conn in the diverted list and counts it in
    6626              : // in_flight_requests. A full pool answers 503, as no response byte has gone out
    6627              : // yet.
    6628           10 : static void mem_dispatch(chttpsvr_conn *conn) {
    6629           10 :   struct chttpserver *srv = conn->srv;
    6630           10 :   void (*fn)(void *) = task_worker;
    6631           10 :   if (conn->park == CONN_PARK_MEM_BODY) {
    6632            6 :     struct timespec now;
    6633            6 :     slow_clock(&now);
    6634            6 :     long long waited = ms_since_ceil(now, conn->mem_wait_start);
    6635            6 :     if (waited < 0) waited = 0;
    6636            6 :     conn->rate_paused_ms += waited;
    6637            6 :     conn->last_progress = now;
    6638            6 :     if (conn->read_deadline_set)
    6639           12 :       timespec_add_ms(&conn->read_deadline, waited > (long long)UINT_MAX
    6640              :                                                 ? UINT_MAX
    6641              :                                                 : (unsigned)waited);
    6642            6 :     conn->park = CONN_PARK_BODY;
    6643            6 :     fn = task_resume;
    6644           12 :     conn_stamp_claim(conn);
    6645              :   } else {
    6646            4 :     conn->park = CONN_PARK_NONE;
    6647              :   }
    6648           10 :   conn->state = CONN_ST_DIVERTED;
    6649           10 :   diverted_list_add(conn);
    6650           10 :   ccol__mutex_lock(srv->mutex);
    6651           10 :   srv->in_flight_requests++;
    6652           10 :   cthrpool pool = srv->worker_pool;
    6653           10 :   ccol__mutex_unlock(srv->mutex);
    6654           10 :   if (!srv_submit(srv, SRV_POOL_WORKER, pool, fn, conn)) {
    6655            0 :     conn->park = CONN_PARK_NONE;
    6656            0 :     conn->req_rejected = true;
    6657            0 :     conn->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    6658            0 :     conn_reject_via_pool(conn);
    6659              :   }
    6660           10 : }
    6661              : 
    6662              : // Admits waiters from the head of the memory-wait list, oldest first, as long
    6663              : // as the head fits under the limit. When the head doesn't fit and every holder
    6664              : // of a reservation is itself waiting, nothing could ever free memory, so the
    6665              : // progress rule lets the head go past the limit until its body is freed; only
    6666              : // one connection is exempt at a time (srv->mem_exempt_active).
    6667              : // This can't deadlock: A holder outside the list is a body arriving, a refusal
    6668              : // or a running handler, and each ends and frees its body, which calls this
    6669              : // again; with no holder outside, the head goes through. The overshoot stays
    6670              : // below twice max_body_size (or twice one declared length when that is 0). A
    6671              : // handler that waits for another request is the one dependency the server can't
    6672              : // see; that request waits until its memory deadline or until a handler returns.
    6673              : // srv->wait_mutex is never held across a dispatch, and only one admission loop
    6674              : // runs at a time: A call that finds one running sets mem_admit_again and
    6675              : // returns.
    6676           26 : static void mem_admit(struct chttpserver *srv) {
    6677           26 :   ccol__mutex_lock(srv->wait_mutex);
    6678           26 :   if (srv->mem_admitting) {
    6679            0 :     srv->mem_admit_again = true;
    6680            0 :     ccol__mutex_unlock(srv->wait_mutex);
    6681            0 :     return;
    6682              :   }
    6683           26 :   srv->mem_admitting = true;
    6684            9 :   for (;;) {
    6685           35 :     chttpsvr_conn *batch[CHTTPSVR_IDLE_CLOSE_BATCH];
    6686           35 :     size_t n = 0;
    6687           35 :     srv->mem_admit_again = false;
    6688           45 :     while (!srv->mem_admission_closed && srv->mem_head &&
    6689              :            n < CHTTPSVR_IDLE_CLOSE_BATCH) {
    6690           22 :       chttpsvr_conn *c = srv->mem_head;
    6691           22 :       bool fits = mem_fits_locked(srv, c->mem_need);
    6692           22 :       bool ahead = !fits && !srv->mem_exempt_active &&
    6693           15 :                    srv->mem_holders == srv->mem_blocked;
    6694           22 :       if (!fits && !ahead) break;
    6695           10 :       mem_wait_unlink_locked(srv, c);
    6696           10 :       mem_grant_locked(srv, c, c->mem_need);
    6697           10 :       if (ahead) {
    6698            5 :         c->mem_exempt = true;
    6699            5 :         srv->mem_exempt_active = true;
    6700              :       }
    6701           10 :       batch[n++] = c;
    6702              :     }
    6703           35 :     if (n == 0 && !srv->mem_admit_again) break;
    6704            9 :     ccol__mutex_unlock(srv->wait_mutex);
    6705           19 :     for (size_t i = 0; i < n; i++) mem_dispatch(batch[i]);
    6706            9 :     ccol__mutex_lock(srv->wait_mutex);
    6707              :   }
    6708           26 :   srv->mem_admitting = false;
    6709           26 :   ccol__mutex_unlock(srv->wait_mutex);
    6710              : }
    6711              : 
    6712              : // Stops mem_admit from dispatching, for a server's teardown.
    6713          563 : static void mem_admission_close(struct chttpserver *srv) {
    6714          563 :   ccol__mutex_lock(srv->wait_mutex);
    6715          563 :   srv->mem_admission_closed = true;
    6716          563 :   ccol__mutex_unlock(srv->wait_mutex);
    6717              : }
    6718              : 
    6719              : // Closes every waiter of the memory-wait list for a server's teardown, claiming
    6720              : // each one under srv->wait_mutex before it closes it outside the lock.
    6721          719 : static void mem_wait_flush(struct chttpserver *srv) {
    6722          723 :   for (;;) {
    6723          721 :     chttpsvr_conn *batch[CHTTPSVR_IDLE_CLOSE_BATCH];
    6724          721 :     size_t n = 0;
    6725          721 :     ccol__mutex_lock(srv->wait_mutex);
    6726          723 :     while (srv->mem_head && n < CHTTPSVR_IDLE_CLOSE_BATCH) {
    6727            2 :       chttpsvr_conn *c = srv->mem_head;
    6728            2 :       mem_wait_unlink_locked(srv, c);
    6729            2 :       batch[n++] = c;
    6730              :     }
    6731          721 :     ccol__mutex_unlock(srv->wait_mutex);
    6732          721 :     if (n == 0) return;
    6733            4 :     for (size_t i = 0; i < n; i++) {
    6734            2 :       batch[i]->park = CONN_PARK_NONE;
    6735            2 :       conn_close(batch[i]);
    6736              :     }
    6737              :   }
    6738              : }
    6739              : 
    6740              : #ifdef RUNNING_UNIT_TESTS
    6741              : // Test hooks of the streaming pool. g_stream_pool_threads_for_tests holds the
    6742              : // thread count of the pool stream_pool_get created last (0 once taken). The
    6743              : // start hold makes the next chttpsvr_start wait after it swapped in the new
    6744              : // run's pools and released srv->mutex; the create hold makes the next
    6745              : // stream_pool_get that builds a pool wait after it read the size. Both wait for
    6746              : // the test's release, 10 seconds at most. The functions below arm, query and
    6747              : // release them.
    6748              : static _Atomic int g_stream_pool_threads_for_tests = 0;
    6749              : static _Atomic bool g_start_hold_armed_for_tests = false;
    6750              : static _Atomic bool g_start_hold_entered_for_tests = false;
    6751              : static _Atomic bool g_start_hold_release_for_tests = false;
    6752              : 
    6753            8 : int chttpsvr__take_stream_pool_threads_for_tests(void) {
    6754            8 :   return atomic_exchange(&g_stream_pool_threads_for_tests, 0);
    6755              : }
    6756              : 
    6757              : static _Atomic bool g_stream_create_hold_armed_for_tests = false;
    6758              : static _Atomic bool g_stream_create_hold_entered_for_tests = false;
    6759              : static _Atomic bool g_stream_create_hold_release_for_tests = false;
    6760              : 
    6761           34 : static void stream_pool_create_hold_for_tests(void) {
    6762           34 :   if (!atomic_exchange(&g_stream_create_hold_armed_for_tests, false)) return;
    6763            1 :   atomic_store(&g_stream_create_hold_entered_for_tests, true);
    6764            1 :   struct timespec ts = {0, 1000000L};
    6765            1 :   for (int i = 0;
    6766            3 :        i < 10000 && !atomic_load(&g_stream_create_hold_release_for_tests); i++)
    6767            2 :     nanosleep(&ts, NULL);
    6768              : }
    6769              : 
    6770            1 : void chttpsvr__arm_stream_create_hold_for_tests(void) {
    6771            1 :   atomic_store(&g_stream_create_hold_entered_for_tests, false);
    6772            1 :   atomic_store(&g_stream_create_hold_release_for_tests, false);
    6773            1 :   atomic_store(&g_stream_create_hold_armed_for_tests, true);
    6774            1 : }
    6775              : 
    6776            2 : bool chttpsvr__stream_create_hold_entered_for_tests(void) {
    6777            2 :   return atomic_load(&g_stream_create_hold_entered_for_tests);
    6778              : }
    6779              : 
    6780            2 : void chttpsvr__release_stream_create_hold_for_tests(void) {
    6781            2 :   atomic_store(&g_stream_create_hold_armed_for_tests, false);
    6782            2 :   atomic_store(&g_stream_create_hold_release_for_tests, true);
    6783            2 : }
    6784              : 
    6785            1 : void chttpsvr__arm_start_hold_for_tests(void) {
    6786            1 :   atomic_store(&g_start_hold_entered_for_tests, false);
    6787            1 :   atomic_store(&g_start_hold_release_for_tests, false);
    6788            1 :   atomic_store(&g_start_hold_armed_for_tests, true);
    6789            1 : }
    6790              : 
    6791            2 : bool chttpsvr__start_hold_entered_for_tests(void) {
    6792            2 :   return atomic_load(&g_start_hold_entered_for_tests);
    6793              : }
    6794              : 
    6795            1 : void chttpsvr__release_start_hold_for_tests(void) {
    6796            1 :   atomic_store(&g_start_hold_armed_for_tests, false);
    6797            1 :   atomic_store(&g_start_hold_release_for_tests, true);
    6798            1 : }
    6799              : 
    6800          322 : static void start_hold_for_tests(void) {
    6801          322 :   if (!atomic_exchange(&g_start_hold_armed_for_tests, false)) return;
    6802            1 :   atomic_store(&g_start_hold_entered_for_tests, true);
    6803            1 :   struct timespec ts = {0, 1000000};
    6804            3 :   for (int i = 0; i < 10000 && !atomic_load(&g_start_hold_release_for_tests);
    6805            2 :        i++)
    6806            2 :     nanosleep(&ts, NULL);
    6807              : }
    6808              : #endif
    6809              : 
    6810              : // Returns srv's streaming pool, creating it on the first streaming request
    6811              : // after a start, so a server that never gets one starts no threads for it. The
    6812              : // size is read with stream_gen under srv->mutex, and the pool is built outside
    6813              : // the lock and installed only while the run is unchanged; a creator that loses
    6814              : // the race destroys its pool, and one that saw a restart builds again with the
    6815              : // new size. A server that isn't running or was just detached gets
    6816              : // CTHRPOOL_NULL.
    6817          175 : static cthrpool stream_pool_get(struct chttpserver *srv) {
    6818          177 :   for (;;) {
    6819          176 :     ccol__mutex_lock(srv->mutex);
    6820          176 :     cthrpool pool = srv->stream_pool;
    6821          176 :     bool running = srv->worker_pool != CTHRPOOL_NULL;
    6822          176 :     uint64_t gen = atomic_load(&srv->stream_gen);
    6823          176 :     int nthreads = atomic_load(&srv->stream_threads);
    6824          176 :     ccol__mutex_unlock(srv->mutex);
    6825          176 :     if (pool || !running) return pool;
    6826           34 :     if (nthreads <= 0) return CTHRPOOL_NULL;
    6827              : 
    6828              : #ifdef RUNNING_UNIT_TESTS
    6829           34 :     stream_pool_create_hold_for_tests();
    6830              : #endif
    6831           34 :     char *err = NULL;
    6832           68 :     cthrpool fresh =
    6833           34 :         cthrpool_create_mp((size_t)nthreads, 0, srv->m_procs, &err);
    6834           34 :     if (!fresh) return CTHRPOOL_NULL;
    6835           34 :     ccol__mutex_lock(srv->mutex);
    6836           34 :     bool same_run = atomic_load(&srv->stream_gen) == gen;
    6837           34 :     if (same_run && !srv->stream_pool && srv->worker_pool != CTHRPOOL_NULL) {
    6838           33 :       srv->stream_pool = fresh;
    6839           33 :       fresh = CTHRPOOL_NULL;
    6840              :     }
    6841           34 :     pool = srv->stream_pool;
    6842           34 :     ccol__mutex_unlock(srv->mutex);
    6843           34 :     if (fresh) {
    6844            1 :       cthrpool_shutdown_drain(fresh);
    6845            1 :       cthrpool_destroy(fresh);
    6846            1 :       if (!same_run) continue;
    6847              :     }
    6848              : #ifdef RUNNING_UNIT_TESTS
    6849           33 :     else if (pool)
    6850           33 :       atomic_store(&g_stream_pool_threads_for_tests, nthreads);
    6851              : #endif
    6852              :     return pool;
    6853              :   }
    6854              : }
    6855              : 
    6856              : // Answers 503 to a request no pool can take (a streaming request the streaming
    6857              : // pool refuses or a parked body the worker pool refuses). The connection
    6858              : // already holds its in_flight_requests slot and is in the diverted list.
    6859            5 : static void conn_reject_busy(chttpsvr_conn *conn) {
    6860            5 :   conn->park = CONN_PARK_NONE;
    6861            5 :   conn->req_rejected = true;
    6862            5 :   conn->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    6863            5 :   conn_reject_via_pool(conn);
    6864            2 : }
    6865              : 
    6866              : // Unlinks c from the streaming queue, which claims it. The caller holds
    6867              : // srv->wait_mutex.
    6868           91 : static void stream_unlink_locked(struct chttpserver *srv, chttpsvr_conn *c) {
    6869           91 :   if (c->sq_prev) c->sq_prev->sq_next = c->sq_next;
    6870           91 :   if (c->sq_next) c->sq_next->sq_prev = c->sq_prev;
    6871           91 :   if (srv->sq_head == c) srv->sq_head = c->sq_next;
    6872           91 :   if (srv->sq_tail == c) srv->sq_tail = c->sq_prev;
    6873           91 :   c->sq_prev = c->sq_next = NULL;
    6874           91 :   c->in_stream_queue = false;
    6875           91 :   srv->sq_len--;
    6876           91 : }
    6877              : 
    6878              : static void stream_token_task(void *arg);
    6879              : static void stream_queue_flush(struct chttpserver *srv);
    6880              : 
    6881              : // What a stream_token_task receives: Its server, and the stream_gen of the run
    6882              : // it was counted for in sq_tokens.
    6883              : typedef struct {
    6884              :   struct chttpserver *srv;
    6885              :   uint64_t gen;
    6886              : } stream_token_arg;
    6887              : 
    6888              : static bool stream_token_start_one(struct chttpserver *srv);
    6889              : 
    6890              : // Starts streaming tasks on the current run's pool while the queue holds more
    6891              : // requests than the run has tasks on their way to it (sq_unclaimed), and fewer
    6892              : // tasks are counted than the pool has threads, so a queued request costs at
    6893              : // most one new task and the pool's own queue never holds more tasks than
    6894              : // threads.
    6895          437 : static void stream_token_start(struct chttpserver *srv) {
    6896          957 :   while (stream_token_start_one(srv)) {
    6897          520 :   }
    6898            0 : }
    6899              : 
    6900              : #ifdef RUNNING_UNIT_TESTS
    6901              : // Test hook: Counts the streaming tasks submitted by every server of the
    6902              : // process.
    6903              : static _Atomic size_t g_stream_tokens_started_for_tests = 0;
    6904              : 
    6905            4 : size_t chttpsvr__stream_tokens_started_for_tests(void) {
    6906            4 :   return atomic_load(&g_stream_tokens_started_for_tests);
    6907              : }
    6908              : #endif
    6909              : 
    6910              : // One step of stream_token_start: Counts and submits one task when the
    6911              : // conditions above hold, and returns true when it did. The pool is read after
    6912              : // stream_gen, so a task counted for one run never goes to an earlier run's
    6913              : // pool. When no pool takes the task (a pool in shutdown, no running server, a
    6914              : // failed allocation), it undoes its count if the run is unchanged; if no other
    6915              : // task of that run is left, every queued request gets a 503, and if the run
    6916              : // changed, the next run gets its own start. Takes srv->wait_mutex.
    6917          520 : static bool stream_token_start_one(struct chttpserver *srv) {
    6918          520 :   size_t nthreads = (size_t)atomic_load(&srv->stream_threads);
    6919          520 :   ccol__mutex_lock(srv->wait_mutex);
    6920          520 :   bool submit = srv->sq_head != NULL && srv->sq_unclaimed < srv->sq_len &&
    6921           94 :                 srv->sq_tokens < nthreads;
    6922          520 :   uint64_t gen = atomic_load(&srv->stream_gen);
    6923          520 :   if (submit) {
    6924           83 :     srv->sq_tokens++;
    6925           83 :     srv->sq_unclaimed++;
    6926              :   }
    6927          520 :   ccol__mutex_unlock(srv->wait_mutex);
    6928          520 :   if (!submit) return false;
    6929           83 :   cthrpool pool = stream_pool_get(srv);
    6930          166 :   stream_token_arg *arg =
    6931           83 :       pool ? (stream_token_arg *)ccol__mem_alloc(srv->m_procs, sizeof(*arg))
    6932           83 :            : NULL;
    6933           83 :   if (arg) {
    6934           83 :     arg->srv = srv;
    6935           83 :     arg->gen = gen;
    6936              : #ifdef RUNNING_UNIT_TESTS
    6937           83 :     atomic_fetch_add(&g_stream_tokens_started_for_tests, 1);
    6938              : #endif
    6939           83 :     if (srv_submit(srv, SRV_POOL_STREAM, pool, stream_token_task, arg))
    6940           83 :       return true;
    6941              : #ifdef RUNNING_UNIT_TESTS
    6942            0 :     atomic_fetch_sub(&g_stream_tokens_started_for_tests, 1);
    6943              : #endif
    6944            0 :     ccol__mem_free(srv->m_procs, arg);
    6945              :   }
    6946            0 :   ccol__mutex_lock(srv->wait_mutex);
    6947            0 :   bool same_run = atomic_load(&srv->stream_gen) == gen;
    6948            0 :   if (same_run) {
    6949            0 :     srv->sq_tokens--;
    6950            0 :     srv->sq_unclaimed--;
    6951              :   }
    6952            0 :   bool orphaned = same_run && srv->sq_tokens == 0;
    6953            0 :   ccol__mutex_unlock(srv->wait_mutex);
    6954            0 :   if (orphaned)
    6955            0 :     stream_queue_flush(srv);
    6956            0 :   else if (!same_run)
    6957            0 :     stream_token_start(srv);
    6958              :   return false;
    6959              : }
    6960              : 
    6961              : // Puts a streaming request into the streaming queue with its queue deadline and
    6962              : // starts a task for it. The connection keeps its in_flight_requests slot, its
    6963              : // place in the diverted list and its paused registration, so a teardown sees
    6964              : // it, but it holds no thread. No pool or a full queue answers 503 at once; the
    6965              : // call never blocks. From the unlock on, conn may already run on the streaming
    6966              : // pool.
    6967           92 : static void stream_enqueue(chttpsvr_conn *conn) {
    6968           92 :   struct chttpserver *srv = conn->srv;
    6969           92 :   cthrpool pool = stream_pool_get(srv);
    6970           92 :   if (!pool) {
    6971            0 :     conn_reject_busy(conn);
    6972            0 :     return;
    6973              :   }
    6974           92 :   size_t qcap = atomic_load(&srv->stream_qcap);
    6975           92 :   unsigned tmo = atomic_load(&srv->stream_qtimeout_ms);
    6976           92 :   conn->park = CONN_PARK_STREAM;
    6977           92 :   conn->sq_has_deadline = tmo != UINT_MAX;
    6978           92 :   if (conn->sq_has_deadline) {
    6979           92 :     slow_clock(&conn->sq_deadline);
    6980          184 :     timespec_add_ms(&conn->sq_deadline, tmo);
    6981              :   }
    6982              : 
    6983           92 :   ccol__mutex_lock(srv->wait_mutex);
    6984           92 :   if (qcap != SIZE_MAX && srv->sq_len >= qcap) {
    6985            1 :     ccol__mutex_unlock(srv->wait_mutex);
    6986            1 :     conn_reject_busy(conn);
    6987            1 :     return;
    6988              :   }
    6989           91 :   conn->sq_prev = srv->sq_tail;
    6990           91 :   conn->sq_next = NULL;
    6991           91 :   if (srv->sq_tail)
    6992            7 :     srv->sq_tail->sq_next = conn;
    6993              :   else
    6994           84 :     srv->sq_head = conn;
    6995           91 :   srv->sq_tail = conn;
    6996           91 :   conn->in_stream_queue = true;
    6997           91 :   srv->sq_len++;
    6998           91 :   ccol__mutex_unlock(srv->wait_mutex);
    6999           91 :   stream_token_start(srv);
    7000              : }
    7001              : 
    7002              : // One streaming-pool task: It takes the oldest queued request, runs it through
    7003              : // task_worker and takes the next, until the queue is empty. Taking a request is
    7004              : // a claim under srv->wait_mutex, as in the sweep, so one of the two answers it
    7005              : // and never both; a request whose deadline passed while it waited gets a 503
    7006              : // here. The thread counts as a worker of srv, so the calls a handler mustn't
    7007              : // make on its own server are refused here too. A task whose run ended
    7008              : // (stream_gen changed) stops and hands the queue to the current run, so the new
    7009              : // thread count applies and the old pool can drain. The task leaves sq_unclaimed
    7010              : // at its first claim and sq_tokens when it finds the queue empty.
    7011           83 : static void stream_token_task(void *arg) {
    7012           83 :   stream_token_arg a = *(stream_token_arg *)arg;
    7013           83 :   struct chttpserver *srv = a.srv;
    7014           83 :   ccol__mem_free(srv->m_procs, arg);
    7015           83 :   chttpsvr_mark_worker_thread(srv);
    7016           83 :   bool first = true;
    7017          170 :   for (;;) {
    7018              : #ifdef RUNNING_UNIT_TESTS
    7019          170 :     stream_claim_hook_wait_if_armed(1);
    7020              : #endif
    7021          170 :     ccol__mutex_lock(srv->wait_mutex);
    7022          170 :     if (atomic_load(&srv->stream_gen) != a.gen) {
    7023            3 :       ccol__mutex_unlock(srv->wait_mutex);
    7024            3 :       stream_token_start(srv);
    7025           83 :       return;
    7026              :     }
    7027          167 :     chttpsvr_conn *c = srv->sq_head;
    7028          167 :     if (first) srv->sq_unclaimed--;
    7029          167 :     first = false;
    7030          167 :     if (!c) {
    7031           80 :       srv->sq_tokens--;
    7032           80 :       ccol__mutex_unlock(srv->wait_mutex);
    7033           80 :       return;
    7034              :     }
    7035           87 :     stream_unlink_locked(srv, c);
    7036           87 :     ccol__mutex_unlock(srv->wait_mutex);
    7037              : #ifdef RUNNING_UNIT_TESTS
    7038           87 :     stream_claim_hook_wait_if_armed(2);
    7039              : #endif
    7040           87 :     struct timespec now;
    7041           87 :     slow_clock(&now);
    7042           87 :     if (c->sq_has_deadline && timespec_reached(now, c->sq_deadline)) {
    7043            1 :       c->park = CONN_PARK_NONE;
    7044            1 :       c->req_rejected = true;
    7045            1 :       c->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    7046            1 :       conn_reject_and_close(c, false);
    7047            1 :       release_in_flight(srv);
    7048            1 :       continue;
    7049              :     }
    7050           86 :     c->park = CONN_PARK_NONE;
    7051           86 :     task_worker(c);
    7052              :   }
    7053              : }
    7054              : 
    7055              : // Answers every queued streaming request with 503, claiming each under
    7056              : // srv->wait_mutex first. A teardown calls it, and so does
    7057              : // stream_token_start_one when the queue has lost every task that drains it.
    7058          719 : static void stream_queue_flush(struct chttpserver *srv) {
    7059          723 :   for (;;) {
    7060          721 :     chttpsvr_conn *batch[CHTTPSVR_IDLE_CLOSE_BATCH];
    7061          721 :     size_t n = 0;
    7062          721 :     ccol__mutex_lock(srv->wait_mutex);
    7063          723 :     while (srv->sq_head && n < CHTTPSVR_IDLE_CLOSE_BATCH) {
    7064            2 :       chttpsvr_conn *c = srv->sq_head;
    7065            2 :       stream_unlink_locked(srv, c);
    7066            2 :       batch[n++] = c;
    7067              :     }
    7068          721 :     ccol__mutex_unlock(srv->wait_mutex);
    7069          721 :     if (n == 0) return;
    7070            4 :     for (size_t i = 0; i < n; i++) conn_reject_busy(batch[i]);
    7071              :   }
    7072              : }
    7073              : 
    7074              : // The part of a sweep tick that no idle list reaches: Requests waiting for body
    7075              : // memory and streaming requests waiting for a thread. Every expired one is
    7076              : // claimed out of its list under srv->wait_mutex, chained through that list's
    7077              : // link field with no cap per tick, and answered with a 503 after the unlock. A
    7078              : // memory waiter has no in_flight_requests slot, so it goes through
    7079              : // conn_dispatch_reject, which takes one; a queued streaming request has one
    7080              : // already. An expired memory waiter can unblock the progress rule, so mem_admit
    7081              : // runs afterwards.
    7082          241 : static void sweep_parked_waits(struct chttpserver *srv,
    7083              :                                struct timespec now_slow) {
    7084          241 :   unsigned mem_ms = atomic_load(&srv->mem_wait_ms);
    7085          241 :   chttpsvr_conn *expired = NULL;
    7086          241 :   bool any = false;
    7087          241 :   ccol__mutex_lock(srv->wait_mutex);
    7088          241 :   if (mem_ms != UINT_MAX) {
    7089          239 :     chttpsvr_conn *c = srv->mem_head;
    7090          242 :     while (c) {
    7091            3 :       chttpsvr_conn *next = c->mem_next;
    7092            3 :       if (ms_since(now_slow, c->mem_wait_start) >= (long long)mem_ms) {
    7093            3 :         mem_wait_unlink_locked(srv, c);
    7094            3 :         c->mem_next = expired;
    7095            3 :         expired = c;
    7096              :       }
    7097              :       c = next;
    7098              :     }
    7099              :   }
    7100          241 :   ccol__mutex_unlock(srv->wait_mutex);
    7101          244 :   while (expired) {
    7102            3 :     chttpsvr_conn *c = expired;
    7103            3 :     expired = c->mem_next;
    7104            3 :     c->mem_next = NULL;
    7105            3 :     any = true;
    7106            3 :     c->park = CONN_PARK_NONE;
    7107            3 :     c->req_rejected = true;
    7108            3 :     c->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    7109            3 :     conn_dispatch_reject(c);
    7110              :   }
    7111          241 :   if (any) mem_admit(srv);
    7112              : 
    7113          241 :   ccol__mutex_lock(srv->wait_mutex);
    7114          241 :   chttpsvr_conn *q = srv->sq_head;
    7115          241 :   while (q) {
    7116            2 :     chttpsvr_conn *next = q->sq_next;
    7117          243 :     if (q->sq_has_deadline && timespec_reached(now_slow, q->sq_deadline)) {
    7118            2 :       stream_unlink_locked(srv, q);
    7119            2 :       q->sq_next = expired;
    7120            2 :       expired = q;
    7121              :     }
    7122              :     q = next;
    7123              :   }
    7124          241 :   ccol__mutex_unlock(srv->wait_mutex);
    7125          243 :   while (expired) {
    7126            2 :     chttpsvr_conn *c = expired;
    7127            2 :     expired = c->sq_next;
    7128            2 :     c->sq_next = NULL;
    7129            2 :     conn_reject_busy(c);
    7130              :   }
    7131          241 : }
    7132              : 
    7133              : // What a Content-Length body of declared bytes, of which carry came with the
    7134              : // headers, reserves before a worker reads it: The capacity its buffer reaches
    7135              : // under body_grow_target's rule to hold the carry-over plus one 8 KiB read,
    7136              : // never more than declared. Every later growth is reserved as the bytes come in
    7137              : // (see drain_body_socket_read).
    7138          115 : static size_t body_first_reserve(size_t declared, size_t carry) {
    7139          115 :   size_t need = carry > SIZE_MAX - 8192 ? SIZE_MAX : carry + 8192;
    7140          115 :   if (need > declared) need = declared;
    7141          115 :   size_t first = CHTTPSVR_BODY_FIRST_CAP;
    7142          115 :   while (first < need) {
    7143            0 :     if (first > SIZE_MAX / 2) return need;
    7144            0 :     first *= 2;
    7145              :   }
    7146          115 :   return first < declared ? first : declared;
    7147              : }
    7148              : 
    7149              : // The cold half of conn_start_diverted, for a request whose divert_gate is set:
    7150              : // a streaming request (SIZE_MAX) goes to the streaming queue, and a body
    7151              : // reserves its first buffer. Returns true when it took the connection over and
    7152              : // false when the ordinary divert carries on. If the first buffer doesn't fit,
    7153              : // the request leaves the diverted list, gives back its in_flight_requests slot
    7154              : // and waits in the memory-wait list without a thread, and nobody reads its body
    7155              : // or sends 100 Continue until memory frees up. The caller has counted the
    7156              : // request, listed it as diverted, paused its registration and saved the
    7157              : // carry-over.
    7158          207 : static __attribute__((noinline, cold)) bool conn_divert_gate(
    7159              :     chttpsvr_conn *conn) {
    7160          207 :   size_t gate = conn->divert_gate;
    7161          207 :   if (gate == SIZE_MAX) {
    7162           92 :     stream_enqueue(conn);
    7163           92 :     return true;
    7164              :   }
    7165          115 :   struct chttpserver *srv = conn->srv;
    7166          115 :   size_t first = body_first_reserve(gate, conn->carry_over_len);
    7167          115 :   if (mem_try_reserve(srv, conn, first)) return false;
    7168            8 :   diverted_list_remove(conn);
    7169            8 :   mem_wait_enqueue(srv, conn, first, CONN_PARK_MEM_START);
    7170            8 :   release_in_flight(srv);
    7171            8 :   mem_admit(srv);
    7172            8 :   return true;
    7173              : }
    7174              : 
    7175              : // The socket half of drain_body, once the carry-over is used up: Reads the
    7176              : // socket without waiting. When the socket has nothing it sets
    7177              : // conn->park_pending to CONN_PARK_BODY and returns -1, and the caller parks the
    7178              : // connection. Before reading it makes sure the body memory reservation covers
    7179              : // this read and any growth it causes (old and new block together); if that
    7180              : // can't be reserved, it sets park_pending to CONN_PARK_MEM_BODY and returns -1
    7181              : // without reading. The capacity it reserves for is clamped to max_body_size and
    7182              : // to the declared Content-Length, so a legal body never waits for memory it
    7183              : // won't use. The first call starts the rate floor's phase, and every byte read
    7184              : // counts as progress.
    7185         2420 : static __attribute__((noinline, cold)) ssize_t drain_body_socket_read(
    7186              :     chttpsvr_conn *conn, chttp1_stream *stream, char *raw, size_t len) {
    7187         2420 :   struct chttpserver *srv = conn->srv;
    7188         2420 :   if (!conn->rate_active) rate_window_start(conn, conn->body_bytes_seen);
    7189         2420 :   size_t cap = conn->body.cap;
    7190         2420 :   size_t limit = atomic_load(&srv->max_body_size);
    7191         2420 :   size_t need = conn->body.len + len;
    7192         2420 :   if (need < conn->body.len) need = SIZE_MAX;
    7193         2420 :   if (limit && need > limit) need = limit < cap ? cap : limit;
    7194         2420 :   if (chttp1_has_content_length(&conn->parser)) {
    7195         2235 :     uint64_t rest = chttp1_declared_content_length(&conn->parser);
    7196         2234 :     if (rest < (uint64_t)(need - conn->body.len)) {
    7197          502 :       size_t d = conn->body.len + (size_t)rest;
    7198          502 :       need = d < cap ? cap : d;
    7199              :     }
    7200              :   }
    7201         2420 :   if ((need > cap || conn->mem_charged < cap) && !conn->options_star &&
    7202          230 :       atomic_load(&srv->mem_cap) != SIZE_MAX) {
    7203          230 :     size_t target = body_grow_target(conn, cap, need, limit);
    7204          460 :     size_t want = target <= cap             ? cap
    7205          230 :                   : target > SIZE_MAX - cap ? SIZE_MAX
    7206          228 :                                             : target + cap;
    7207          230 :     if (conn->mem_charged < want) {
    7208          112 :       size_t step = want - conn->mem_charged;
    7209          112 :       if (!mem_try_reserve(srv, conn, step)) {
    7210            7 :         conn->mem_need = step;
    7211            7 :         conn->park_pending = CONN_PARK_MEM_BODY;
    7212            7 :         return -1;
    7213              :       }
    7214              :     }
    7215              :   }
    7216         2413 :   ssize_t n = chttp1_stream_read(stream, raw, len, 0);
    7217         2413 :   if (n > 0) {
    7218         2053 :     conn->rate_bytes += (uint64_t)n;
    7219         2053 :     conn->rate_queued = 0;
    7220         2053 :     slow_clock(&conn->last_progress);
    7221          360 :   } else if (n < 0 && chttp1_stream_timed_out(stream)) {
    7222          322 :     conn->park_pending = CONN_PARK_BODY;
    7223              :   }
    7224              :   return n;
    7225              : }
    7226              : 
    7227              : // Parks conn: Arms its registration for the direction the park of the given
    7228              : // kind needs (read for a body or a linger, the direction the write wants for a
    7229              : // write park), sets conn->park and adds conn to the parked list. Every park
    7230              : // path ends here, so a parked connection holds no thread while the reactor
    7231              : // waits for it.
    7232              : // The caller owns conn and doesn't touch it after a true return. A registration
    7233              : // paused by the worker phase gets a modify and a resume; a connection that
    7234              : // never had one (its first request was parsed right after the accept) gets a
    7235              : // fresh ceventloop_add, which takes a lifetime reference on conn and on srv as
    7236              : // every add does. Returns false, with conn in no list and park cleared, when
    7237              : // the reactor refuses; the caller then closes conn.
    7238          594 : static bool conn_park_arm(chttpsvr_conn *conn, uint8_t kind) {
    7239          594 :   cselect_dir dir;
    7240          594 :   if (kind == CONN_PARK_BODY) {
    7241            6 :     dir = (conn->tls && ctls_conn_wants_write(conn->tls)) ? cselect_write
    7242          328 :                                                           : cselect_read;
    7243          322 :     conn_set_rcvlowat(conn);
    7244          272 :   } else if (kind == CONN_PARK_LINGER) {
    7245          134 :     dir = cselect_read;
    7246          134 :     conn_reset_rcvlowat(conn);
    7247              :   } else {
    7248          138 :     dir = conn->wp_wants_read ? cselect_read : cselect_write;
    7249          138 :     conn_reset_rcvlowat(conn);
    7250          138 :     conn->wp_outq = conn_send_queue(conn);
    7251              :   }
    7252          594 :   conn->park = kind;
    7253          594 :   conn->state = CONN_ST_READING_HEADERS;
    7254          594 :   if (conn->reg) {
    7255          708 :     if (conn_reg_modify(conn, dir) != ccol_success ||
    7256          354 :         ceventloop_resume(srv_engine_bundler.reactor, conn->reg) !=
    7257              :             ccol_success) {
    7258            0 :       conn->park = CONN_PARK_NONE;
    7259            0 :       return false;
    7260              :     }
    7261              :   } else {
    7262          240 :     char *err = NULL;
    7263          480 :     conn->reg = ceventloop_add(
    7264          240 :         srv_engine_bundler.reactor, cselectable_fd(conn->fd, dir),
    7265          240 :         (ceventloop_handlers){.on_readable = conn_on_readable,
    7266              :                               .on_writable = conn_on_writable,
    7267              :                               .on_error = conn_on_error,
    7268              :                               .on_removed = conn_on_removed},
    7269              :         conn, &err);
    7270          240 :     if (!conn->reg) {
    7271            0 :       conn->park = CONN_PARK_NONE;
    7272            0 :       return false;
    7273              :     }
    7274          240 :     conn->reg_dir = (uint8_t)dir;
    7275          240 :     atomic_fetch_add(&conn->lifetime_refs, 1);
    7276          240 :     atomic_fetch_add(&conn->srv->lifetime_refs, 1);
    7277              :   }
    7278              : #ifdef RUNNING_UNIT_TESTS
    7279          594 :   atomic_fetch_add(&g_park_count_for_tests, 1);
    7280          594 :   if (kind < 8) atomic_fetch_add(&g_park_kind_count_for_tests[kind], 1);
    7281              : #endif
    7282          594 :   parked_list_add(conn);
    7283          594 :   return true;
    7284              : }
    7285              : 
    7286              : // Gives up, on the worker that was reading it, a connection whose body stopped
    7287              : // arriving or that must wait for body memory (conn->park_pending says which).
    7288              : // Afterwards the connection holds no thread and no in_flight_requests slot, and
    7289              : // the reactor or a memory admission hands it to a worker again. Nothing in the
    7290              : // stream needs keeping: The body reader only reads the socket once the
    7291              : // carry-over is empty, and a pipelined request can only follow a complete body.
    7292              : // A memory wait goes onto the server's memory wait queue and runs mem_admit. A
    7293              : // body park trims the body reservation down to the buffer it holds (a body with
    7294              : // no buffer yet keeps its first reservation) and arms the registration; if that
    7295              : // fails the connection is closed. The in-flight slot is released only after
    7296              : // conn is parked or closed.
    7297          329 : static __attribute__((noinline, cold)) void task_park_body(
    7298              :     chttpsvr_conn *conn, struct chttpserver *srv, chttp1_stream *stream,
    7299              :     chttpsvr_req *req) {
    7300          329 :   uint8_t kind = conn->park_pending;
    7301          329 :   conn->park_pending = CONN_PARK_NONE;
    7302          329 :   destroy_req_scratch(req);
    7303          329 :   chttp1_stream_release(stream);
    7304          329 :   diverted_list_remove(conn);
    7305          329 :   if (kind == CONN_PARK_MEM_BODY) {
    7306            7 :     mem_wait_enqueue(srv, conn, conn->mem_need, CONN_PARK_MEM_BODY);
    7307            7 :     release_in_flight(srv);
    7308            7 :     mem_admit(srv);
    7309            7 :     return;
    7310              :   }
    7311          322 :   if (conn->mem_charged > conn->body.cap && conn->body.cap)
    7312            5 :     mem_trim(conn, conn->body.cap);
    7313          322 :   if (!conn_park_arm(conn, CONN_PARK_BODY)) {
    7314            0 :     conn_close(conn);
    7315            0 :     release_in_flight(srv);
    7316            0 :     return;
    7317              :   }
    7318          322 :   release_in_flight(srv);
    7319              : }
    7320              : 
    7321              : // Hands a parked connection that the reactor claimed on readiness to a free
    7322              : // worker, which runs task_resume. It stamps the claim time first, so the queue
    7323              : // wait isn't charged to the client, and pauses the registration so no more
    7324              : // readiness fires while a worker owns the connection. It puts conn in the
    7325              : // diverted list and counts it in srv->in_flight_requests (under srv->mutex).
    7326              : // When the pool refuses, a parked body gets a 503, since nothing of its
    7327              : // response is out yet, and a parked response, already partly sent, is closed.
    7328          441 : static __attribute__((noinline, cold)) void conn_resume_parked(
    7329              :     chttpsvr_conn *conn) {
    7330          441 :   struct chttpserver *srv = conn->srv;
    7331          441 :   conn_stamp_claim(conn);
    7332          441 :   conn_pause_reg(conn);
    7333          441 :   conn->state = CONN_ST_DIVERTED;
    7334          441 :   diverted_list_add(conn);
    7335          441 :   ccol__mutex_lock(srv->mutex);
    7336          441 :   srv->in_flight_requests++;
    7337          441 :   cthrpool pool = srv->worker_pool;
    7338          441 :   ccol__mutex_unlock(srv->mutex);
    7339              : #ifdef RUNNING_UNIT_TESTS
    7340          441 :   atomic_fetch_add(&g_resume_dispatch_count_for_tests, 1);
    7341              : #endif
    7342          882 :   if (srv_submit(srv, SRV_POOL_WORKER, pool, task_resume, conn)) return;
    7343            1 :   if (conn->park == CONN_PARK_WRITE) {
    7344            1 :     conn->park = CONN_PARK_NONE;
    7345            1 :     conn_close(conn);
    7346            1 :     release_in_flight(srv);
    7347            1 :     return;
    7348              :   }
    7349            0 :   conn_reject_busy(conn);
    7350              : }
    7351              : 
    7352              : // Longest time a lingering close waits. When the server closes a connection
    7353              : // while the client is still sending (often the body of a refused request), the
    7354              : // kernel answers those bytes with a reset, and a reset can wipe the response
    7355              : // out of the client's receive buffer. So the server shuts down its write side
    7356              : // and reads and throws away what arrives, as nginx's lingering_close does. The
    7357              : // bound is a time, because a byte budget smaller than a refused upload would
    7358              : // close the connection under a client that sends the whole body before it reads
    7359              : // the response.
    7360              : #define CHTTPSVR_LINGER_MS 2000u
    7361              : // Most bytes one dispatch of a lingering connection throws away; the rest waits
    7362              : // for the next readiness report, so a fast sender can't hold the reactor
    7363              : // thread.
    7364              : #define CHTTPSVR_LINGER_STEP_BYTES ((size_t)256 * 1024)
    7365              : 
    7366              : #ifdef RUNNING_UNIT_TESTS
    7367              : // Test hook: Counts the lingering closes that started, and its reader.
    7368              : static _Atomic size_t g_linger_count_for_tests = 0;
    7369           13 : size_t chttpsvr__linger_count_for_tests(void) {
    7370           13 :   return atomic_load(&g_linger_count_for_tests);
    7371              : }
    7372              : #endif
    7373              : 
    7374              : // Tells whether conn's client may still send bytes the server hasn't read: The
    7375              : // rest of a body, pipelined bytes in the carry-over, or bytes already queued in
    7376              : // the socket (FIONREAD). The close paths use it to pick a lingering close over
    7377              : // a plain one.
    7378          579 : static bool conn_request_bytes_may_remain(chttpsvr_conn *conn) {
    7379          579 :   if (chttp1_request_bytes_may_remain(&conn->parser)) return true;
    7380          408 :   if (conn->carry_over_len != 0) return true;
    7381          408 :   int queued = 0;
    7382          814 :   return ioctl(conn->fd, FIONREAD, &queued) == 0 && queued > 0;
    7383              : }
    7384              : 
    7385              : // Reads and throws away what the client sent, without waiting, up to
    7386              : // CHTTPSVR_LINGER_STEP_BYTES per call. Returns true while the linger should go
    7387              : // on (the socket is empty or the step budget is used up), and false once the
    7388              : // client closed or the read failed.
    7389       153427 : static bool linger_discard(chttpsvr_conn *conn) {
    7390       153427 :   char buf[16384];
    7391       153427 :   size_t taken = 0;
    7392       450373 :   while (taken < CHTTPSVR_LINGER_STEP_BYTES) {
    7393       450361 :     ssize_t n = read(conn->fd, buf, sizeof(buf));
    7394       450361 :     if (n > 0) {
    7395       296946 :       taken += (size_t)n;
    7396       296946 :       continue;
    7397              :     }
    7398       153415 :     if (n < 0 && errno == EINTR) continue;
    7399       153549 :     return n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK);
    7400              :   }
    7401              :   return true;
    7402              : }
    7403              : 
    7404              : // Starts conn's lingering close in place of conn_close (see
    7405              : // CHTTPSVR_LINGER_MS). The caller owns conn, has it in no list but the diverted
    7406              : // list, and doesn't touch it again.
    7407              : // It frees the request state, the response and the body reservation right away,
    7408              : // since the real close can be up to CHTTPSVR_LINGER_MS away. A TLS connection
    7409              : // sends its close_notify as its TLS state goes; nothing else is written. Then
    7410              : // it shuts down the write side, sets conn->linger_deadline, discards what is
    7411              : // already there and parks conn as CONN_PARK_LINGER, which holds no thread but
    7412              : // still counts against max_connections. Any failure closes the connection at
    7413              : // once.
    7414          177 : static __attribute__((noinline, cold)) void conn_linger(chttpsvr_conn *conn) {
    7415          177 :   conn_drop_request_state(conn);
    7416          176 :   destroy_resp(&conn->resp, conn->m_procs);
    7417          176 :   if (conn->tls) {
    7418            1 :     ctls_conn_destroy(conn->tls);
    7419            1 :     conn->tls = NULL;
    7420              :   }
    7421          176 :   if (shutdown(conn->fd, SHUT_WR) != 0) {
    7422           38 :     conn_close(conn);
    7423           38 :     return;
    7424              :   }
    7425          138 :   clock_gettime(CLOCK_MONOTONIC, &conn->linger_deadline);
    7426          276 :   timespec_add_ms(&conn->linger_deadline, CHTTPSVR_LINGER_MS);
    7427          138 :   if (!linger_discard(conn)) {
    7428            4 :     conn_close(conn);
    7429            4 :     return;
    7430              :   }
    7431          134 :   diverted_list_remove(conn);
    7432          134 :   if (!conn_park_arm(conn, CONN_PARK_LINGER)) {
    7433            0 :     conn_close(conn);
    7434            0 :     return;
    7435              :   }
    7436              : #ifdef RUNNING_UNIT_TESTS
    7437          134 :   atomic_fetch_add(&g_linger_count_for_tests, 1);
    7438              : #endif
    7439              : }
    7440              : 
    7441              : // Handles a lingering connection the reactor claimed on readiness: Throws away
    7442              : // what arrived, then parks it again, or closes it once the client closed or
    7443              : // conn->linger_deadline passed.
    7444       153289 : static __attribute__((noinline, cold)) void conn_linger_step(
    7445              :     chttpsvr_conn *conn) {
    7446       153289 :   struct timespec now;
    7447       153289 :   clock_gettime(CLOCK_MONOTONIC, &now);
    7448       306448 :   if (linger_discard(conn) && !timespec_reached(now, conn->linger_deadline)) {
    7449       153158 :     parked_list_add(conn);
    7450       153158 :     return;
    7451              :   }
    7452          131 :   conn->park = CONN_PARK_NONE;
    7453          131 :   conn_close(conn);
    7454              : }
    7455              : 
    7456              : // Saves the state of a response whose write ran into a full socket, so
    7457              : // task_continue_write can finish it later. head and head_len are the unsent
    7458              : // part of the header block, which lives on send_response's stack and is copied;
    7459              : // body_pos is how much of the body is out. internal marks one of the library's
    7460              : // own writes (a rejection or the interim line), whose time limit is capped by
    7461              : // CHTTPSVR_INTERNAL_WRITE_MAX_TOTAL_MS.
    7462              : // It sets the wp_* fields and conn->wp_active, and moves pipelined bytes of a
    7463              : // next request from the stream onto conn->carry_over, because the caller
    7464              : // releases the stream; if those bytes can't be copied, the connection closes
    7465              : // when the write ends instead of waiting for a request the client already sent.
    7466              : // The write's rate window starts where the write started, taken from the write
    7467              : // deadline when a total-duration bound is on. If the header copy fails
    7468              : // wp_active stays false, and the caller closes the connection as for any failed
    7469              : // write.
    7470           29 : static __attribute__((noinline, cold)) void send_response_park(
    7471              :     chttpsvr_conn *conn, chttp1_stream *stream, const char *head,
    7472              :     size_t head_len, size_t body_pos, bool keep_alive, bool no_body,
    7473              :     bool internal) {
    7474           29 :   char *copy = NULL;
    7475           29 :   if (head_len) {
    7476            9 :     copy = (char *)ccol__mem_alloc(conn->m_procs, head_len);
    7477            9 :     if (!copy) return;
    7478            9 :     memcpy(copy, head, head_len);
    7479              :   }
    7480           29 :   conn->wp_head = copy;
    7481           29 :   conn->wp_head_len = head_len;
    7482           29 :   conn->wp_head_pos = 0;
    7483           29 :   conn->wp_body_pos = body_pos;
    7484           29 :   conn->wp_keep_alive = keep_alive;
    7485           29 :   conn->wp_no_body = no_body;
    7486           29 :   conn->wp_wants_read = stream->tls && chttp1_stream_timed_out(stream) &&
    7487            0 :                         !ctls_conn_wants_write((ctls_conn *)stream->tls);
    7488           29 :   conn->wp_active = true;
    7489           29 :   size_t lo_len = 0;
    7490           29 :   char *lo = chttp1_stream_take_leftover(stream, &lo_len);
    7491           29 :   if (lo) {
    7492            1 :     ccol__mem_free(conn->m_procs, conn->carry_over);
    7493            1 :     conn->carry_over = lo;
    7494            1 :     conn->carry_over_len = lo_len;
    7495           28 :   } else if (lo_len) {
    7496            1 :     conn->wp_keep_alive = false;
    7497              :   }
    7498           29 :   rate_window_start(conn, body_pos);
    7499           29 :   unsigned max_dur = atomic_load(&conn->srv->max_response_write_duration_ms);
    7500           35 :   if (internal && (max_dur == 0 || max_dur > internal_write_ceiling_ms()))
    7501            7 :     max_dur = internal_write_ceiling_ms();
    7502           29 :   if (conn->write_deadline_set && max_dur) {
    7503           28 :     struct timespec now_mono;
    7504           28 :     clock_gettime(CLOCK_MONOTONIC, &now_mono);
    7505           56 :     long long run =
    7506           28 :         (long long)max_dur - ms_since_ceil(conn->write_deadline, now_mono);
    7507           28 :     if (run > 0) timespec_sub_ms(&conn->rate_start, run);
    7508              :   }
    7509              : }
    7510              : 
    7511              : // Parks a connection whose response ran into a full socket (see
    7512              : // send_response_park) until the socket has room; the sweep applies the write
    7513              : // limits and the rate floor meanwhile. It releases the in-flight slot after
    7514              : // conn is parked, or after it is closed when the park fails.
    7515          132 : static __attribute__((noinline, cold)) void conn_park_write(
    7516              :     chttpsvr_conn *conn, struct chttpserver *srv) {
    7517          132 :   diverted_list_remove(conn);
    7518          132 :   if (!conn_park_arm(conn, CONN_PARK_WRITE)) {
    7519            0 :     conn->wp_active = false;
    7520            0 :     ccol__mem_free(conn->m_procs, conn->wp_head);
    7521            0 :     conn->wp_head = NULL;
    7522            0 :     conn_close(conn);
    7523            0 :     release_in_flight(srv);
    7524            0 :     return;
    7525              :   }
    7526          132 :   release_in_flight(srv);
    7527              : }
    7528              : 
    7529              : // Drops the saved state of a parked response once its write has ended.
    7530           23 : static void conn_end_parked_write(chttpsvr_conn *conn) {
    7531           23 :   conn->wp_active = false;
    7532           23 :   ccol__mem_free(conn->m_procs, conn->wp_head);
    7533           23 :   conn->wp_head = NULL;
    7534           23 :   conn->wp_head_len = conn->wp_head_pos = conn->wp_body_pos = 0;
    7535           23 : }
    7536              : 
    7537              : // Writes the rest of a parked response without waiting, checking the write
    7538              : // deadline before each write (the library's own writes keep their internal
    7539              : // ceiling). It advances the wp_* positions, the rate byte count and
    7540              : // conn->last_progress. Returns 1 once the whole response is out, 0 when the
    7541              : // write failed or a write limit ran out, and -1 when the socket is full again;
    7542              : // on -1 it records in conn->wp_wants_read whether TLS needs the socket readable
    7543              : // first.
    7544          132 : static int send_response_continue(chttp1_stream *stream, chttpsvr_conn *conn) {
    7545          132 :   size_t blen = conn->wp_no_body ? 0 : conn->resp.body_len;
    7546          207 :   for (;;) {
    7547          339 :     size_t alen = conn->wp_head_len - conn->wp_head_pos;
    7548          339 :     size_t brem = blen - conn->wp_body_pos;
    7549          339 :     if (alen + brem == 0) return 1;
    7550          316 :     unsigned call_timeout_ms = 0;
    7551          316 :     if (!response_write_deadline_ok(conn, conn->wp_reject || conn->wp_interim,
    7552              :                                     &call_timeout_ms))
    7553              :       return 0;
    7554          632 :     ssize_t n = chttp1_stream_writev2(
    7555          316 :         stream, conn->wp_head ? conn->wp_head + conn->wp_head_pos : NULL, alen,
    7556          311 :         brem ? conn->resp.body + conn->wp_body_pos : NULL, brem, 0);
    7557          316 :     if (n <= 0) {
    7558          109 :       if (n < 0 && chttp1_stream_timed_out(stream)) {
    7559          218 :         conn->wp_wants_read =
    7560          109 :             stream->tls && !ctls_conn_wants_write((ctls_conn *)stream->tls);
    7561          109 :         return -1;
    7562              :       }
    7563            0 :       return 0;
    7564              :     }
    7565          207 :     size_t moved = (size_t)n;
    7566          207 :     size_t in_head = moved < alen ? moved : alen;
    7567          207 :     conn->wp_head_pos += in_head;
    7568          207 :     conn->wp_body_pos += moved - in_head;
    7569          207 :     conn->rate_bytes += (uint64_t)n;
    7570          207 :     slow_clock(&conn->last_progress);
    7571              :   }
    7572              : }
    7573              : 
    7574              : // Worker thread: Body read, handler and response.
    7575              : //
    7576              : // What drain_body returns, and only then, when the body stopped arriving or
    7577              : // must wait for memory and the caller has to park the connection instead of
    7578              : // waiting.
    7579              : #define CHTTPSVR_BODY_PARKED ccol_container_empty
    7580              : 
    7581              : static bool rate_floor_shrink(chttpsvr_conn *conn, unsigned *timeout_ms_inout);
    7582              : 
    7583              : // Shrinks *timeout_ms_inout so a body read doesn't wait past the body's
    7584              : // max_body_read_duration_ms deadline. Returns false, and sets
    7585              : // conn->deadline_exceeded, once that deadline has passed.
    7586          104 : static bool check_read_deadline(chttpsvr_conn *conn,
    7587              :                                 unsigned *timeout_ms_inout) {
    7588          104 :   unsigned max_dur = atomic_load(&conn->srv->max_body_read_duration_ms);
    7589          104 :   if (!shrink_timeout_to_deadline(&conn->read_deadline,
    7590              :                                   &conn->read_deadline_set, max_dur,
    7591              :                                   timeout_ms_inout)) {
    7592            0 :     conn->deadline_exceeded = true;
    7593            0 :     return false;
    7594              :   }
    7595              :   return true;
    7596              : }
    7597              : 
    7598              : // The same check as check_read_deadline, kept inline for drain_body, which runs
    7599              : // for every buffered body.
    7600         2471 : static inline __attribute__((always_inline)) bool check_read_deadline_inl(
    7601              :     chttpsvr_conn *conn, unsigned *timeout_ms_inout) {
    7602         2471 :   unsigned max_dur = atomic_load(&conn->srv->max_body_read_duration_ms);
    7603         2471 :   if (!shrink_timeout_to_deadline_inl(&conn->read_deadline,
    7604              :                                       &conn->read_deadline_set, max_dur,
    7605              :                                       timeout_ms_inout)) {
    7606            0 :     conn->deadline_exceeded = true;
    7607            0 :     return false;
    7608              :   }
    7609              :   return true;
    7610              : }
    7611              : 
    7612              : // Reads a buffered route's whole request body on the calling worker and feeds
    7613              : // it to the parser; http1_on_body collects it in conn->body. Streaming routes
    7614              : // never come here, their handler reads with chttpsvr_req_read. The carry-over
    7615              : // that came with the headers is read first, then the socket without waiting.
    7616              : // Returns ccol_success, CHTTPSVR_BODY_PARKED when the caller must park
    7617              : // (conn->park_pending set), ccol_timed_out, ccol_msg_too_large,
    7618              : // ccol_not_enough_memory, or ccol_http_transfer_aborted; the caller maps these
    7619              : // to a status. A truncated body or bad framing sets conn->body_malformed so it
    7620              : // answers 400, never 500, and an oversized chunk sets conn->body_too_large.
    7621              : // Bytes past the end of the message belong to a pipelined next request and go
    7622              : // back onto the stream's carry-over; if that fails the parser is forced to
    7623              : // close the connection, or the client would wait for an answer to a request
    7624              : // whose bytes we lost.
    7625         1271 : static ccol_retval drain_body(chttpsvr_conn *conn, chttp1_stream *stream) {
    7626         2013 :   for (;;) {
    7627         3284 :     if (chttp1_parser_message_complete(&conn->parser)) break;
    7628         2471 :     unsigned timeout_ms = atomic_load(&conn->srv->stream_read_timeout_ms);
    7629         5317 :     if (!check_read_deadline_inl(conn, &timeout_ms)) return ccol_timed_out;
    7630         2471 :     char raw[8192];
    7631         2471 :     ssize_t n = chttp1_stream_has_carry(stream)
    7632          101 :                     ? chttp1_stream_read(stream, raw, sizeof(raw),
    7633              :                                          to_stream_timeout_ms(timeout_ms))
    7634         2471 :                     : drain_body_socket_read(conn, stream, raw, sizeof(raw));
    7635         2471 :     if (n < 0) {
    7636          329 :       if (conn->park_pending) return CHTTPSVR_BODY_PARKED;
    7637            0 :       if (chttp1_stream_timed_out(stream)) return ccol_timed_out;
    7638              :       return ccol_http_transfer_aborted;
    7639              :     }
    7640         2142 :     if (n == 0) {
    7641           38 :       conn->body_malformed = true;
    7642           38 :       return ccol_http_transfer_aborted;
    7643              :     }
    7644         2104 :     chttp1_errno r = chttp1_parser_execute(&conn->parser, raw, (size_t)n);
    7645         2104 :     if (r == CHTTP1_PAUSED) {
    7646           83 :       size_t consumed = chttp1_parser_consumed(&conn->parser);
    7647           89 :       if ((size_t)n > consumed &&
    7648            6 :           !chttp1_stream_push_back_leftover(stream, raw + consumed,
    7649              :                                             (size_t)n - consumed)) {
    7650            1 :         chttp1_parser_force_close(&conn->parser);
    7651              :       }
    7652              :       break;
    7653              :     }
    7654         2021 :     if (r == CHTTP1_USER || r == CHTTP1_ERROR) {
    7655            8 :       if (chttp1_chunk_size_limit_exceeded(&conn->parser))
    7656            2 :         conn->body_too_large = true;
    7657            8 :       if (r == CHTTP1_ERROR && !conn->body_too_large &&
    7658            4 :           !conn->body_alloc_failed)
    7659            4 :         conn->body_malformed = true;
    7660            8 :       return conn->body_too_large      ? ccol_msg_too_large
    7661            8 :              : conn->body_alloc_failed ? ccol_not_enough_memory
    7662              :                                        : ccol_http_transfer_aborted;
    7663              :     }
    7664              :   }
    7665          896 :   return ccol_success;
    7666              : }
    7667              : 
    7668              : // Reads up to buflen bytes of a streaming route's request body into buf,
    7669              : // waiting as the read timeout, the body duration bound and the rate floor
    7670              : // allow. Returns the count read, 0 at the end of the body, and -1 on failure;
    7671              : // chttpsvr_req_stream_error then tells why from the flags this sets on conn
    7672              : // (deadline_exceeded, body_too_large, transfer_aborted). It fails for a NULL
    7673              : // req, a buffered route, or a request with no matched route (a rejection a
    7674              : // middleware sees), which also covers a req used after its handler returned.
    7675              : // The first call sends the deferred 100 Continue when the client asked for it
    7676              : // and a body is still to come, so a handler that rejects without reading never
    7677              : // invites the upload. A failed or short interim write sets
    7678              : // conn->interim_write_failed and transfer_aborted, and no response follows it.
    7679              : // Bytes past the end of the message are pushed back onto the stream for
    7680              : // task_tail, as in drain_body.
    7681         3241 : ssize_t chttpsvr_req_read(chttpsvr_req *req, void *buf, size_t buflen) {
    7682         3241 :   if (!req) return -1;
    7683         3240 :   if (buflen == 0) return 0;
    7684         3238 :   if (!buf) return -1;
    7685         3237 :   chttpsvr_conn *conn = req->conn;
    7686         3237 :   if (!conn || !conn->matched_route) return -1;
    7687         3237 :   if (!conn->matched_route->is_streaming) return -1;
    7688         3236 :   if (!req->stream) return -1;
    7689              : 
    7690         3236 :   if (conn->expects_continue && !conn->interim_continue_sent) {
    7691            4 :     conn->interim_continue_sent = true;
    7692            4 :     if (!chttp1_parser_message_complete(&conn->parser)) {
    7693            3 :       unsigned wtimeout_ms = atomic_load(&conn->srv->response_write_timeout_ms);
    7694            3 :       if (write_interim_continue(conn, req->stream, wtimeout_ms) != 1) {
    7695            2 :         conn->interim_write_failed = true;
    7696            2 :         conn->transfer_aborted = true;
    7697              :       }
    7698              :     }
    7699              :   }
    7700         3236 :   if (conn->interim_write_failed) return -1;
    7701              : 
    7702           92 :   for (;;) {
    7703         3326 :     growbuf *b = &conn->body;
    7704         3326 :     if (b->pos < b->len) {
    7705         3192 :       size_t avail = b->len - b->pos;
    7706         3192 :       size_t take = avail < buflen ? avail : buflen;
    7707         3192 :       memcpy(buf, b->buf + b->pos, take);
    7708         3192 :       b->pos += take;
    7709         3234 :       return (ssize_t)take;
    7710              :     }
    7711          134 :     if (chttp1_parser_message_complete(&conn->parser)) return 0;
    7712              : 
    7713          104 :     unsigned timeout_ms = atomic_load(&conn->srv->stream_read_timeout_ms);
    7714          104 :     if (!check_read_deadline(conn, &timeout_ms)) return -1;
    7715          104 :     if (!rate_floor_shrink(conn, &timeout_ms)) {
    7716            0 :       conn->deadline_exceeded = true;
    7717            0 :       return -1;
    7718              :     }
    7719          104 :     char raw[8192];
    7720          202 :     ssize_t n = chttp1_stream_read(req->stream, raw, sizeof(raw),
    7721              :                                    to_stream_timeout_ms(timeout_ms));
    7722          104 :     if (n > 0) conn->rate_bytes += (uint64_t)n;
    7723          104 :     if (n < 0) {
    7724            3 :       if (chttp1_stream_timed_out(req->stream)) {
    7725            3 :         conn->deadline_exceeded = true;
    7726              :       } else {
    7727            0 :         conn->transfer_aborted = true;
    7728              :       }
    7729            3 :       return -1;
    7730              :     }
    7731          101 :     if (n == 0) {
    7732            5 :       conn->transfer_aborted = true;
    7733            5 :       return -1;
    7734              :     }
    7735           96 :     chttp1_errno r = chttp1_parser_execute(&conn->parser, raw, (size_t)n);
    7736           96 :     if (r == CHTTP1_USER || r == CHTTP1_ERROR) {
    7737            4 :       if (chttp1_chunk_size_limit_exceeded(&conn->parser))
    7738            1 :         conn->body_too_large = true;
    7739            4 :       conn->transfer_aborted = true;
    7740            4 :       return -1;
    7741              :     }
    7742           92 :     if (r == CHTTP1_PAUSED) {
    7743           27 :       size_t consumed = chttp1_parser_consumed(&conn->parser);
    7744           29 :       if ((size_t)n > consumed &&
    7745            2 :           !chttp1_stream_push_back_leftover(req->stream, raw + consumed,
    7746              :                                             (size_t)n - consumed)) {
    7747            1 :         chttp1_parser_force_close(&conn->parser);
    7748              :       }
    7749              :     }
    7750              :   }
    7751              : }
    7752              : 
    7753              : // Tells a streaming handler why chttpsvr_req_read failed, from the flags the
    7754              : // read set on the connection: ccol_timed_out, ccol_msg_too_large,
    7755              : // ccol_not_enough_memory or ccol_http_transfer_aborted, in that priority, else
    7756              : // ccol_success. Returns ccol_invalid_args for a NULL or detached req.
    7757           13 : ccol_retval chttpsvr_req_stream_error(const chttpsvr_req *req) {
    7758           13 :   if (!req || !req->conn) return ccol_invalid_args;
    7759           12 :   chttpsvr_conn *conn = req->conn;
    7760           12 :   if (conn->deadline_exceeded) return ccol_timed_out;
    7761            9 :   if (conn->body_too_large) return ccol_msg_too_large;
    7762            7 :   if (conn->body_alloc_failed) return ccol_not_enough_memory;
    7763            6 :   if (conn->transfer_aborted) return ccol_http_transfer_aborted;
    7764              :   return ccol_success;
    7765              : }
    7766              : 
    7767              : // Finishes a request whose response went out or was given up: It frees the
    7768              : // stream and the request scratch, then closes, lingers, parks a half-written
    7769              : // response, or hands a kept-alive connection back to the reactor. task_worker,
    7770              : // task_resume and the parked-write paths all end here; it is inlined so an
    7771              : // ordinary request compiles as one function.
    7772              : // Pipelined bytes of a next request, already off the wire, are taken from the
    7773              : // stream and kept only on keep-alive. They are fed to the parser right here, as
    7774              : // is any input that TLS holds inside the SSL object, because epoll would never
    7775              : // report either. After conn_feed_bytes the connection may already be freed by
    7776              : // another thread, so only srv (whose m_procs equals conn->m_procs) is used
    7777              : // after that call. A kept-alive connection gets its registration forced back to
    7778              : // the read direction (or write, when TLS needs it) and resumed, or a fresh add
    7779              : // with both handlers when it never had one. srv->in_flight_requests is released
    7780              : // last on every path, once conn is closed or back in the idle list, or the
    7781              : // drain could free srv under us.
    7782         1049 : static inline __attribute__((always_inline)) void task_tail(
    7783              :     chttpsvr_conn *conn, struct chttpserver *srv, chttp1_stream *stream,
    7784              :     chttpsvr_req *req, bool prepared, bool keep_alive, bool response_out) {
    7785         1049 :   size_t reclaimed_len = 0;
    7786         3148 :   char *reclaimed =
    7787          929 :       prepared ? chttp1_stream_take_leftover(stream, &reclaimed_len) : NULL;
    7788              : 
    7789         1049 :   if (prepared) chttp1_stream_release(stream);
    7790         1050 :   destroy_req_scratch(req);
    7791              : 
    7792         1050 :   if (!keep_alive) ccol__mem_free(conn->m_procs, reclaimed);
    7793              : 
    7794         1050 :   if (!keep_alive) {
    7795          386 :     if (__builtin_expect(conn->wp_active, 0)) {
    7796           22 :       conn_drop_request_state(conn);
    7797           22 :       conn_park_write(conn, srv);
    7798          497 :       return;
    7799              :     }
    7800          715 :     if (__builtin_expect(response_out && (reclaimed_len != 0 ||
    7801          351 :                                           conn_request_bytes_may_remain(conn)),
    7802              :                          0))
    7803           64 :       conn_linger(conn);
    7804              :     else
    7805          300 :       conn_close(conn);
    7806          364 :     release_in_flight(srv);
    7807          364 :     return;
    7808              :   }
    7809              : 
    7810          664 :   diverted_list_remove(conn);
    7811          664 :   conn_reset_for_request(conn);
    7812          664 :   conn->state = CONN_ST_READING_HEADERS;
    7813              : 
    7814          664 :   if (reclaimed) {
    7815           88 :     conn->carry_over = reclaimed;
    7816           88 :     conn->carry_over_len = reclaimed_len;
    7817          576 :   } else if (__builtin_expect(reclaimed_len != 0, 0)) {
    7818            1 :     conn_close(conn);
    7819            1 :     release_in_flight(srv);
    7820            1 :     return;
    7821              :   }
    7822              : 
    7823          663 :   if (conn->carry_over_len > 0) {
    7824           89 :     char *lo = conn->carry_over;
    7825           89 :     size_t lo_len = conn->carry_over_len;
    7826           89 :     conn->carry_over = NULL;
    7827           89 :     conn->carry_over_len = 0;
    7828           89 :     ccol_memmgmt_procs *mp = srv->m_procs;
    7829           89 :     bool need_more = conn_feed_bytes(conn, lo, lo_len);
    7830           89 :     ccol__mem_free(mp, lo);
    7831           89 :     if (!need_more) {
    7832           86 :       release_in_flight(srv);
    7833           86 :       return;
    7834              :     }
    7835              :   }
    7836              : 
    7837          577 :   cselect_dir tail_dir = cselect_read;
    7838          577 :   while (conn->tls && ctls_conn_has_pending_input(conn->tls)) {
    7839            2 :     char tls_buf[8192];
    7840            2 :     ssize_t n = ctls_conn_read(conn->tls, tls_buf, sizeof(tls_buf));
    7841            2 :     if (n < 0 && errno == EINTR) continue;
    7842            0 :     if (n < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
    7843            0 :       if (ctls_conn_wants_write(conn->tls)) tail_dir = cselect_write;
    7844            0 :       break;
    7845              :     }
    7846            2 :     if (n <= 0) {
    7847            0 :       conn_close(conn);
    7848            0 :       release_in_flight(srv);
    7849            2 :       return;
    7850              :     }
    7851            2 :     if (!conn_feed_bytes(conn, tls_buf, (size_t)n)) {
    7852            2 :       release_in_flight(srv);
    7853            2 :       return;
    7854              :     }
    7855              :   }
    7856              : 
    7857          575 :   if (conn->reg) {
    7858          421 :     if (conn_reg_modify(conn, tail_dir) != ccol_success) {
    7859            0 :       conn_close(conn);
    7860            0 :       release_in_flight(srv);
    7861            0 :       return;
    7862              :     }
    7863          421 :     if (ceventloop_resume(srv_engine_bundler.reactor, conn->reg) !=
    7864              :         ccol_success) {
    7865            0 :       conn_close(conn);
    7866            0 :       release_in_flight(srv);
    7867            0 :       return;
    7868              :     }
    7869              :   } else {
    7870          154 :     char *err = NULL;
    7871          308 :     conn->reg = ceventloop_add(
    7872          154 :         srv_engine_bundler.reactor, cselectable_fd(conn->fd, tail_dir),
    7873          154 :         (ceventloop_handlers){.on_readable = conn_on_readable,
    7874              :                               .on_writable = conn_on_writable,
    7875              :                               .on_error = conn_on_error,
    7876              :                               .on_removed = conn_on_removed},
    7877              :         conn, &err);
    7878          154 :     if (!conn->reg) {
    7879            0 :       conn_close(conn);
    7880            0 :       release_in_flight(srv);
    7881            0 :       return;
    7882              :     }
    7883          154 :     conn->reg_dir = (uint8_t)tail_dir;
    7884          154 :     atomic_fetch_add(&conn->lifetime_refs, 1);
    7885          154 :     atomic_fetch_add(&srv->lifetime_refs, 1);
    7886              :   }
    7887          575 :   idle_list_add(conn);
    7888          575 :   release_in_flight(srv);
    7889              : }
    7890              : 
    7891              : // Ends a request whose body is read: Frees the body, decides keep-alive
    7892              : // (complete message, client allows it, body not too large, server not draining)
    7893              : // and sends the response, then calls task_tail. A response never waits for a
    7894              : // slow reader on this thread; a full socket parks the connection. Nothing is
    7895              : // sent after a failed interim 100 Continue, because part of that line may be on
    7896              : // the wire.
    7897         1033 : static inline __attribute__((always_inline)) void task_finish(
    7898              :     chttpsvr_conn *conn, struct chttpserver *srv, chttp1_stream *stream,
    7899              :     chttpsvr_req *req, bool prepared, bool aborted, unsigned write_timeout_ms) {
    7900         2066 :   conn_drop_body(conn);
    7901         2066 :   bool msg_fully_parsed =
    7902         1033 :       prepared && chttp1_parser_message_complete(&conn->parser);
    7903         1950 :   bool keep_alive = prepared && !aborted && msg_fully_parsed &&
    7904          966 :                     chttp1_should_keep_alive(&conn->parser) &&
    7905         1712 :                     !conn->body_too_large && !srv_draining(srv);
    7906              : 
    7907         1033 :   stream->write_nonblocking = true;
    7908         2062 :   bool sent = prepared && !conn->interim_write_failed &&
    7909         1030 :               send_response(stream, &conn->resp, keep_alive, write_timeout_ms,
    7910         1030 :                             conn->method == CHTTP_HEAD, conn, false);
    7911              :   if (!sent) keep_alive = false;
    7912              : 
    7913         1032 :   task_tail(conn, srv, stream, req, prepared, keep_alive, sent);
    7914              : }
    7915              : 
    7916              : // Worker task for a newly diverted request: Reads the body of a buffered route,
    7917              : // runs the middleware chain and the handler, and ends through task_finish. A
    7918              : // request still queued when a teardown started (srv_draining) gets a 503 with
    7919              : // Connection: close instead of a handler.
    7920              : // If copying the carry-over fails the stream is prepared without it, so the
    7921              : // client still gets an error response; the body is then lost and the handler
    7922              : // doesn't run. A buffered route sends its 100 Continue here when a body is
    7923              : // still expected; a streaming route defers it to chttpsvr_req_read, so its
    7924              : // handler can reject without inviting the upload. "OPTIONS *" is answered with
    7925              : // 200 and no handler, reading and discarding a body up to
    7926              : // CHTTPSVR_OPTIONS_STAR_MAX_BODY. A body that stalls or must wait for memory
    7927              : // parks the connection and the thread returns. A failed buffered body maps to
    7928              : // 413, 408, 400 (malformed) or 500.
    7929         1050 : static void task_worker(void *arg) {
    7930         1050 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    7931         1050 :   struct chttpserver *srv = conn->srv;
    7932         1050 :   chttpsvr_mark_worker_thread(srv);
    7933              : 
    7934         1050 :   if (__builtin_expect(srv_draining(srv), 0)) {
    7935            2 :     ccol__mem_free(conn->m_procs, conn->carry_over);
    7936            2 :     conn->carry_over = NULL;
    7937            2 :     conn->carry_over_len = 0;
    7938            2 :     conn->req_rejected = true;
    7939            2 :     conn->reject_status = CHTTP_STATUS_SERVICE_UNAVAILABLE;
    7940            2 :     conn_reject_via_pool(conn);
    7941          122 :     return;
    7942              :   }
    7943              : 
    7944         1048 :   chttp1_stream stream;
    7945         1048 :   bool prepared;
    7946              : #ifdef RUNNING_UNIT_TESTS
    7947         1048 :   if (atomic_load(&g_force_stream_prepare_fail_for_tests)) {
    7948              :     prepared = false;
    7949              :   } else
    7950              : #endif
    7951         1047 :       if (conn->tls)
    7952           94 :     prepared = chttp1_stream_prepare_tls(&stream, conn->fd, conn->tls,
    7953           94 :                                          conn->carry_over, conn->carry_over_len,
    7954              :                                          conn->m_procs);
    7955              :   else
    7956          953 :     prepared = chttp1_stream_prepare(&stream, conn->fd, conn->carry_over,
    7957              :                                      conn->carry_over_len, conn->m_procs);
    7958         1048 :   bool body_unavailable = !prepared;
    7959         1048 :   if (body_unavailable) {
    7960            1 :     prepared =
    7961            1 :         conn->tls
    7962            0 :             ? chttp1_stream_prepare_tls(&stream, conn->fd, conn->tls, NULL, 0,
    7963              :                                         conn->m_procs)
    7964            1 :             : chttp1_stream_prepare(&stream, conn->fd, NULL, 0, conn->m_procs);
    7965              :   }
    7966         1048 :   stream.fd_nonblocking = true;
    7967         1048 :   ccol__mem_free(conn->m_procs, conn->carry_over);
    7968         1048 :   conn->carry_over = NULL;
    7969         1048 :   conn->carry_over_len = 0;
    7970              : 
    7971         1048 :   unsigned write_timeout_ms = atomic_load(&srv->response_write_timeout_ms);
    7972         2096 :   bool options_star_body_refused =
    7973         1051 :       conn->options_star && chttp1_has_content_length(&conn->parser) &&
    7974            3 :       chttp1_declared_content_length(&conn->parser) >
    7975              :           (uint64_t)CHTTPSVR_OPTIONS_STAR_MAX_BODY;
    7976         1048 :   if (prepared && !body_unavailable && conn->expects_continue &&
    7977           39 :       !conn->matched_route->is_streaming && !options_star_body_refused &&
    7978           17 :       !chttp1_parser_message_complete(&conn->parser)) {
    7979           16 :     stream.write_nonblocking = true;
    7980           16 :     int ic = write_interim_continue(conn, &stream, write_timeout_ms);
    7981           16 :     conn->interim_continue_sent = true;
    7982           16 :     if (ic < 0) {
    7983            1 :       chttp1_stream_release(&stream);
    7984            1 :       conn_park_write(conn, srv);
    7985            1 :       return;
    7986              :     }
    7987           15 :     if (ic == 0) conn->interim_write_failed = true;
    7988              :   }
    7989              : 
    7990         1047 :   chttpsvr_req req;
    7991         1047 :   memset(&req, 0, sizeof(req));
    7992         1047 :   req.conn = conn;
    7993         1047 :   req.stream = prepared ? &stream : NULL;
    7994         1047 :   req.param_names = (const char **)conn->matched_route->param_names;
    7995         1047 :   req.m_procs = conn->m_procs;
    7996              : 
    7997         1047 :   ccol_retval body_err = ccol_success;
    7998         1047 :   bool aborted = conn->interim_write_failed;
    7999         1047 :   if (!aborted && conn->options_star) {
    8000           52 :     bool body_ok = prepared && !body_unavailable && !options_star_body_refused;
    8001           51 :     if (body_ok) {
    8002           51 :       ccol_retval star_err = drain_body(conn, &stream);
    8003           51 :       if (star_err == CHTTPSVR_BODY_PARKED) {
    8004            1 :         task_park_body(conn, srv, &stream, &req);
    8005            1 :         return;
    8006              :       }
    8007           50 :       body_ok = (star_err == ccol_success);
    8008              :     }
    8009           51 :     conn->resp.status_code = CHTTP_STATUS_OK;
    8010           51 :     aborted = !body_ok;
    8011          994 :   } else if (!aborted) {
    8012          994 :     if (body_unavailable) {
    8013              :       body_err = ccol_not_enough_memory;
    8014          993 :     } else if (prepared) {
    8015          993 :       if (!conn->matched_route->is_streaming) {
    8016          905 :         body_err = drain_body(conn, &stream);
    8017          905 :         if (body_err != CHTTPSVR_BODY_PARKED) mem_settle(conn);
    8018              :       }
    8019              :     } else {
    8020              :       body_err = ccol_not_enough_memory;
    8021              :     }
    8022              : 
    8023          906 :     if (body_err != ccol_success &&
    8024          120 :         (body_unavailable || !conn->matched_route->is_streaming)) {
    8025          121 :       if (body_err == CHTTPSVR_BODY_PARKED) {
    8026          116 :         task_park_body(conn, srv, &stream, &req);
    8027          116 :         return;
    8028              :       }
    8029           10 :       conn->resp.status_code =
    8030              :           (body_err == ccol_msg_too_large) ? CHTTP_STATUS_PAYLOAD_TOO_LARGE
    8031            5 :           : (body_err == ccol_timed_out)   ? CHTTP_STATUS_REQUEST_TIMEOUT
    8032            4 :           : conn->body_malformed           ? CHTTP_STATUS_BAD_REQUEST
    8033            4 :                                            : CHTTP_STATUS_INTERNAL_ERROR;
    8034            5 :       aborted = true;
    8035              :     } else {
    8036          873 :       chttpsvr_next(&req, &conn->resp);
    8037              :     }
    8038              :   }
    8039              : 
    8040         1860 :   task_finish(conn, srv, &stream, &req, prepared, aborted, write_timeout_ms);
    8041              : }
    8042              : 
    8043              : static void task_continue_write(chttpsvr_conn *conn, struct chttpserver *srv,
    8044              :                                 chttp1_stream *stream, bool expired);
    8045              : static void task_continue_interim(chttpsvr_conn *conn, struct chttpserver *srv,
    8046              :                                   bool expired);
    8047              : static void task_read_body_and_finish(chttpsvr_conn *conn,
    8048              :                                       struct chttpserver *srv,
    8049              :                                       chttp1_stream *stream, bool expired);
    8050              : 
    8051              : // Worker task for a parked connection the reactor handed back (see
    8052              : // conn_resume_parked). It judges the park's limits at the claim time, since the
    8053              : // sweep only looks once a second, and takes the queue wait off the client's
    8054              : // clocks. Then it continues a parked interim line (task_continue_interim), a
    8055              : // parked response (task_continue_write), or a parked body
    8056              : // (task_read_body_and_finish). The stream starts empty: A body only parks with
    8057              : // an empty carry-over, and a parked response's pipelined bytes wait on the
    8058              : // connection.
    8059          446 : static void task_resume(void *arg) {
    8060          446 :   chttpsvr_conn *conn = (chttpsvr_conn *)arg;
    8061          446 :   struct chttpserver *srv = conn->srv;
    8062          446 :   chttpsvr_mark_worker_thread(srv);
    8063          446 :   uint8_t kind = conn->park;
    8064          446 :   struct timespec now, now_slow;
    8065          446 :   clock_gettime(CLOCK_MONOTONIC, &now);
    8066          446 :   slow_clock(&now_slow);
    8067          446 :   bool expired = parked_expired(srv, conn, conn->claim_mono, conn->claim_slow);
    8068          446 :   if (!expired) conn_uncharge_queue_wait(conn, now, now_slow);
    8069          446 :   conn->park = CONN_PARK_NONE;
    8070          446 :   conn->rate_queued = 0;
    8071              : 
    8072          446 :   chttp1_stream stream;
    8073          446 :   if (kind == CONN_PARK_WRITE && conn->wp_interim) {
    8074            1 :     task_continue_interim(conn, srv, expired);
    8075          133 :     return;
    8076              :   }
    8077          445 :   if (conn->tls)
    8078            8 :     chttp1_stream_prepare_tls(&stream, conn->fd, conn->tls, NULL, 0,
    8079              :                               conn->m_procs);
    8080              :   else
    8081          437 :     chttp1_stream_prepare(&stream, conn->fd, NULL, 0, conn->m_procs);
    8082          445 :   stream.fd_nonblocking = true;
    8083              : 
    8084          445 :   if (kind == CONN_PARK_WRITE) {
    8085          131 :     task_continue_write(conn, srv, &stream, expired);
    8086          131 :     return;
    8087              :   }
    8088          314 :   task_read_body_and_finish(conn, srv, &stream, expired);
    8089              : }
    8090              : 
    8091              : // Reads the rest of a buffered body after a park or after its 100 Continue went
    8092              : // out, runs the handler and ends the request through task_finish, as
    8093              : // task_worker does. The caller prepared stream and gives it up here. expired
    8094              : // means a park limit ran out, which answers 408. It parks again if the body
    8095              : // stalls, and otherwise resets the receive low-water mark and settles the body
    8096              : // reservation.
    8097          315 : static void task_read_body_and_finish(chttpsvr_conn *conn,
    8098              :                                       struct chttpserver *srv,
    8099              :                                       chttp1_stream *stream, bool expired) {
    8100          315 :   unsigned write_timeout_ms = atomic_load(&srv->response_write_timeout_ms);
    8101          315 :   chttpsvr_req req;
    8102          315 :   memset(&req, 0, sizeof(req));
    8103          315 :   req.conn = conn;
    8104          315 :   req.stream = stream;
    8105          315 :   req.param_names = (const char **)conn->matched_route->param_names;
    8106          315 :   req.m_procs = conn->m_procs;
    8107              : 
    8108          315 :   ccol_retval body_err = ccol_timed_out;
    8109          315 :   if (!expired) body_err = drain_body(conn, stream);
    8110          315 :   if (body_err == CHTTPSVR_BODY_PARKED) {
    8111          212 :     task_park_body(conn, srv, stream, &req);
    8112          212 :     return;
    8113              :   }
    8114          103 :   conn_reset_rcvlowat(conn);
    8115          103 :   mem_settle(conn);
    8116              : 
    8117          103 :   bool aborted = false;
    8118          103 :   if (conn->options_star) {
    8119            1 :     conn->resp.status_code = CHTTP_STATUS_OK;
    8120            1 :     aborted = body_err != ccol_success;
    8121          102 :   } else if (body_err != ccol_success) {
    8122           82 :     conn->resp.status_code =
    8123              :         (body_err == ccol_msg_too_large) ? CHTTP_STATUS_PAYLOAD_TOO_LARGE
    8124           41 :         : (body_err == ccol_timed_out)   ? CHTTP_STATUS_REQUEST_TIMEOUT
    8125           39 :         : conn->body_malformed           ? CHTTP_STATUS_BAD_REQUEST
    8126           39 :                                          : CHTTP_STATUS_INTERNAL_ERROR;
    8127           41 :     aborted = true;
    8128              :   } else {
    8129           61 :     chttpsvr_next(&req, &conn->resp);
    8130              :   }
    8131          206 :   task_finish(conn, srv, stream, &req, true, aborted, write_timeout_ms);
    8132              : }
    8133              : 
    8134              : // Continues a parked response. A full socket parks the connection again. A
    8135              : // finished response ends through task_tail with the keep-alive decision of the
    8136              : // first write; a rejection's response ends like conn_reject_and_close, with a
    8137              : // lingering close when the client may still be sending. expired gives up the
    8138              : // write.
    8139          131 : static void task_continue_write(chttpsvr_conn *conn, struct chttpserver *srv,
    8140              :                                 chttp1_stream *stream, bool expired) {
    8141          131 :   stream->write_nonblocking = true;
    8142          131 :   int r = expired ? 0 : send_response_continue(stream, conn);
    8143          131 :   if (r < 0) {
    8144          109 :     chttp1_stream_release(stream);
    8145          109 :     conn_park_write(conn, srv);
    8146          223 :     return;
    8147              :   }
    8148           22 :   bool keep_alive = r == 1 && conn->wp_keep_alive && !srv_draining(srv);
    8149           22 :   conn_end_parked_write(conn);
    8150           22 :   if (conn->wp_reject) {
    8151            5 :     conn->wp_reject = false;
    8152            5 :     chttp1_stream_release(stream);
    8153            5 :     if (r == 1 && conn_request_bytes_may_remain(conn))
    8154            0 :       conn_linger(conn);
    8155              :     else
    8156            5 :       conn_close(conn);
    8157            5 :     release_in_flight(srv);
    8158            5 :     return;
    8159              :   }
    8160           17 :   chttpsvr_req req;
    8161           17 :   memset(&req, 0, sizeof(req));
    8162           34 :   task_tail(conn, srv, stream, &req, true, keep_alive, r == 1);
    8163              : }
    8164              : 
    8165              : // Continues a buffered request whose 100 Continue line ran into a full socket.
    8166              : // The body bytes that came with the headers go into the stream first. Once the
    8167              : // line is out the body is read and the request ends as in task_worker. If the
    8168              : // socket is full again, the carry-over goes back onto conn and the connection
    8169              : // parks again. If the line can't be finished (a limit ran out, the write
    8170              : // failed, or a copy failed) the connection closes with no response, because
    8171              : // part of the line may be on the wire.
    8172            1 : static void task_continue_interim(chttpsvr_conn *conn, struct chttpserver *srv,
    8173              :                                   bool expired) {
    8174            1 :   chttp1_stream stream;
    8175            1 :   bool carried;
    8176            1 :   if (conn->tls)
    8177            0 :     carried = chttp1_stream_prepare_tls(&stream, conn->fd, conn->tls,
    8178            0 :                                         conn->carry_over, conn->carry_over_len,
    8179              :                                         conn->m_procs);
    8180              :   else
    8181            1 :     carried = chttp1_stream_prepare(&stream, conn->fd, conn->carry_over,
    8182              :                                     conn->carry_over_len, conn->m_procs);
    8183            1 :   if (!carried) {
    8184            0 :     if (conn->tls)
    8185            0 :       chttp1_stream_prepare_tls(&stream, conn->fd, conn->tls, NULL, 0,
    8186              :                                 conn->m_procs);
    8187              :     else
    8188            0 :       chttp1_stream_prepare(&stream, conn->fd, NULL, 0, conn->m_procs);
    8189              :   }
    8190            1 :   ccol__mem_free(conn->m_procs, conn->carry_over);
    8191            1 :   conn->carry_over = NULL;
    8192            1 :   conn->carry_over_len = 0;
    8193            1 :   stream.fd_nonblocking = true;
    8194            1 :   stream.write_nonblocking = true;
    8195            1 :   int r = expired || !carried ? 0 : send_response_continue(&stream, conn);
    8196            1 :   if (r < 0) {
    8197            0 :     size_t lo_len = 0;
    8198            0 :     char *lo = chttp1_stream_take_leftover(&stream, &lo_len);
    8199            0 :     chttp1_stream_release(&stream);
    8200            0 :     if (lo_len && !lo) {
    8201            0 :       conn_end_parked_write(conn);
    8202            0 :       conn->wp_interim = false;
    8203            0 :       conn->interim_write_failed = true;
    8204            0 :       chttpsvr_req req;
    8205            0 :       memset(&req, 0, sizeof(req));
    8206            0 :       task_tail(conn, srv, &stream, &req, false, false, false);
    8207            0 :       return;
    8208              :     }
    8209            0 :     conn->carry_over = lo;
    8210            0 :     conn->carry_over_len = lo_len;
    8211            0 :     conn_park_write(conn, srv);
    8212            0 :     return;
    8213              :   }
    8214            1 :   conn_end_parked_write(conn);
    8215            1 :   conn->wp_interim = false;
    8216            1 :   conn->write_deadline_set = false;
    8217            1 :   conn->rate_active = false;
    8218            1 :   if (r == 0) {
    8219            0 :     conn->interim_write_failed = true;
    8220            0 :     chttpsvr_req req;
    8221            0 :     memset(&req, 0, sizeof(req));
    8222            0 :     task_tail(conn, srv, &stream, &req, true, false, false);
    8223            0 :     return;
    8224              :   }
    8225            1 :   task_read_body_and_finish(conn, srv, &stream, false);
    8226              : }
    8227              : 
    8228              : // Listener: Accept and socket options.
    8229              : //
    8230              : // Shortest gap in seconds between two accept-failure log lines of one server,
    8231              : // so a lasting failure can't flood the log.
    8232              : #define CHTTPSVR_ACCEPT_ERR_LOG_INTERVAL_SEC 5
    8233              : // Most connections one listener dispatch accepts before it returns to the
    8234              : // reactor.
    8235              : #define CHTTPSVR_ACCEPT_BATCH_LIMIT 64u
    8236              : 
    8237              : // Tells whether an accept4() failure is about one pending connection rather
    8238              : // than the listener, so the accept loop can go straight on to the next
    8239              : // connection in the backlog. The list is ECONNABORTED plus the pending network
    8240              : // errors and the firewall EPERM that accept(2) documents for Linux.
    8241           22 : static bool accept_errno_is_transient(int e) {
    8242           22 :   switch (e) {
    8243              :     case ECONNABORTED:
    8244              :     case EPROTO:
    8245              :     case ENETDOWN:
    8246              :     case ENETUNREACH:
    8247              :     case ENOPROTOOPT:
    8248              :     case EHOSTDOWN:
    8249              : #ifdef ENONET
    8250              :     case ENONET:
    8251              : #endif
    8252              :     case EHOSTUNREACH:
    8253              :     case EOPNOTSUPP:
    8254              :     case EPERM:
    8255              :     case ETIMEDOUT:
    8256              : #ifdef ENOSR
    8257              :     case ENOSR:
    8258              : #endif
    8259              :     case ESOCKTNOSUPPORT:
    8260              :     case EPROTONOSUPPORT:
    8261              :       return true;
    8262            8 :     default:
    8263            8 :       return false;
    8264              :   }
    8265              : }
    8266              : 
    8267              : // Tells whether an accept4() failure comes from a process or system resource
    8268              : // running out (EMFILE, ENFILE, ENOBUFS, ENOMEM), which a retry won't fix until
    8269              : // something else frees it. It only labels the log line. The accept loop pauses
    8270              : // the listener for every errno that isn't transient, because a level-triggered
    8271              : // listen backlog would otherwise dispatch again and again; the idle sweep
    8272              : // resumes it later, so the shared reactor thread never sleeps.
    8273           11 : static bool accept_errno_is_resource_exhaustion(int e) {
    8274           11 :   switch (e) {
    8275              :     case EMFILE:
    8276              :     case ENFILE:
    8277              :     case ENOBUFS:
    8278              :     case ENOMEM:
    8279              :       return true;
    8280            6 :     default:
    8281            6 :       return false;
    8282              :   }
    8283              : }
    8284              : 
    8285              : #ifdef RUNNING_UNIT_TESTS
    8286              : // Test hooks that expose the two errno classifiers, since producing those
    8287              : // errors for real depends on the environment.
    8288           21 : bool chttpsvr__accept_errno_is_transient_for_tests(int e) {
    8289           21 :   return accept_errno_is_transient(e);
    8290              : }
    8291           10 : bool chttpsvr__accept_errno_is_resource_exhaustion_for_tests(int e) {
    8292           10 :   return accept_errno_is_resource_exhaustion(e);
    8293              : }
    8294              : #endif
    8295              : 
    8296              : // Rate limit for the accept loop's diagnostics: Returns true at most once per
    8297              : // CHTTPSVR_ACCEPT_ERR_LOG_INTERVAL_SEC for srv, and records the moment in
    8298              : // srv->last_accept_err_log when it does. Only the listener's own dispatch
    8299              : // touches those fields.
    8300            3 : static bool listener_accept_err_log_gate(struct chttpserver *srv) {
    8301            3 :   struct timespec now;
    8302            3 :   clock_gettime(CLOCK_MONOTONIC, &now);
    8303            3 :   if (srv->last_accept_err_log_set &&
    8304            0 :       now.tv_sec - srv->last_accept_err_log.tv_sec <
    8305              :           CHTTPSVR_ACCEPT_ERR_LOG_INTERVAL_SEC)
    8306              :     return false;
    8307            3 :   srv->last_accept_err_log = now;
    8308            3 :   srv->last_accept_err_log_set = true;
    8309            3 :   return true;
    8310              : }
    8311              : 
    8312              : // Returns the text of err through the thread-safe strerror_r, in either form:
    8313              : // the GNU one (glibc with _GNU_SOURCE) may return its own string and leave buf
    8314              : // alone, the POSIX one fills buf.
    8315            1 : static const char *errno_text(int err, char *buf, size_t len) {
    8316              : #if defined(__GLIBC__) && defined(_GNU_SOURCE)
    8317            1 :   return strerror_r(err, buf, len);
    8318              : #else
    8319              :   if (strerror_r(err, buf, len) != 0) snprintf(buf, len, "error %d", err);
    8320              :   return buf;
    8321              : #endif
    8322              : }
    8323              : 
    8324              : // Logs an unexpected accept4() failure through the engine logger, rate limited
    8325              : // by listener_accept_err_log_gate. The line marks the resource exhaustion
    8326              : // cases, as a hint for the operator; anything else may be worth reporting as a
    8327              : // bug. It uses errno_text because two listeners can log at the same moment on
    8328              : // two reactor threads.
    8329            1 : static void listener_log_accept_err_rate_limited(struct chttpserver *srv,
    8330              :                                                  int err) {
    8331            1 :   if (!listener_accept_err_log_gate(srv)) return;
    8332            1 :   char errbuf[128];
    8333            1 :   SRV_ENGINE_LOG(
    8334              :       clog_warn, "accept() failed errno=%d (%s)%s", err,
    8335              :       errno_text(err, errbuf, sizeof(errbuf)),
    8336              :       accept_errno_is_resource_exhaustion(err) ? " [resource exhaustion]" : "");
    8337              : }
    8338              : 
    8339              : #ifdef RUNNING_UNIT_TESTS
    8340              : // Test counters for the two listener pauses: How often an allocation failure
    8341              : // right after an accept paused a listener, and how often
    8342              : // listener_pause_for_resource_pressure really paused one. The sweep clears the
    8343              : // pause flag about once a second, so a test reads the difference of a counter
    8344              : // over its own window instead of polling the flag.
    8345              : static _Atomic size_t g_listener_alloc_failure_pause_count_for_tests = 0;
    8346              : // Test hook: Gives the number of pauses after an allocation failure so far.
    8347          149 : size_t chttpsvr__listener_alloc_failure_pause_count_for_tests(void) {
    8348          149 :   return atomic_load(&g_listener_alloc_failure_pause_count_for_tests);
    8349              : }
    8350              : 
    8351              : static _Atomic size_t g_listener_resource_pause_count_for_tests = 0;
    8352              : // Test hook: Gives the number of successful resource-pressure pauses so far.
    8353            6 : size_t chttpsvr__listener_resource_pause_count_for_tests(void) {
    8354            6 :   return atomic_load(&g_listener_resource_pause_count_for_tests);
    8355              : }
    8356              : #endif
    8357              : 
    8358              : // Pauses srv's listener registration after accept failed for lack of a resource
    8359              : // (or for any other reason the loop can't retry at once), so a backlog that
    8360              : // can't be served doesn't make the level-triggered reactor call the accept loop
    8361              : // again and again. It reads srv->listen_reg under srv->mutex. Only when the
    8362              : // pause succeeds does it set srv->listener_paused_for_resource_pressure, which
    8363              : // tells the idle sweep to resume the listener on a later tick. With no
    8364              : // registration, or a failed pause (which only a concurrent remove could cause,
    8365              : // and listener_dispatch_pins prevents that), it does nothing.
    8366            3 : static void listener_pause_for_resource_pressure(struct chttpserver *srv) {
    8367            3 :   ccol__mutex_lock(srv->mutex);
    8368            3 :   ceventloop_reg lreg = srv->listen_reg;
    8369            3 :   ccol__mutex_unlock(srv->mutex);
    8370            3 :   if (!lreg) return;
    8371            3 :   if (ceventloop_pause(srv_engine_bundler.reactor, lreg) == ccol_success) {
    8372            3 :     atomic_store(&srv->listener_paused_for_resource_pressure, true);
    8373              : #ifdef RUNNING_UNIT_TESTS
    8374            3 :     atomic_fetch_add(&g_listener_resource_pause_count_for_tests, 1);
    8375              : #endif
    8376              :   }
    8377              : }
    8378              : 
    8379              : // Handles a failed allocation right after a successful accept (conn_create or
    8380              : // ctls_conn_create_server gave NULL): It logs what failed, through the same
    8381              : // rate-limit gate as the accept errors, and pauses the listener. Without the
    8382              : // pause a custom allocator that has run dry would make the loop accept, fail,
    8383              : // close and repeat for as long as clients keep connecting.
    8384            2 : static void listener_log_and_pause_for_alloc_failure(struct chttpserver *srv,
    8385              :                                                      const char *what) {
    8386            2 :   if (listener_accept_err_log_gate(srv))
    8387            2 :     SRV_ENGINE_LOG(clog_warn, "%s failed after accept()", what);
    8388              : #ifdef RUNNING_UNIT_TESTS
    8389            2 :   atomic_fetch_add(&g_listener_alloc_failure_pause_count_for_tests, 1);
    8390              : #endif
    8391            2 :   listener_pause_for_resource_pressure(srv);
    8392            2 : }
    8393              : 
    8394              : #ifdef RUNNING_UNIT_TESTS
    8395              : // Test counter of accepted unix:// connections whose socket buffers
    8396              : // apply_accepted_socket_options raised, with its reader.
    8397              : static _Atomic size_t g_accepted_sockbuf_raise_count_for_tests = 0;
    8398            4 : size_t chttpsvr__accepted_sockbuf_raise_count_for_tests(void) {
    8399            4 :   return atomic_load(&g_accepted_sockbuf_raise_count_for_tests);
    8400              : }
    8401              : #endif
    8402              : 
    8403              : // Sets the socket options of a freshly accepted connection. The fd is already
    8404              : // non-blocking from accept, so no fcntl is needed. A TCP socket gets
    8405              : // TCP_NODELAY and, when enable_keepalive is set, SO_KEEPALIVE; its buffer sizes
    8406              : // stay as the kernel chose them, because setting SO_SNDBUF or SO_RCVBUF turns
    8407              : // Linux's buffer autotuning off and caps the throughput of connections with a
    8408              : // long round trip. A unix:// socket has no autotuning and can get small
    8409              : // defaults, so both of its buffers are raised to at least 128 KiB.
    8410         1288 : static void apply_accepted_socket_options(int fd, bool is_unix,
    8411              :                                           bool enable_keepalive) {
    8412         1288 :   int one = 1;
    8413         1288 :   if (!is_unix) {
    8414         1272 :     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
    8415         1272 :     if (enable_keepalive)
    8416            1 :       setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
    8417         1272 :     return;
    8418              :   }
    8419              : #ifdef RUNNING_UNIT_TESTS
    8420           16 :   atomic_fetch_add(&g_accepted_sockbuf_raise_count_for_tests, 1);
    8421              : #endif
    8422           16 :   int bufsz = 131072;
    8423           16 :   int cur = 0;
    8424           16 :   socklen_t cur_len = sizeof(cur);
    8425           16 :   if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &cur, &cur_len) != 0 || cur < bufsz)
    8426            0 :     setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &bufsz, sizeof(bufsz));
    8427           16 :   cur_len = sizeof(cur);
    8428           16 :   if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &cur, &cur_len) != 0 || cur < bufsz)
    8429            0 :     setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &bufsz, sizeof(bufsz));
    8430              : }
    8431              : 
    8432              : #ifdef RUNNING_UNIT_TESTS
    8433              : // Test counter of listener dispatches in the whole process. A test that holds a
    8434              : // server at max_connections reads its difference over a window: A paused
    8435              : // listener adds a few dispatches, a busy-looping one adds thousands.
    8436              : static _Atomic size_t g_listener_dispatch_count_for_tests = 0;
    8437            4 : size_t chttpsvr__listener_dispatch_count_for_tests(void) {
    8438            4 :   return atomic_load(&g_listener_dispatch_count_for_tests);
    8439              : }
    8440              : 
    8441              : // Test record of the most connections one dispatch of the accept loop accepted,
    8442              : // across all servers since the last reset, which a test compares with
    8443              : // CHTTPSVR_ACCEPT_BATCH_LIMIT. The three functions below read it, reset it and
    8444              : // raise it with a compare-and-swap loop.
    8445              : static _Atomic size_t g_listener_max_accepts_per_dispatch_for_tests = 0;
    8446            1 : size_t chttpsvr__listener_max_accepts_per_dispatch_for_tests(void) {
    8447            1 :   return atomic_load(&g_listener_max_accepts_per_dispatch_for_tests);
    8448              : }
    8449            1 : void chttpsvr__listener_max_accepts_per_dispatch_reset_for_tests(void) {
    8450            1 :   atomic_store(&g_listener_max_accepts_per_dispatch_for_tests, 0);
    8451            1 : }
    8452         2427 : static void listener_note_accepts_for_tests(size_t n) {
    8453         2427 :   size_t cur = atomic_load(&g_listener_max_accepts_per_dispatch_for_tests);
    8454           73 :   while (n > cur &&
    8455           73 :          !atomic_compare_exchange_weak(
    8456              :              &g_listener_max_accepts_per_dispatch_for_tests, &cur, n)) {
    8457         2427 :   }
    8458              : }
    8459              : 
    8460              : // Test hook state for a forced accept error. When the armed server is the one
    8461              : // dispatching, its next accept result is thrown away (a real connection is
    8462              : // closed unused) and replaced by a failure with the armed errno, then both
    8463              : // fields are cleared. It names one server because the reactor is shared by the
    8464              : // whole process, and another server's dispatch would otherwise take the forced
    8465              : // errno. It lets a test check how the loop treats an errno that is hard to
    8466              : // produce for real, such as EBADF or EINVAL.
    8467              : static _Atomic(struct chttpserver *) g_force_next_accept_errno_for_tests_srv =
    8468              :     NULL;
    8469              : static _Atomic int g_force_next_accept_errno_for_tests_val = 0;
    8470              : // Test hook: Arms the forced accept errno for the server behind h.
    8471            1 : void chttpsvr__force_next_accept_errno_for_tests(chttpsvr h, int errno_val) {
    8472            1 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
    8473            1 :   atomic_store(&g_force_next_accept_errno_for_tests_val, errno_val);
    8474            1 :   atomic_store(&g_force_next_accept_errno_for_tests_srv, raw);
    8475            1 : }
    8476              : #endif
    8477              : 
    8478              : // The accept loop of a listener. It accepts at most CHTTPSVR_ACCEPT_BATCH_LIMIT
    8479              : // connections per dispatch and goes back to the reactor, so a flood of connects
    8480              : // can't keep the single reactor thread from serving established connections;
    8481              : // the level-triggered registration brings it back while the backlog isn't
    8482              : // empty. Each accepted fd raises srv->current_connections, gets its socket
    8483              : // options, a connection object and, with TLS, a server TLS object, and is
    8484              : // pumped once.
    8485              : // At max_connections it pauses the listener instead of returning, since a plain
    8486              : // return would be dispatched again at once; it then checks the count again
    8487              : // after the pause and resumes if a slot freed meanwhile, because the sweep's
    8488              : // resume may have run just before the pause. Any accept error other than
    8489              : // EAGAIN, EINTR or a per-connection transient one pauses the listener as well,
    8490              : // and so does a failed allocation. The caller holds a listener_dispatch_pins
    8491              : // pin, which keeps lfd open for the whole call.
    8492         1141 : static void listener_on_readable_impl(struct chttpserver *srv, int lfd) {
    8493              : #ifdef RUNNING_UNIT_TESTS
    8494         1141 :   atomic_fetch_add(&g_listener_dispatch_count_for_tests, 1);
    8495         1141 :   size_t accepted_for_tests = 0;
    8496              : #endif
    8497              : 
    8498         2427 :   for (unsigned batch = 0; batch < CHTTPSVR_ACCEPT_BATCH_LIMIT; batch++) {
    8499              : #ifdef RUNNING_UNIT_TESTS
    8500         2426 :     listener_note_accepts_for_tests(accepted_for_tests);
    8501              : #endif
    8502         2426 :     size_t cap = atomic_load(&srv->max_connections);
    8503         2426 :     if (cap && atomic_load(&srv->current_connections) >= cap) {
    8504            4 :       ccol__mutex_lock(srv->mutex);
    8505            4 :       ceventloop_reg lreg = srv->listen_reg;
    8506            4 :       ccol__mutex_unlock(srv->mutex);
    8507            8 :       if (lreg &&
    8508            4 :           ceventloop_pause(srv_engine_bundler.reactor, lreg) == ccol_success) {
    8509            4 :         if (atomic_load(&srv->current_connections) < cap)
    8510            0 :           ceventloop_resume(srv_engine_bundler.reactor, lreg);
    8511              :       }
    8512         1140 :       return;
    8513              :     }
    8514              : 
    8515         2422 :     struct sockaddr_storage ss;
    8516         2422 :     socklen_t slen = sizeof(ss);
    8517         2422 :     int cfd = ccol_accept_nb(lfd, (struct sockaddr *)&ss, &slen);
    8518         2422 :     int accept_errno = cfd < 0 ? errno : 0;
    8519              : #ifdef RUNNING_UNIT_TESTS
    8520         2422 :     if (atomic_load(&g_force_next_accept_errno_for_tests_srv) == srv) {
    8521            1 :       int forced_errno =
    8522            1 :           atomic_exchange(&g_force_next_accept_errno_for_tests_val, 0);
    8523            1 :       atomic_store(&g_force_next_accept_errno_for_tests_srv, NULL);
    8524            1 :       if (forced_errno) {
    8525            1 :         if (cfd >= 0) close(cfd);
    8526              :         cfd = -1;
    8527              :         accept_errno = forced_errno;
    8528              :       }
    8529              :     }
    8530              : #endif
    8531         2421 :     if (cfd < 0) {
    8532         1134 :       if (accept_errno == EWOULDBLOCK || accept_errno == EAGAIN) return;
    8533            1 :       if (accept_errno == EINTR) continue;
    8534            1 :       if (accept_errno_is_transient(accept_errno)) continue;
    8535            1 :       listener_log_accept_err_rate_limited(srv, accept_errno);
    8536            1 :       listener_pause_for_resource_pressure(srv);
    8537            1 :       return;
    8538              :     }
    8539         1288 :     atomic_fetch_add(&srv->current_connections, 1);
    8540              : #ifdef RUNNING_UNIT_TESTS
    8541         1288 :     accepted_for_tests++;
    8542              : #endif
    8543         1288 :     apply_accepted_socket_options(cfd, atomic_load(&srv->is_unix_socket),
    8544         1288 :                                   srv->enable_keepalive);
    8545              : 
    8546         1288 :     ccol__call_once(srv_parser_bundler.once, init_parser_settings);
    8547         1288 :     chttpsvr_conn *conn = conn_create(srv, cfd, &srv_parser_bundler.settings);
    8548         1288 :     if (!conn) {
    8549            2 :       close(cfd);
    8550            2 :       atomic_fetch_sub(&srv->current_connections, 1);
    8551            2 :       listener_log_and_pause_for_alloc_failure(srv, "connection allocation");
    8552            2 :       return;
    8553              :     }
    8554              : 
    8555         1286 :     if (srv->tls_ctx) {
    8556           29 :       conn->tls = ctls_conn_create_server(srv->tls_ctx, cfd, conn, NULL);
    8557           29 :       if (!conn->tls) {
    8558            0 :         conn_free(conn);
    8559            0 :         listener_log_and_pause_for_alloc_failure(srv, "TLS connection setup");
    8560            0 :         return;
    8561              :       }
    8562           29 :       conn->state = CONN_ST_TLS_HANDSHAKE;
    8563              :     } else {
    8564         1257 :       conn->state = CONN_ST_READING_HEADERS;
    8565              :     }
    8566         1286 :     conn_pump(conn);
    8567              :   }
    8568              : #ifdef RUNNING_UNIT_TESTS
    8569            1 :   listener_note_accepts_for_tests(accepted_for_tests);
    8570              : #endif
    8571              : }
    8572              : 
    8573              : // The listener's on_readable callback. It pins srv through
    8574              : // srv->listener_dispatch_pins for the whole run of listener_on_readable_impl
    8575              : // and drops the pin last, broadcasting resolve_cv so chttpsvr_stop_internal's
    8576              : // wait can go on. The pin and the read of srv->listen_fd happen under
    8577              : // srv->mutex, which orders them against the stop that clears listen_fd and
    8578              : // waits for the pins. A dispatch whose fd differs from listen_fd (the server
    8579              : // stopped, or restarted on a new fd) returns at once: It must not accept on a
    8580              : // listener it wasn't registered for. srv's memory itself stays valid through
    8581              : // the lifetime_refs reference the registration holds.
    8582         1143 : static void listener_on_readable(ceventloop loop, ceventloop_reg reg,
    8583              :                                  cselectable *sel, void *arg) {
    8584         1143 :   (void)loop;
    8585         1143 :   (void)reg;
    8586         1143 :   struct chttpserver *srv = (struct chttpserver *)arg;
    8587              : 
    8588              : #ifdef RUNNING_UNIT_TESTS
    8589         1143 :   listener_dispatch_race_hook_wait_if_armed(true);
    8590              : #endif
    8591              : 
    8592         1143 :   ccol__mutex_lock(srv->mutex);
    8593         1143 :   atomic_fetch_add(&srv->listener_dispatch_pins, 1);
    8594         1143 :   int lfd = atomic_load(&srv->listen_fd);
    8595         1143 :   ccol__mutex_unlock(srv->mutex);
    8596              : 
    8597              : #ifdef RUNNING_UNIT_TESTS
    8598         1143 :   listener_dispatch_race_hook_wait_if_armed(false);
    8599              : #endif
    8600              : 
    8601         1143 :   if (lfd >= 0 && lfd == sel->fd) listener_on_readable_impl(srv, lfd);
    8602              : 
    8603         1143 :   ccol__mutex_lock(srv->mutex);
    8604         1143 :   atomic_fetch_sub(&srv->listener_dispatch_pins, 1);
    8605         1143 :   ccol__cond_var_broadcast(srv->resolve_cv);
    8606         1143 :   ccol__mutex_unlock(srv->mutex);
    8607         1143 : }
    8608              : 
    8609              : // The listener registration's on_removed callback, which runs once no dispatch
    8610              : // of it can still run. It drops the srv->lifetime_refs reference chttpsvr_start
    8611              : // took for the registration and runs chttpsvr_finish_destroy when that was the
    8612              : // last one.
    8613          300 : static void listener_on_removed(void *arg) {
    8614          300 :   struct chttpserver *srv = (struct chttpserver *)arg;
    8615          300 :   if (atomic_fetch_sub(&srv->lifetime_refs, 1) == 1)
    8616            1 :     chttpsvr_finish_destroy(srv);
    8617          300 : }
    8618              : 
    8619              : // Listen sockets. A host that starts with this prefix names a Unix domain
    8620              : // socket path.
    8621              : #define CHTTPSVR_UNIX_PREFIX "unix://"
    8622              : 
    8623              : // Removes a unix:// listener's socket file and releases what ub holds (path,
    8624              : // directory fd). The file is unlinked only while the name still points at the
    8625              : // socket this server bound (same dev and ino), so a file someone else put there
    8626              : // meanwhile stays. The gap between that check and the unlink can't be closed,
    8627              : // since POSIX has no unlink by inode.
    8628          300 : static void unix_bind_cleanup(chttpsvr_unix_bind *ub, ccol_memmgmt_procs *mp) {
    8629          300 :   if (!ub->path) return;
    8630           15 :   if (ub->dir_fd >= 0) {
    8631           15 :     struct stat st;
    8632           15 :     if (fstatat(ub->dir_fd, ub->base, &st, AT_SYMLINK_NOFOLLOW) == 0 &&
    8633           15 :         S_ISSOCK(st.st_mode) && st.st_dev == ub->dev && st.st_ino == ub->ino)
    8634           14 :       unlinkat(ub->dir_fd, ub->base, 0);
    8635           15 :     close(ub->dir_fd);
    8636              :   }
    8637           15 :   ccol__mem_free(mp, ub->path);
    8638           15 :   ub->path = NULL;
    8639           15 :   ub->base = NULL;
    8640           15 :   ub->dir_fd = -1;
    8641              : }
    8642              : 
    8643              : // Decides, before the bind, what to do with a file that already exists at a
    8644              : // unix:// path. It returns true when the bind may go ahead: Nothing is there,
    8645              : // or a stale socket that no one listens on was found and removed (only while
    8646              : // the name still points at the socket the probe saw). It returns false with
    8647              : // errno set when the start must fail and leave the file alone: EEXIST for
    8648              : // something that isn't a socket, so a configuration typo never deletes a
    8649              : // regular file, and EADDRINUSE when a live listener answers. The probe is a
    8650              : // non-blocking connect from a scratch socket; ECONNREFUSED means a socket file
    8651              : // with no listener.
    8652           17 : static bool unix_path_prepare(const struct sockaddr_un *addr) {
    8653           17 :   struct stat st;
    8654           17 :   if (lstat(addr->sun_path, &st) != 0) return errno == ENOENT;
    8655            3 :   if (!S_ISSOCK(st.st_mode)) {
    8656            1 :     SRV_ENGINE_LOG(clog_error,
    8657              :                    "unix socket path %s exists and is not a socket; "
    8658              :                    "leaving it in place",
    8659              :                    addr->sun_path);
    8660            1 :     errno = EEXIST;
    8661            1 :     return false;
    8662              :   }
    8663            2 :   int probe = ccol_socket_nb(AF_UNIX, SOCK_STREAM, 0);
    8664            2 :   if (probe < 0) return false;
    8665            2 :   int rc = connect(probe, (const struct sockaddr *)addr, sizeof(*addr));
    8666            2 :   int e = rc == 0 ? 0 : errno;
    8667            2 :   close(probe);
    8668            2 :   if (e == ECONNREFUSED) {
    8669            1 :     struct stat again;
    8670            1 :     if (lstat(addr->sun_path, &again) == 0 && S_ISSOCK(again.st_mode) &&
    8671            1 :         again.st_dev == st.st_dev && again.st_ino == st.st_ino)
    8672            1 :       unlink(addr->sun_path);
    8673            1 :     return true;
    8674              :   }
    8675            1 :   if (e == ENOENT) return true;
    8676            1 :   if (e == 0 || e == EAGAIN || e == EINPROGRESS) {
    8677            1 :     SRV_ENGINE_LOG(clog_error,
    8678              :                    "unix socket path %s: another server already listens "
    8679              :                    "on it",
    8680              :                    addr->sun_path);
    8681            1 :     e = EADDRINUSE;
    8682              :   }
    8683            1 :   errno = e;
    8684            1 :   return false;
    8685              : }
    8686              : 
    8687              : // Open flags of a unix:// path's directory descriptor. The descriptor only
    8688              : // names the directory for the *at() calls, so O_PATH is enough where the system
    8689              : // has it (no read permission needed); macOS doesn't.
    8690              : #if defined(O_PATH)
    8691              : #define UNIX_DIR_OPEN_FLAGS (O_PATH | O_DIRECTORY | O_CLOEXEC)
    8692              : #else
    8693              : #define UNIX_DIR_OPEN_FLAGS (O_RDONLY | O_DIRECTORY | O_CLOEXEC)
    8694              : #endif
    8695              : 
    8696              : // Opens the directory that holds path, for chttpsvr_unix_bind.dir_fd, and
    8697              : // points *base at the last component of path. It gives the fd, or -1 with errno
    8698              : // set (EINVAL for a path that ends in a slash).
    8699           18 : static int unix_open_dir(const char *path, const char **base) {
    8700           18 :   const char *slash = strrchr(path, '/');
    8701           18 :   if (!slash) {
    8702            1 :     *base = path;
    8703            1 :     return open(".", UNIX_DIR_OPEN_FLAGS);
    8704              :   }
    8705           17 :   *base = slash + 1;
    8706           17 :   if (!**base) {
    8707            0 :     errno = EINVAL;
    8708            0 :     return -1;
    8709              :   }
    8710           17 :   size_t dlen = slash == path ? 1 : (size_t)(slash - path);
    8711           17 :   char dir[sizeof(((struct sockaddr_un *)0)->sun_path)];
    8712           17 :   memcpy(dir, path, dlen);
    8713           17 :   dir[dlen] = '\0';
    8714           17 :   return open(dir, UNIX_DIR_OPEN_FLAGS);
    8715              : }
    8716              : 
    8717              : #ifdef RUNNING_UNIT_TESTS
    8718              : // Test record of the errno of the last failed listen socket setup, with its
    8719              : // reader.
    8720              : static _Atomic int g_last_listen_errno_for_tests = 0;
    8721            3 : int chttpsvr__last_listen_errno_for_tests(void) {
    8722            3 :   return atomic_load(&g_last_listen_errno_for_tests);
    8723              : }
    8724              : #endif
    8725              : 
    8726              : // Creates, binds and listens on a unix:// socket at path. It refuses an empty
    8727              : // path (EINVAL) and one too long for sun_path (ENAMETOOLONG), handles an
    8728              : // existing file through unix_path_prepare, and records the directory fd, the
    8729              : // base name and the dev and ino of the new socket in *ub so that the stop
    8730              : // removes only this socket. If the new socket can't be identified after bind,
    8731              : // the start fails and the file stays as a stale socket that the next start
    8732              : // replaces. It gives the listening fd, or -1 with errno set and nothing left
    8733              : // allocated.
    8734           20 : static int make_unix_listen_socket(const char *path, chttpsvr_unix_bind *ub,
    8735              :                                    ccol_memmgmt_procs *mp) {
    8736           20 :   if (!*path) {
    8737            1 :     errno = EINVAL;
    8738            1 :     return -1;
    8739              :   }
    8740           19 :   if (strlen(path) >= sizeof(((struct sockaddr_un *)0)->sun_path)) {
    8741            1 :     errno = ENAMETOOLONG;
    8742            1 :     return -1;
    8743              :   }
    8744           18 :   struct sockaddr_un addr;
    8745           18 :   memset(&addr, 0, sizeof(addr));
    8746           18 :   addr.sun_family = AF_UNIX;
    8747           18 :   strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
    8748              : 
    8749           18 :   chttpsvr_unix_bind b = {.path = NULL, .base = NULL, .dir_fd = -1};
    8750           18 :   b.path = ccol_strdup(mp, path);
    8751           18 :   if (!b.path) return -1;
    8752           18 :   const char *base_in_cfg = NULL;
    8753           18 :   b.dir_fd = unix_open_dir(path, &base_in_cfg);
    8754           18 :   if (b.dir_fd < 0) {
    8755            1 :     ccol__mem_free(mp, b.path);
    8756            1 :     return -1;
    8757              :   }
    8758           17 :   b.base = b.path + (base_in_cfg - path);
    8759              : 
    8760           17 :   int fd = -1;
    8761           17 :   if (unix_path_prepare(&addr)) fd = ccol_socket_nb(AF_UNIX, SOCK_STREAM, 0);
    8762           15 :   if (fd < 0) {
    8763            2 :     close(b.dir_fd);
    8764            2 :     ccol__mem_free(mp, b.path);
    8765            2 :     return -1;
    8766              :   }
    8767           15 :   struct stat st;
    8768           15 :   if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
    8769            0 :     close(fd);
    8770            0 :     close(b.dir_fd);
    8771            0 :     ccol__mem_free(mp, b.path);
    8772            0 :     return -1;
    8773              :   }
    8774           15 :   if (fstatat(b.dir_fd, b.base, &st, AT_SYMLINK_NOFOLLOW) != 0 ||
    8775           15 :       !S_ISSOCK(st.st_mode)) {
    8776            0 :     close(fd);
    8777            0 :     close(b.dir_fd);
    8778            0 :     ccol__mem_free(mp, b.path);
    8779            0 :     return -1;
    8780              :   }
    8781           15 :   b.dev = st.st_dev;
    8782           15 :   b.ino = st.st_ino;
    8783           15 :   if (listen(fd, SOMAXCONN) != 0) {
    8784            0 :     close(fd);
    8785            0 :     unix_bind_cleanup(&b, mp);
    8786            0 :     return -1;
    8787              :   }
    8788           15 :   *ub = b;
    8789           15 :   return fd;
    8790              : }
    8791              : 
    8792              : // Creates, binds and listens on one TCP socket with SO_REUSEADDR, and
    8793              : // SO_REUSEPORT when asked and available. v6only is -1 to keep the system's
    8794              : // IPV6_V6ONLY default, or 0 or 1 to set it. It gives the fd, or -1 with errno
    8795              : // set by the step that failed.
    8796          290 : static int bind_tcp(int family, const struct sockaddr *sa, socklen_t salen,
    8797              :                     bool enable_reuseport, int v6only) {
    8798          290 :   int fd = ccol_socket_nb(family, SOCK_STREAM, 0);
    8799          290 :   if (fd < 0) return -1;
    8800          290 :   int one = 1;
    8801          290 :   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    8802              : #ifdef SO_REUSEPORT
    8803          290 :   if (enable_reuseport)
    8804            2 :     setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
    8805              : #else
    8806              :   (void)enable_reuseport;
    8807              : #endif
    8808          299 :   if (family == AF_INET6 && v6only >= 0 &&
    8809            9 :       setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)) != 0) {
    8810            0 :     int e = errno;
    8811            0 :     close(fd);
    8812            0 :     errno = e;
    8813            0 :     return -1;
    8814              :   }
    8815          290 :   if (bind(fd, sa, salen) != 0 || listen(fd, SOMAXCONN) != 0) {
    8816            4 :     int e = errno;
    8817            4 :     close(fd);
    8818            4 :     errno = e;
    8819            4 :     return -1;
    8820              :   }
    8821              :   return fd;
    8822              : }
    8823              : 
    8824              : // Tells whether an IPv6 socket here can take IPv4 clients too; OpenBSD refuses
    8825              : // to turn IPV6_V6ONLY off, so it can't. make_listen_socket asks it to decide
    8826              : // whether to fall back to 0.0.0.0. When the probe socket fails for a reason
    8827              : // other than missing IPv6 (no descriptors or memory left), it says yes, so the
    8828              : // caller reports its own bind error instead of falling back.
    8829            1 : static bool ipv6_dual_stack_supported(void) {
    8830            1 :   int fd = ccol_socket_nb(AF_INET6, SOCK_STREAM, 0);
    8831            1 :   if (fd < 0) return errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT;
    8832            1 :   int off = 0;
    8833            1 :   bool ok = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off)) == 0;
    8834            1 :   close(fd);
    8835            1 :   return ok;
    8836              : }
    8837              : 
    8838              : // Opens the listener that host names, following Go's net listener. NULL or ""
    8839              : // gives one dual-stack socket on [::] (IPv6 only with ipv6_only), with a
    8840              : // fallback to 0.0.0.0 when the host has no IPv6 or the system no dual-stack
    8841              : // sockets. A literal address binds exactly that address, and "[addr]" binds the
    8842              : // address inside the brackets (a bracketed name is refused). A name binds its
    8843              : // first IPv4 address, else its first IPv6 one (the reverse with ipv6_only), and
    8844              : // only that one, so its bind error is the answer. "unix://path" goes to
    8845              : // make_unix_listen_socket.
    8846              : // It sets *is_unix and fills *ub for a unix:// listener. It gives the fd, or -1
    8847              : // with errno set; a name that doesn't resolve is logged with the resolver's
    8848              : // message and gives EADDRNOTAVAIL.
    8849          312 : static int make_listen_socket(const char *host, uint16_t port,
    8850              :                               bool enable_reuseport, bool ipv6_only,
    8851              :                               bool *is_unix, chttpsvr_unix_bind *ub,
    8852              :                               ccol_memmgmt_procs *mp) {
    8853          312 :   ub->path = NULL;
    8854          312 :   ub->base = NULL;
    8855          312 :   ub->dir_fd = -1;
    8856          312 :   *is_unix = host && strncmp(host, CHTTPSVR_UNIX_PREFIX,
    8857              :                              strlen(CHTTPSVR_UNIX_PREFIX)) == 0;
    8858          312 :   if (*is_unix)
    8859           20 :     return make_unix_listen_socket(host + strlen(CHTTPSVR_UNIX_PREFIX), ub, mp);
    8860              : 
    8861          292 :   int v6only_explicit = ipv6_only ? 1 : -1;
    8862          292 :   if (!host || !*host) {
    8863            6 :     struct sockaddr_in6 a6;
    8864            6 :     memset(&a6, 0, sizeof(a6));
    8865            6 :     a6.sin6_family = AF_INET6;
    8866            6 :     a6.sin6_port = htons(port);
    8867            6 :     a6.sin6_addr = in6addr_any;
    8868            6 :     int fd = bind_tcp(AF_INET6, (struct sockaddr *)&a6, sizeof(a6),
    8869              :                       enable_reuseport, ipv6_only ? 1 : 0);
    8870            6 :     if (fd >= 0 || ipv6_only) return fd;
    8871            1 :     int e = errno;
    8872            2 :     if (e != EAFNOSUPPORT && e != EADDRNOTAVAIL && e != EPROTONOSUPPORT &&
    8873            1 :         ipv6_dual_stack_supported()) {
    8874            1 :       errno = e;
    8875            1 :       return -1;
    8876              :     }
    8877            0 :     struct sockaddr_in a4;
    8878            0 :     memset(&a4, 0, sizeof(a4));
    8879            0 :     a4.sin_family = AF_INET;
    8880            0 :     a4.sin_port = htons(port);
    8881            0 :     a4.sin_addr.s_addr = htonl(INADDR_ANY);
    8882            0 :     return bind_tcp(AF_INET, (struct sockaddr *)&a4, sizeof(a4),
    8883              :                     enable_reuseport, -1);
    8884              :   }
    8885              : 
    8886          286 :   char unbracketed[256];
    8887          286 :   size_t host_len = strlen(host);
    8888          286 :   bool bracketed = host[0] == '[';
    8889          286 :   if (bracketed) {
    8890            4 :     if (host_len < 3 || host[host_len - 1] != ']' ||
    8891            3 :         host_len - 2 >= sizeof(unbracketed)) {
    8892            1 :       SRV_ENGINE_LOG(clog_error, "listen host \"%s\" is malformed", host);
    8893            1 :       errno = EINVAL;
    8894            1 :       return -1;
    8895              :     }
    8896            3 :     memcpy(unbracketed, host + 1, host_len - 2);
    8897            3 :     unbracketed[host_len - 2] = '\0';
    8898            3 :     host = unbracketed;
    8899              :   }
    8900              : 
    8901          285 :   struct addrinfo hints, *res = NULL;
    8902          285 :   memset(&hints, 0, sizeof(hints));
    8903          285 :   hints.ai_family = AF_UNSPEC;
    8904          285 :   hints.ai_socktype = SOCK_STREAM;
    8905          285 :   if (bracketed) hints.ai_flags = AI_NUMERICHOST;
    8906          285 :   char port_str[8];
    8907          285 :   snprintf(port_str, sizeof(port_str), "%u", port);
    8908          285 :   int gai = getaddrinfo(host, port_str, &hints, &res);
    8909          285 :   if (gai != 0 || !res) {
    8910            1 :     int e = errno;
    8911            1 :     if (gai == EAI_SYSTEM)
    8912            0 :       SRV_ENGINE_LOG(clog_error,
    8913              :                      "listen host \"%s\" does not resolve: errno=%d", host, e);
    8914              :     else
    8915            1 :       SRV_ENGINE_LOG(clog_error, "listen host \"%s\" does not resolve: %s",
    8916              :                      host, gai != 0 ? gai_strerror(gai) : "no address");
    8917            1 :     if (res) freeaddrinfo(res);
    8918            1 :     errno = EADDRNOTAVAIL;
    8919            1 :     return -1;
    8920              :   }
    8921          284 :   const int first_family = ipv6_only ? AF_INET6 : AF_INET;
    8922          281 :   const int second_family = ipv6_only ? AF_INET : AF_INET6;
    8923          284 :   struct addrinfo *pick = NULL;
    8924          570 :   for (struct addrinfo *rp = res; rp && !pick; rp = rp->ai_next)
    8925          286 :     if (rp->ai_family == first_family) pick = rp;
    8926          286 :   for (struct addrinfo *rp = res; rp && !pick; rp = rp->ai_next)
    8927            2 :     if (rp->ai_family == second_family) pick = rp;
    8928          284 :   int fd = -1;
    8929          284 :   if (pick) {
    8930          284 :     fd = bind_tcp(pick->ai_family, pick->ai_addr, pick->ai_addrlen,
    8931              :                   enable_reuseport, v6only_explicit);
    8932              :   } else {
    8933            0 :     errno = EAFNOSUPPORT;
    8934              :   }
    8935          284 :   int e = errno;
    8936          284 :   freeaddrinfo(res);
    8937          284 :   errno = e;
    8938          284 :   return fd;
    8939              : }
    8940              : 
    8941              : // Reads the port and numeric local address of the TCP listener fd for
    8942              : // chttpsvr_bound_port() and chttpsvr_bound_address(); with port 0 the system
    8943              : // chooses, so the socket is the only place to learn it from. It gives false
    8944              : // with errno set when getsockname fails or the address family isn't IPv4 or
    8945              : // IPv6.
    8946          286 : static bool listen_sockname(int fd, uint16_t *port_out, char *host,
    8947              :                             size_t host_len) {
    8948          286 :   struct sockaddr_storage ss;
    8949          286 :   socklen_t len = sizeof(ss);
    8950          286 :   memset(&ss, 0, sizeof(ss));
    8951          286 :   if (getsockname(fd, (struct sockaddr *)&ss, &len) != 0) return false;
    8952          286 :   const void *addr;
    8953          286 :   if (ss.ss_family == AF_INET) {
    8954          276 :     const struct sockaddr_in *a4 = (const struct sockaddr_in *)&ss;
    8955          276 :     *port_out = ntohs(a4->sin_port);
    8956          276 :     addr = &a4->sin_addr;
    8957           10 :   } else if (ss.ss_family == AF_INET6) {
    8958           10 :     const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)&ss;
    8959           10 :     *port_out = ntohs(a6->sin6_port);
    8960           10 :     addr = &a6->sin6_addr;
    8961              :   } else {
    8962            0 :     errno = EAFNOSUPPORT;
    8963            0 :     return false;
    8964              :   }
    8965          286 :   return inet_ntop(ss.ss_family, addr, host, (socklen_t)host_len) != NULL;
    8966              : }
    8967              : 
    8968              : // The registry of router shells. A shell is the chttpsvr_router struct itself,
    8969              : // while its contents (prefix, middleware list, routes) are separate
    8970              : // allocations. A caller's chttpsvr_router pointer has no generation of its own,
    8971              : // and the public router calls must read router->owner before any resolve can
    8972              : // pin the server, so the shell is never freed while the process may still read
    8973              : // it. destroy_router stores CHTTPSVR_NULL into owner and frees only the
    8974              : // contents, so a reader sees a live handle or the sentinel, never freed memory.
    8975              : // Shells come from the default allocator, since they outlive the server's
    8976              : // allocator, and the registry lets the exit-time destructor free them once.
    8977              : static struct {
    8978              :   ccol__mutex mutex;
    8979              :   ccol__once_flag once;
    8980              :   // A plain realloc'd array of every shell still allocated.
    8981              :   chttpsvr_router **shells;
    8982              :   size_t count;
    8983              :   size_t capacity;
    8984              :   // Set once the exit-time destructor has run. From then on a server's destroy
    8985              :   // frees all its shells, and the array goes with the last shell.
    8986              :   bool finalized;
    8987              : } chttpsvr_router_shell_registry = {0};
    8988              : 
    8989              : // Initializes the registry mutex, once; a failure is fatal.
    8990            6 : static void chttpsvr_router_shell_registry_init_globals(void) {
    8991            6 :   if (ccol__mutex_init(chttpsvr_router_shell_registry.mutex) != 0)
    8992            0 :     ccol__fatal_err(
    8993              :         "chttpsvr router shell registry: failed to initialize mutex");
    8994            6 : }
    8995              : 
    8996              : // Adds the new shell r to the registry under its mutex and records its index in
    8997              : // r->shell_idx. When the array can't grow, r gets SIZE_MAX and isn't tracked;
    8998              : // the only cost is a still-reachable shell at exit.
    8999          952 : static void chttpsvr_router_shell_register(chttpsvr_router *r) {
    9000          952 :   ccol__call_once(chttpsvr_router_shell_registry.once,
    9001              :                   chttpsvr_router_shell_registry_init_globals);
    9002          952 :   ccol__mutex_lock(chttpsvr_router_shell_registry.mutex);
    9003          952 :   if (chttpsvr_router_shell_registry.count ==
    9004          952 :       chttpsvr_router_shell_registry.capacity) {
    9005           12 :     size_t new_cap = doubling_growth_cap(
    9006              :         chttpsvr_router_shell_registry.capacity, sizeof(chttpsvr_router *), 8);
    9007              :     if (new_cap > 0) {
    9008           12 :       chttpsvr_router **nn =
    9009           12 :           (chttpsvr_router **)realloc(chttpsvr_router_shell_registry.shells,
    9010              :                                       new_cap * sizeof(chttpsvr_router *));
    9011           12 :       if (nn) {
    9012           12 :         chttpsvr_router_shell_registry.shells = nn;
    9013           12 :         chttpsvr_router_shell_registry.capacity = new_cap;
    9014              :       }
    9015              :     }
    9016              :   }
    9017          952 :   r->shell_idx = SIZE_MAX;
    9018          952 :   if (chttpsvr_router_shell_registry.count <
    9019          952 :       chttpsvr_router_shell_registry.capacity) {
    9020          952 :     r->shell_idx = chttpsvr_router_shell_registry.count;
    9021          952 :     chttpsvr_router_shell_registry
    9022          952 :         .shells[chttpsvr_router_shell_registry.count++] = r;
    9023              :   }
    9024          952 :   ccol__mutex_unlock(chttpsvr_router_shell_registry.mutex);
    9025          952 : }
    9026              : 
    9027              : // Takes r out of the registry by swapping the last shell into its place, and
    9028              : // frees the array once the destructor has run and the registry is empty. The
    9029              : // caller holds the registry mutex and frees r itself.
    9030          560 : static void chttpsvr_router_shell_unregister_locked(chttpsvr_router *r) {
    9031          560 :   size_t i = r->shell_idx;
    9032          560 :   if (i < chttpsvr_router_shell_registry.count &&
    9033          560 :       chttpsvr_router_shell_registry.shells[i] == r) {
    9034          560 :     chttpsvr_router *last = chttpsvr_router_shell_registry
    9035          560 :                                 .shells[--chttpsvr_router_shell_registry.count];
    9036          560 :     chttpsvr_router_shell_registry.shells[i] = last;
    9037          560 :     last->shell_idx = i;
    9038              :   }
    9039          560 :   r->shell_idx = SIZE_MAX;
    9040          560 :   if (chttpsvr_router_shell_registry.finalized &&
    9041            2 :       chttpsvr_router_shell_registry.count == 0) {
    9042            1 :     free(chttpsvr_router_shell_registry.shells);
    9043            1 :     chttpsvr_router_shell_registry.shells = NULL;
    9044            1 :     chttpsvr_router_shell_registry.capacity = 0;
    9045              :   }
    9046          560 : }
    9047              : 
    9048              : // Frees the shells of a destroyed server's routers that no caller can reach any
    9049              : // more: Always the root router, which is never handed out, and every router
    9050              : // once the exit-time destructor has run. A sub-router of a server destroyed
    9051              : // earlier keeps its shell, so a stale pointer to it stays safe to pass. Every
    9052              : // router has already gone through destroy_router. It takes the registry mutex.
    9053          559 : static void chttpsvr_router_shells_release(chttpsvr_router **routers,
    9054              :                                            size_t count,
    9055              :                                            chttpsvr_router *root) {
    9056          559 :   ccol__call_once(chttpsvr_router_shell_registry.once,
    9057              :                   chttpsvr_router_shell_registry_init_globals);
    9058          559 :   ccol__mutex_lock(chttpsvr_router_shell_registry.mutex);
    9059          559 :   bool all = chttpsvr_router_shell_registry.finalized;
    9060         1507 :   for (size_t i = 0; i < count; i++) {
    9061          948 :     chttpsvr_router *r = routers[i];
    9062          948 :     if (r != root && !all) continue;
    9063          560 :     chttpsvr_router_shell_unregister_locked(r);
    9064          560 :     ccol__default_mem_free(r);
    9065              :   }
    9066          559 :   ccol__mutex_unlock(chttpsvr_router_shell_registry.mutex);
    9067          559 : }
    9068              : 
    9069              : // Frees at exit every shell whose owner is CHTTPSVR_NULL (its router was
    9070              : // destroyed, or its registration failed half way), so valgrind reports no
    9071              : // still-reachable shells. A shell of a server the application never destroyed
    9072              : // stays, packed at the front of the array, because that server's threads keep
    9073              : // running past this destructor and find_route reads the shell; the server's own
    9074              : // destroy frees it later. It sets finalized and frees the array when nothing is
    9075              : // kept. The once guard comes first because a process may never have created a
    9076              : // server.
    9077            7 : __attribute__((destructor)) static void cleanup_chttpsvr_router_shells(void) {
    9078            7 :   ccol__call_once(chttpsvr_router_shell_registry.once,
    9079              :                   chttpsvr_router_shell_registry_init_globals);
    9080            7 :   ccol__mutex_lock(chttpsvr_router_shell_registry.mutex);
    9081            7 :   size_t kept = 0;
    9082          399 :   for (size_t i = 0; i < chttpsvr_router_shell_registry.count; i++) {
    9083          392 :     chttpsvr_router *r = chttpsvr_router_shell_registry.shells[i];
    9084          392 :     if (atomic_load(&r->owner) == CHTTPSVR_NULL) {
    9085          390 :       r->shell_idx = SIZE_MAX;
    9086          390 :       ccol__default_mem_free(r);
    9087              :     } else {
    9088            2 :       r->shell_idx = kept;
    9089            2 :       chttpsvr_router_shell_registry.shells[kept++] = r;
    9090              :     }
    9091              :   }
    9092            7 :   chttpsvr_router_shell_registry.count = kept;
    9093            7 :   chttpsvr_router_shell_registry.finalized = true;
    9094            7 :   if (kept == 0) {
    9095            6 :     free(chttpsvr_router_shell_registry.shells);
    9096            6 :     chttpsvr_router_shell_registry.shells = NULL;
    9097            6 :     chttpsvr_router_shell_registry.capacity = 0;
    9098              :   }
    9099            7 :   ccol__mutex_unlock(chttpsvr_router_shell_registry.mutex);
    9100            7 : }
    9101              : 
    9102              : #if CCOL_FORK_SAFETY_REQUIRED
    9103              : // The fork prepare handler. fork() copies only the calling thread, so a lock
    9104              : // another thread holds would stay locked in the child for good; this takes
    9105              : // every lock of the module first: The slot table, servers_bundler then
    9106              : // srv_engine_bundler (one fixed order, so a future change that nests them has
    9107              : // one order to follow), the router shell registry, the sweep's wake_mu leaf
    9108              : // lock, and for every in_use server its mutex, idle_mutex, diverted_mutex,
    9109              : // wait_mutex and routes_lock for write. Each registry's once guard runs first,
    9110              : // so a fork before the module was used doesn't lock uninitialized memory. The
    9111              : // pools, the reactor and the loggers are protected by their own modules'
    9112              : // handlers.
    9113           28 : static void chttpsvr_atfork_prepare(void) {
    9114              : #ifdef RUNNING_UNIT_TESTS
    9115           28 :   ccol__atfork_order_record(ccol__atfork_module_chttpserver);
    9116              : #endif
    9117           28 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
    9118           28 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
    9119              : 
    9120           28 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
    9121           28 :   ccol__mutex_lock(servers_bundler.mutex);
    9122           28 :   ccol__mutex_lock(srv_engine_bundler.mutex);
    9123              : 
    9124           28 :   ccol__call_once(chttpsvr_router_shell_registry.once,
    9125              :                   chttpsvr_router_shell_registry_init_globals);
    9126           28 :   ccol__mutex_lock(chttpsvr_router_shell_registry.mutex);
    9127           28 :   ccol__mutex_lock(idle_sweep_bundler.wake_mu);
    9128              : 
    9129           56 :   size_t n =
    9130           28 :       chttpsvr_slot_table.slots ? cvector_size(chttpsvr_slot_table.slots) : 0;
    9131          167 :   for (size_t i = 0; i < n; i++) {
    9132          139 :     chttpsvr_slot *slot =
    9133          139 :         (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, i);
    9134          139 :     if (!slot->in_use) continue;
    9135           41 :     ccol__mutex_lock(slot->ptr->mutex);
    9136           41 :     ccol__mutex_lock(slot->ptr->idle_mutex);
    9137           41 :     ccol__mutex_lock(slot->ptr->diverted_mutex);
    9138           41 :     ccol__mutex_lock(slot->ptr->wait_mutex);
    9139           41 :     ccol__rw_lock_wrlock(slot->ptr->routes_lock);
    9140              :   }
    9141           28 : }
    9142              : 
    9143              : // Releases every lock chttpsvr_atfork_prepare took; the parent and the child
    9144              : // handlers share it. Plain mutexes are unlocked in both, but in the child
    9145              : // routes_lock is initialized again, because a glibc rwlock's write lock tracks
    9146              : // its owner's TID and an unlock from the child's new thread releases nothing.
    9147              : // In the child it also clears state that names threads which don't exist there.
    9148              : // Every server's pending_resolve_count, servers_bundler_pins and
    9149              : // listener_dispatch_pins go to 0, since destroy waits on them without a limit
    9150              : // (in_flight_requests stays: Its wait is bounded, and a reset could free a
    9151              : // connection a worker really holds). A server caught in a teardown
    9152              : // (CHTTPSVR_QS_QUIESCING) is marked quiesced and unregistered with the locked
    9153              : // variant, as servers_bundler.mutex is held; retrying its half-done steps could
    9154              : // free things twice, so what it held leaks. A lifecycle of STARTING or STOPPING
    9155              : // goes back to IDLE, or the handle would be unusable; an orphaned listener fd
    9156              : // may make a later start fail with EADDRINUSE. The stop watcher's flags and
    9157              : // requests, reaper_joinable, the sweep's running flag and its condition
    9158              : // variable, and srv_engine_bundler.stopping are reset, so a later start, stop
    9159              : // or wait in the child neither joins a vanished thread nor waits for a
    9160              : // broadcast that never comes.
    9161           28 : static void chttpsvr_atfork_release_impl(bool is_child) {
    9162           56 :   size_t n =
    9163           28 :       chttpsvr_slot_table.slots ? cvector_size(chttpsvr_slot_table.slots) : 0;
    9164          167 :   for (size_t i = 0; i < n; i++) {
    9165          139 :     chttpsvr_slot *slot =
    9166          139 :         (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, i);
    9167          139 :     if (!slot->in_use) continue;
    9168           41 :     struct chttpserver *srv = slot->ptr;
    9169              : 
    9170           41 :     if (is_child) {
    9171            0 :       atomic_store(&srv->pending_resolve_count, (size_t)0);
    9172            0 :       atomic_store(&srv->servers_bundler_pins, (size_t)0);
    9173            0 :       atomic_store(&srv->listener_dispatch_pins, (size_t)0);
    9174            0 :       if (ccol__rw_lock_reinit_in_child(srv->routes_lock) != 0)
    9175            0 :         ccol__fatal_err(
    9176              :             "chttpsvr atfork release: failed to reinit routes_lock");
    9177              : 
    9178            0 :       switch (srv->quiesce_state) {
    9179            0 :         case CHTTPSVR_QS_QUIESCING: {
    9180            0 :           srv->quiesce_state = CHTTPSVR_QS_QUIESCED;
    9181            0 :           srv->quiesce_waiters = 0;
    9182            0 :           servers_unregister_locked(srv);
    9183            0 :           break;
    9184              :         }
    9185              :         case CHTTPSVR_QS_NOT_QUIESCED:
    9186              :         case CHTTPSVR_QS_QUIESCED:
    9187              :           break;
    9188              :       }
    9189            0 :       switch (srv->lifecycle) {
    9190            0 :         case CHTTPSVR_LC_STOPPING:
    9191              :         case CHTTPSVR_LC_STARTING:
    9192            0 :           srv->lifecycle = CHTTPSVR_LC_IDLE;
    9193            0 :           break;
    9194              :         case CHTTPSVR_LC_IDLE:
    9195              :         case CHTTPSVR_LC_RUNNING:
    9196              :           break;
    9197              :       }
    9198              :     } else {
    9199           41 :       ccol__rw_lock_unlock(srv->routes_lock);
    9200              :     }
    9201           41 :     ccol__mutex_unlock(srv->wait_mutex);
    9202           41 :     ccol__mutex_unlock(srv->diverted_mutex);
    9203           41 :     ccol__mutex_unlock(srv->idle_mutex);
    9204           41 :     ccol__mutex_unlock(srv->mutex);
    9205              :   }
    9206              : 
    9207           28 :   if (is_child) {
    9208            0 :     g_engine_stop_watcher.started = false;
    9209            0 :     atomic_store(&g_engine_stop_watcher.ready, false);
    9210            0 :     atomic_store(&g_engine_stop_watcher.join_reaper_requested, false);
    9211            0 :     atomic_store(&g_engine_stop_watcher.stop_requested, (uintptr_t)0);
    9212              : 
    9213            0 :     srv_engine_bundler.reaper_joinable = false;
    9214            0 :     idle_sweep_bundler.running = false;
    9215            0 :     if (idle_sweep_init_wake_cv() != 0)
    9216            0 :       ccol__fatal_err(
    9217              :           "chttpserver atfork child: failed to reinit the sweep condition "
    9218              :           "variable");
    9219              : 
    9220            0 :     srv_engine_bundler.stopping = false;
    9221              :   }
    9222              : 
    9223           28 :   ccol__mutex_unlock(idle_sweep_bundler.wake_mu);
    9224           28 :   ccol__mutex_unlock(chttpsvr_router_shell_registry.mutex);
    9225           28 :   ccol__mutex_unlock(servers_bundler.mutex);
    9226           28 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
    9227           28 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
    9228           28 : }
    9229              : 
    9230              : // The fork parent handler: Releases the locks the prepare handler took.
    9231           28 : static void chttpsvr_atfork_release(void) {
    9232           28 :   chttpsvr_atfork_release_impl(false);
    9233           28 : }
    9234              : 
    9235              : // The fork child handler: Releases the locks and resets the inherited state of
    9236              : // every server and thread. It runs as part of fork()'s return, before any
    9237              : // application code in the child can reach a server.
    9238            0 : static void chttpsvr_atfork_child_release(void) {
    9239            0 :   chttpsvr_atfork_release_impl(true);
    9240            0 : }
    9241              : #endif
    9242              : 
    9243              : // Counts the '/'-separated segments of a router prefix, which
    9244              : // find_route uses to order routers by how specific their mount is. The prefix
    9245              : // has no trailing or repeated slashes, so each '/' starts one segment; "" (the
    9246              : // root) and "/" have none.
    9247          952 : static int count_prefix_segments(const char *prefix) {
    9248          952 :   size_t len = strlen(prefix);
    9249          952 :   if (len <= 1) return 0;
    9250              :   int count = 0;
    9251         4440 :   for (size_t i = 0; i < len; i++)
    9252         4051 :     if (prefix[i] == '/') count++;
    9253              :   return count;
    9254              : }
    9255              : 
    9256              : // Creates a router for srv with prefix (NULL means the root's ""), trailing
    9257              : // slashes removed, and registers its shell. The shell comes from the default
    9258              : // allocator because it outlives the server and mp (see
    9259              : // chttpsvr_router_shell_registry); the prefix comes from mp. owner starts as
    9260              : // CHTTPSVR_NULL. It gives NULL when an allocation fails.
    9261          954 : static chttpsvr_router *create_router(struct chttpserver *srv,
    9262              :                                       const char *prefix,
    9263              :                                       ccol_memmgmt_procs *mp) {
    9264          954 :   chttpsvr_router *r =
    9265          954 :       (chttpsvr_router *)ccol__default_mem_calloc(1, sizeof(chttpsvr_router));
    9266          954 :   if (!r) return NULL;
    9267          954 :   r->prefix = ccol_strdup(mp, prefix ? prefix : "");
    9268          954 :   if (!r->prefix) {
    9269            2 :     ccol__default_mem_free(r);
    9270            2 :     return NULL;
    9271              :   }
    9272          952 :   size_t plen = strlen(r->prefix);
    9273          953 :   while (plen > 1 && r->prefix[plen - 1] == '/') r->prefix[--plen] = '\0';
    9274          952 :   r->prefix_len = plen;
    9275          952 :   r->prefix_seg_count = count_prefix_segments(r->prefix);
    9276          952 :   r->srv = srv;
    9277          952 :   r->m_procs = mp;
    9278          952 :   atomic_store(&r->owner, CHTTPSVR_NULL);
    9279          952 :   chttpsvr_router_shell_register(r);
    9280          952 :   return r;
    9281              : }
    9282              : 
    9283              : // Frees the contents of router r (middleware nodes, routes, prefix) with mp and
    9284              : // leaves the shell allocated. It stores CHTTPSVR_NULL into r->owner first, so a
    9285              : // reader that comes later sees the sentinel instead of racing the frees;
    9286              : // chttpsvr_finish_destroy calls it only after the pending_resolve_count wait,
    9287              : // so no reader is inside router_add_route or router_add_mw.
    9288          950 : static void destroy_router(chttpsvr_router *r, ccol_memmgmt_procs *mp) {
    9289          950 :   atomic_store(&r->owner, CHTTPSVR_NULL);
    9290          950 :   chttpsvr_mw_node *mw = r->mw_head;
    9291         1105 :   while (mw) {
    9292          155 :     chttpsvr_mw_node *next = mw->next;
    9293          155 :     ccol__mem_free(mp, mw);
    9294              :     mw = next;
    9295              :   }
    9296          950 :   r->mw_head = r->mw_tail = NULL;
    9297          950 :   r->mw_count = 0;
    9298         1849 :   for (size_t i = 0; i < r->route_count; i++) {
    9299          899 :     free_route_data(r->routes[i], mp);
    9300          899 :     ccol__mem_free(mp, r->routes[i]);
    9301              :   }
    9302          950 :   ccol__mem_free(mp, r->routes);
    9303          950 :   r->routes = NULL;
    9304          950 :   r->route_count = r->route_cap = 0;
    9305          950 :   ccol__mem_free(mp, r->prefix);
    9306          950 :   r->prefix = NULL;
    9307          950 :   r->srv = NULL;
    9308          950 : }
    9309              : 
    9310              : // Compiles pattern and appends a route for method to router, taking
    9311              : // srv->routes_lock for write around the append. A method above CHTTP_ANY is
    9312              : // refused, since find_route keeps methods as bits of a mask. It returns
    9313              : // ccol_success, ccol_invalid_args, the error of compile_pattern, or
    9314              : // ccol_not_enough_memory, and on failure frees the route it built.
    9315          954 : static ccol_retval router_add_route(chttpsvr_router *router,
    9316              :                                     chttp_method method, const char *pattern,
    9317              :                                     chttpsvr_handler_fn fn, void *ctx,
    9318              :                                     bool is_streaming) {
    9319          954 :   if (!router || !pattern || !fn) return ccol_invalid_args;
    9320          954 :   if ((unsigned int)method > (unsigned int)CHTTP_ANY) return ccol_invalid_args;
    9321              : 
    9322          930 :   ccol_memmgmt_procs *mp = router->m_procs;
    9323              : 
    9324          930 :   chttpsvr_route *rt =
    9325          930 :       (chttpsvr_route *)ccol__mem_alloc(mp, sizeof(chttpsvr_route));
    9326          930 :   if (!rt) return ccol_not_enough_memory;
    9327          928 :   memset(rt, 0, sizeof(*rt));
    9328          928 :   rt->method = method;
    9329          928 :   rt->fn = fn;
    9330          928 :   rt->ctx = ctx;
    9331          928 :   rt->is_streaming = is_streaming;
    9332              : 
    9333          928 :   ccol_retval rv = compile_pattern(pattern, &rt->segs, &rt->seg_count,
    9334              :                                    &rt->param_names, &rt->param_count, mp);
    9335          928 :   if (rv != ccol_success) {
    9336           27 :     ccol__mem_free(mp, rt);
    9337           27 :     return rv;
    9338              :   }
    9339              : 
    9340          901 :   ccol__rw_lock_wrlock(router->srv->routes_lock);
    9341          901 :   if (router->route_count >= router->route_cap) {
    9342          390 :     if (router->route_cap > (SIZE_MAX - 4) / 2 ||
    9343          390 :         router->route_cap * 2 + 4 > SIZE_MAX / sizeof(chttpsvr_route *)) {
    9344            0 :       ccol__rw_lock_unlock(router->srv->routes_lock);
    9345            0 :       free_route_data(rt, mp);
    9346            0 :       ccol__mem_free(mp, rt);
    9347            0 :       return ccol_not_enough_memory;
    9348              :     }
    9349          390 :     size_t new_cap = router->route_cap * 2 + 4;
    9350          390 :     chttpsvr_route **nr = (chttpsvr_route **)ccol__mem_realloc(
    9351              :         mp, router->routes, new_cap * sizeof(chttpsvr_route *));
    9352          390 :     if (!nr) {
    9353            2 :       ccol__rw_lock_unlock(router->srv->routes_lock);
    9354            2 :       free_route_data(rt, mp);
    9355            2 :       ccol__mem_free(mp, rt);
    9356            2 :       return ccol_not_enough_memory;
    9357              :     }
    9358          388 :     router->routes = nr;
    9359          388 :     router->route_cap = new_cap;
    9360              :   }
    9361          899 :   router->routes[router->route_count++] = rt;
    9362          899 :   if (rt->seg_count > router->max_route_seg_count)
    9363          350 :     router->max_route_seg_count = rt->seg_count;
    9364          899 :   ccol__rw_lock_unlock(router->srv->routes_lock);
    9365          899 :   return ccol_success;
    9366              : }
    9367              : 
    9368              : // Appends middleware fn with its ctx to the end of router's chain; chttpsvr_use
    9369              : // and chttpsvr_router_use call it. It gives ccol_invalid_args for a NULL router
    9370              : // or fn, ccol_not_enough_memory when the node can't be allocated, and
    9371              : // ccol_not_permitted once the router holds CHTTPSVR_MAX_MW entries. The node is
    9372              : // allocated before the write lock of srv->routes_lock is taken, and the chain
    9373              : // and mw_count change only under that lock, so a request that walks the chain
    9374              : // under the read lock never sees a half-linked node.
    9375        52351 : static ccol_retval router_add_mw(chttpsvr_router *router,
    9376              :                                  chttpsvr_middleware_fn fn, void *ctx) {
    9377        52351 :   if (!router || !fn) return ccol_invalid_args;
    9378        52351 :   ccol_memmgmt_procs *mp = router->m_procs;
    9379        52351 :   chttpsvr_mw_node *node =
    9380        52351 :       (chttpsvr_mw_node *)ccol__mem_alloc(mp, sizeof(chttpsvr_mw_node));
    9381        52351 :   if (!node) return ccol_not_enough_memory;
    9382        52351 :   node->fn = fn;
    9383        52351 :   node->ctx = ctx;
    9384        52351 :   node->next = NULL;
    9385              : 
    9386        52351 :   ccol__rw_lock_wrlock(router->srv->routes_lock);
    9387        52351 :   if (router->mw_count >= CHTTPSVR_MAX_MW) {
    9388        52195 :     ccol__rw_lock_unlock(router->srv->routes_lock);
    9389        52195 :     ccol__mem_free(mp, node);
    9390        52195 :     return ccol_not_permitted;
    9391              :   }
    9392          156 :   if (!router->mw_tail) {
    9393           61 :     router->mw_head = router->mw_tail = node;
    9394              :   } else {
    9395           95 :     router->mw_tail->next = node;
    9396           95 :     router->mw_tail = node;
    9397              :   }
    9398          156 :   router->mw_count++;
    9399          156 :   ccol__rw_lock_unlock(router->srv->routes_lock);
    9400          156 :   return ccol_success;
    9401              : }
    9402              : 
    9403              : // Query parameters
    9404              : 
    9405              : // Splits a raw query string at '&' into key and value pairs, URL-decodes both
    9406              : // and stores them, in order, in a new chttpsvr_qparams allocated from mp, which
    9407              : // goes to *qp_out. A pair without '=' gets an empty value and "=v" an empty
    9408              : // key; an empty pair (as in "a=1&&b=2") is skipped, and so is a pair whose key
    9409              : // or value doesn't decode. Short keys and values are copied through a stack
    9410              : // buffer before decoding. It gives ccol_success, or ccol_not_enough_memory
    9411              : // after freeing everything it built.
    9412           98 : static ccol_retval parse_qparams(const char *raw_query,
    9413              :                                  chttpsvr_qparams **qp_out,
    9414              :                                  ccol_memmgmt_procs *mp) {
    9415           98 :   chttpsvr_qparams *qp =
    9416           98 :       (chttpsvr_qparams *)ccol__mem_calloc(mp, 1, sizeof(chttpsvr_qparams));
    9417           98 :   if (!qp) return ccol_not_enough_memory;
    9418           97 :   qp->m_procs = mp;
    9419              : 
    9420           97 :   const char *p = raw_query;
    9421          275 :   while (p && *p) {
    9422          274 :     const char *amp = strchr(p, '&');
    9423          274 :     size_t pair_len = amp ? (size_t)(amp - p) : strlen(p);
    9424          274 :     if (pair_len == 0) {
    9425            2 :       p = amp ? amp + 1 : NULL;
    9426            2 :       continue;
    9427              :     }
    9428          272 :     const char *eq = (const char *)memchr(p, '=', pair_len);
    9429              : 
    9430          272 :     size_t key_raw_len = eq ? (size_t)(eq - p) : pair_len;
    9431          254 :     const char *val_raw = eq ? eq + 1 : NULL;
    9432          272 :     size_t val_raw_len = eq ? pair_len - key_raw_len - 1 : 0;
    9433              : 
    9434          272 :     char key_src[512];
    9435          272 :     char *key_sp = key_src;
    9436          272 :     bool kh = false;
    9437          272 :     if (key_raw_len + 1 > sizeof(key_src)) {
    9438            1 :       key_sp = (char *)ccol__mem_alloc(mp, key_raw_len + 1);
    9439            1 :       kh = true;
    9440            1 :       if (!key_sp) goto oom;
    9441              :     }
    9442          271 :     memcpy(key_sp, p, key_raw_len);
    9443          271 :     key_sp[key_raw_len] = '\0';
    9444          271 :     char *key_decoded = (char *)ccol__mem_alloc(mp, key_raw_len + 1);
    9445          271 :     if (!key_decoded) {
    9446            5 :       if (kh) ccol__mem_free(mp, key_sp);
    9447            5 :       goto oom;
    9448              :     }
    9449          266 :     ssize_t kl = decode_url_unsafe(key_decoded, key_sp);
    9450          266 :     if (kh) ccol__mem_free(mp, key_sp);
    9451          266 :     if (kl < 0) {
    9452            1 :       ccol__mem_free(mp, key_decoded);
    9453            1 :       goto next;
    9454              :     }
    9455          265 :     key_decoded[(size_t)kl] = '\0';
    9456              : 
    9457          265 :     char *val_decoded = NULL;
    9458          265 :     if (val_raw) {
    9459          248 :       char val_src[512];
    9460          248 :       char *val_sp = val_src;
    9461          248 :       bool vh = false;
    9462          248 :       if (val_raw_len + 1 > sizeof(val_src)) {
    9463           15 :         val_sp = (char *)ccol__mem_alloc(mp, val_raw_len + 1);
    9464           15 :         vh = true;
    9465           15 :         if (!val_sp) {
    9466            1 :           ccol__mem_free(mp, key_decoded);
    9467            5 :           goto oom;
    9468              :         }
    9469              :       }
    9470          247 :       memcpy(val_sp, val_raw, val_raw_len);
    9471          247 :       val_sp[val_raw_len] = '\0';
    9472          247 :       val_decoded = (char *)ccol__mem_alloc(mp, val_raw_len + 1);
    9473          247 :       if (!val_decoded) {
    9474            4 :         if (vh) ccol__mem_free(mp, val_sp);
    9475            4 :         ccol__mem_free(mp, key_decoded);
    9476            4 :         goto oom;
    9477              :       }
    9478          243 :       ssize_t vl = decode_url_unsafe(val_decoded, val_sp);
    9479          243 :       if (vh) ccol__mem_free(mp, val_sp);
    9480          243 :       if (vl < 0) {
    9481            0 :         ccol__mem_free(mp, val_decoded);
    9482            0 :         ccol__mem_free(mp, key_decoded);
    9483            0 :         goto next;
    9484              :       }
    9485          243 :       val_decoded[(size_t)vl] = '\0';
    9486              :     } else {
    9487           17 :       val_decoded = ccol_strdup(mp, "");
    9488           16 :       if (!val_decoded) {
    9489            1 :         ccol__mem_free(mp, key_decoded);
    9490            1 :         goto oom;
    9491              :       }
    9492              :     }
    9493              : 
    9494          259 :     if (qp->count >= qp->cap) {
    9495           96 :       if (qp->cap > (SIZE_MAX - 8) / 2 ||
    9496           96 :           qp->cap * 2 + 8 > SIZE_MAX / sizeof(char *)) {
    9497            0 :         ccol__mem_free(mp, key_decoded);
    9498            0 :         ccol__mem_free(mp, val_decoded);
    9499            0 :         goto oom;
    9500              :       }
    9501           96 :       size_t nc = qp->cap * 2 + 8;
    9502           96 :       char **nk = (char **)ccol__mem_realloc(mp, qp->keys, nc * sizeof(char *));
    9503           96 :       if (!nk) {
    9504            1 :         ccol__mem_free(mp, key_decoded);
    9505            1 :         ccol__mem_free(mp, val_decoded);
    9506            1 :         goto oom;
    9507              :       }
    9508           95 :       qp->keys = nk;
    9509           95 :       char **nv =
    9510           95 :           (char **)ccol__mem_realloc(mp, qp->values, nc * sizeof(char *));
    9511           95 :       if (!nv) {
    9512            1 :         ccol__mem_free(mp, key_decoded);
    9513            1 :         ccol__mem_free(mp, val_decoded);
    9514            1 :         goto oom;
    9515              :       }
    9516           94 :       qp->values = nv;
    9517           94 :       qp->cap = nc;
    9518              :     }
    9519          257 :     qp->keys[qp->count] = key_decoded;
    9520          257 :     qp->values[qp->count] = val_decoded;
    9521          257 :     qp->count++;
    9522              : 
    9523          258 :   next:
    9524          258 :     p = amp ? amp + 1 : NULL;
    9525              :   }
    9526              : 
    9527           83 :   *qp_out = qp;
    9528           83 :   return ccol_success;
    9529              : 
    9530           14 : oom:
    9531           38 :   for (size_t i = 0; i < qp->count; i++) {
    9532           24 :     ccol__mem_free(mp, qp->keys[i]);
    9533           24 :     ccol__mem_free(mp, qp->values[i]);
    9534              :   }
    9535           14 :   ccol__mem_free(mp, qp->keys);
    9536           14 :   ccol__mem_free(mp, qp->values);
    9537           14 :   ccol__mem_free(mp, qp);
    9538              :   return ccol_not_enough_memory;
    9539              : }
    9540              : 
    9541              : // Gives the parsed query parameters of req, parsing conn->raw_query on the
    9542              : // first call only and caching the result in req->qparams. A request with no
    9543              : // query gets an empty set. When parsing fails for lack of memory it sets
    9544              : // req->qparams_parse_oom, which chttpsvr_req_query_oom reads to tell a failed
    9545              : // allocation from an absent key, and gives an empty set or NULL.
    9546              : // req->qparams_attempted stops a second attempt after a failure.
    9547          191 : static chttpsvr_qparams *ensure_qparams(chttpsvr_req *req) {
    9548          191 :   chttpsvr_conn *conn = req->conn;
    9549          191 :   if (req->qparams) return req->qparams;
    9550          100 :   if (req->qparams_attempted) return NULL;
    9551          100 :   req->qparams_attempted = true;
    9552              : 
    9553          100 :   if (!conn->raw_query || !*conn->raw_query) {
    9554            2 :     chttpsvr_qparams *qp = (chttpsvr_qparams *)ccol__mem_calloc(
    9555              :         req->m_procs, 1, sizeof(chttpsvr_qparams));
    9556            2 :     if (!qp) {
    9557            0 :       req->qparams_parse_oom = true;
    9558            0 :       return NULL;
    9559              :     }
    9560            2 :     qp->m_procs = req->m_procs;
    9561            2 :     req->qparams = qp;
    9562            2 :     return qp;
    9563              :   }
    9564           98 :   if (parse_qparams(conn->raw_query, &req->qparams, req->m_procs) !=
    9565              :       ccol_success) {
    9566           15 :     req->qparams_parse_oom = true;
    9567           15 :     chttpsvr_qparams *qp = (chttpsvr_qparams *)ccol__mem_calloc(
    9568              :         req->m_procs, 1, sizeof(chttpsvr_qparams));
    9569           15 :     if (qp) {
    9570           15 :       qp->m_procs = req->m_procs;
    9571           15 :       req->qparams = qp;
    9572           15 :       return qp;
    9573              :     }
    9574              :     return NULL;
    9575              :   }
    9576           83 :   return req->qparams;
    9577              : }
    9578              : 
    9579              : // Public API
    9580              : 
    9581              : // Creates a stopped server: Its copy of mprocs, a logger derived from cl (or a
    9582              : // fatal-only logger on stderr when cl is CLOG_NULL), its mutexes, condition
    9583              : // variables and routes lock, the root router, and a slot in the handle table.
    9584              : // It gives the new handle, or CHTTPSVR_NULL with *err_str set; every failure
    9585              : // undoes what was already built. A create after the exit-time destructor
    9586              : // released the slot table is refused before anything is allocated. A closed or
    9587              : // stale parent logger is reported through err_str, because clog_derive would
    9588              : // end the process. requests_done_cv uses CLOCK_MONOTONIC to match the deadline
    9589              : // wait_in_flight_bounded builds. root->owner is set to the handle so the
    9590              : // exit-time destructor can tell a live root router from a destroyed one.
    9591          567 : chttpsvr chttpsvr_create_mp(ccol_memmgmt_procs *mprocs, clog cl,
    9592              :                             char **err_str) {
    9593          567 :   if (!ccol__verify_memmgmt_procs(mprocs, err_str)) return CHTTPSVR_NULL;
    9594              : 
    9595          567 :   if (chttpsvr_slot_table_released()) {
    9596            1 :     if (err_str)
    9597            1 :       *err_str = CCOL__ERR_STR(
    9598              :           "the library already released its server table at unload");
    9599            1 :     return CHTTPSVR_NULL;
    9600              :   }
    9601              : 
    9602          566 :   struct chttpserver *srv = (struct chttpserver *)ccol__mem_calloc(
    9603              :       mprocs, 1, sizeof(struct chttpserver));
    9604          566 :   if (!srv) {
    9605            1 :     if (err_str) *err_str = CCOL__ERR_STR("out of memory");
    9606            1 :     return CHTTPSVR_NULL;
    9607              :   }
    9608          565 :   atomic_init(&srv->lifetime_refs, 1);
    9609              : 
    9610          565 :   if (mprocs) {
    9611           48 :     srv->m_procs = (ccol_memmgmt_procs *)ccol__mem_alloc(
    9612              :         mprocs, sizeof(ccol_memmgmt_procs));
    9613           48 :     if (!srv->m_procs) {
    9614            1 :       ccol__mem_free(mprocs, srv);
    9615            1 :       if (err_str) *err_str = CCOL__ERR_STR("out of memory");
    9616            1 :       return CHTTPSVR_NULL;
    9617              :     }
    9618           47 :     memcpy(srv->m_procs, mprocs, sizeof(ccol_memmgmt_procs));
    9619              :   }
    9620              : 
    9621          564 :   ccol_retval derive_rv = ccol_success;
    9622          264 :   clog logger = cl ? clog__derive_checked(cl, &derive_rv)
    9623          564 :                    : clog_create_from_fd_mp(2, CLOG_FATAL, NULL, mprocs);
    9624          564 :   if (logger && cl) clog_set_field(logger, "component", "http-server");
    9625          564 :   if (!logger) {
    9626            1 :     ccol__mem_free(mprocs, srv->m_procs);
    9627            1 :     ccol__mem_free(mprocs, srv);
    9628            1 :     if (err_str)
    9629            1 :       *err_str = derive_rv == ccol_invalid_args
    9630              :                      ? CCOL__ERR_STR("the parent logger is not open")
    9631            1 :                      : CCOL__ERR_STR("failed to create server logger");
    9632            1 :     return CHTTPSVR_NULL;
    9633              :   }
    9634              : 
    9635          563 :   if (ccol__mutex_init(srv->mutex) != 0) {
    9636            0 :     clog_close(logger);
    9637            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9638            0 :     ccol__mem_free(mprocs, srv);
    9639            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__mutex_init failed");
    9640            0 :     return CHTTPSVR_NULL;
    9641              :   }
    9642          563 :   if (ccol__mutex_init(srv->idle_mutex) != 0) {
    9643            0 :     ccol__mutex_destroy(srv->mutex);
    9644            0 :     clog_close(logger);
    9645            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9646            0 :     ccol__mem_free(mprocs, srv);
    9647            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__mutex_init failed");
    9648            0 :     return CHTTPSVR_NULL;
    9649              :   }
    9650          563 :   if (ccol__mutex_init(srv->diverted_mutex) != 0) {
    9651            0 :     ccol__mutex_destroy(srv->idle_mutex);
    9652            0 :     ccol__mutex_destroy(srv->mutex);
    9653            0 :     clog_close(logger);
    9654            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9655            0 :     ccol__mem_free(mprocs, srv);
    9656            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__mutex_init failed");
    9657            0 :     return CHTTPSVR_NULL;
    9658              :   }
    9659          563 :   if (ccol__mutex_init(srv->wait_mutex) != 0) {
    9660            0 :     ccol__mutex_destroy(srv->diverted_mutex);
    9661            0 :     ccol__mutex_destroy(srv->idle_mutex);
    9662            0 :     ccol__mutex_destroy(srv->mutex);
    9663            0 :     clog_close(logger);
    9664            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9665            0 :     ccol__mem_free(mprocs, srv);
    9666            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__mutex_init failed");
    9667            0 :     return CHTTPSVR_NULL;
    9668              :   }
    9669          563 :   if (ccol__cond_var_init(srv->resolve_cv) != 0) {
    9670            0 :     ccol__mutex_destroy(srv->idle_mutex);
    9671            0 :     ccol__mutex_destroy(srv->diverted_mutex);
    9672            0 :     ccol__mutex_destroy(srv->wait_mutex);
    9673            0 :     ccol__mutex_destroy(srv->mutex);
    9674            0 :     clog_close(logger);
    9675            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9676            0 :     ccol__mem_free(mprocs, srv);
    9677            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__cond_var_init failed");
    9678            0 :     return CHTTPSVR_NULL;
    9679              :   }
    9680              : 
    9681              :   {
    9682          563 :     ccol__cond_var_attr cv_attr;
    9683          563 :     int cv_rc = 0;
    9684          563 :     if (ccol__cond_var_attr_init(cv_attr) == 0) {
    9685          563 :       ccol__cond_var_attr_setclock(cv_attr, CLOCK_MONOTONIC);
    9686          563 :       cv_rc = ccol__cond_var_init_ca(srv->requests_done_cv, cv_attr);
    9687          563 :       ccol__cond_var_attr_destroy(cv_attr);
    9688              :     } else {
    9689              :       cv_rc = 1;
    9690              :     }
    9691          563 :     if (cv_rc != 0) {
    9692            0 :       ccol__cond_var_destroy(srv->resolve_cv);
    9693            0 :       ccol__mutex_destroy(srv->idle_mutex);
    9694            0 :       ccol__mutex_destroy(srv->diverted_mutex);
    9695            0 :       ccol__mutex_destroy(srv->wait_mutex);
    9696            0 :       ccol__mutex_destroy(srv->mutex);
    9697            0 :       clog_close(logger);
    9698            0 :       ccol__mem_free(mprocs, srv->m_procs);
    9699            0 :       ccol__mem_free(mprocs, srv);
    9700            0 :       if (err_str) *err_str = CCOL__ERR_STR("ccol__cond_var_init failed");
    9701            0 :       return CHTTPSVR_NULL;
    9702              :     }
    9703              :   }
    9704              : 
    9705          563 :   if (ccol__cond_var_init(srv->quiesce_done_cv) != 0) {
    9706            0 :     ccol__cond_var_destroy(srv->requests_done_cv);
    9707            0 :     ccol__cond_var_destroy(srv->resolve_cv);
    9708            0 :     ccol__mutex_destroy(srv->idle_mutex);
    9709            0 :     ccol__mutex_destroy(srv->diverted_mutex);
    9710            0 :     ccol__mutex_destroy(srv->wait_mutex);
    9711            0 :     ccol__mutex_destroy(srv->mutex);
    9712            0 :     clog_close(logger);
    9713            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9714            0 :     ccol__mem_free(mprocs, srv);
    9715            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__cond_var_init failed");
    9716            0 :     return CHTTPSVR_NULL;
    9717              :   }
    9718              : 
    9719          563 :   if (ccol__rw_lock_init(srv->routes_lock) != 0) {
    9720            0 :     ccol__cond_var_destroy(srv->quiesce_done_cv);
    9721            0 :     ccol__cond_var_destroy(srv->requests_done_cv);
    9722            0 :     ccol__cond_var_destroy(srv->resolve_cv);
    9723            0 :     ccol__mutex_destroy(srv->idle_mutex);
    9724            0 :     ccol__mutex_destroy(srv->diverted_mutex);
    9725            0 :     ccol__mutex_destroy(srv->wait_mutex);
    9726            0 :     ccol__mutex_destroy(srv->mutex);
    9727            0 :     clog_close(logger);
    9728            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9729            0 :     ccol__mem_free(mprocs, srv);
    9730            0 :     if (err_str) *err_str = CCOL__ERR_STR("ccol__rw_lock_init failed");
    9731            0 :     return CHTTPSVR_NULL;
    9732              :   }
    9733              : 
    9734          563 :   chttpsvr_router *root = create_router(srv, "", srv->m_procs);
    9735          563 :   if (!root) {
    9736            1 :     ccol__rw_lock_destroy(srv->routes_lock);
    9737            1 :     ccol__cond_var_destroy(srv->quiesce_done_cv);
    9738            1 :     ccol__cond_var_destroy(srv->requests_done_cv);
    9739            1 :     ccol__cond_var_destroy(srv->resolve_cv);
    9740            1 :     ccol__mutex_destroy(srv->idle_mutex);
    9741            1 :     ccol__mutex_destroy(srv->diverted_mutex);
    9742            1 :     ccol__mutex_destroy(srv->wait_mutex);
    9743            1 :     ccol__mutex_destroy(srv->mutex);
    9744            1 :     clog_close(logger);
    9745            1 :     ccol__mem_free(mprocs, srv->m_procs);
    9746            1 :     ccol__mem_free(mprocs, srv);
    9747            1 :     if (err_str) *err_str = CCOL__ERR_STR("out of memory");
    9748            1 :     return CHTTPSVR_NULL;
    9749              :   }
    9750              : 
    9751          562 :   srv->routers = (chttpsvr_router **)ccol__mem_alloc(srv->m_procs,
    9752              :                                                      sizeof(chttpsvr_router *));
    9753          562 :   if (!srv->routers) {
    9754            1 :     destroy_router(root, srv->m_procs);
    9755            1 :     ccol__rw_lock_destroy(srv->routes_lock);
    9756            1 :     ccol__cond_var_destroy(srv->quiesce_done_cv);
    9757            1 :     ccol__cond_var_destroy(srv->requests_done_cv);
    9758            1 :     ccol__cond_var_destroy(srv->resolve_cv);
    9759            1 :     ccol__mutex_destroy(srv->idle_mutex);
    9760            1 :     ccol__mutex_destroy(srv->diverted_mutex);
    9761            1 :     ccol__mutex_destroy(srv->wait_mutex);
    9762            1 :     ccol__mutex_destroy(srv->mutex);
    9763            1 :     clog_close(logger);
    9764            1 :     ccol__mem_free(mprocs, srv->m_procs);
    9765            1 :     ccol__mem_free(mprocs, srv);
    9766            1 :     if (err_str) *err_str = CCOL__ERR_STR("out of memory");
    9767            1 :     return CHTTPSVR_NULL;
    9768              :   }
    9769          561 :   srv->routers[0] = root;
    9770          561 :   srv->root_router = root;
    9771          561 :   srv->router_count = 1;
    9772          561 :   srv->router_cap = 1;
    9773          561 :   srv->cl = logger;
    9774          561 :   atomic_store(&srv->listen_fd, -1);
    9775          561 :   srv->lifecycle = CHTTPSVR_LC_IDLE;
    9776              : 
    9777          561 :   chttpsvr h = chttpsvr_handle_slot_acquire(srv);
    9778          561 :   if (h == 0) {
    9779            0 :     if (err_str) *err_str = CCOL__ERR_STR("failed to allocate server slot");
    9780            0 :     ccol__mem_free(srv->m_procs, srv->routers);
    9781            0 :     destroy_router(root, srv->m_procs);
    9782            0 :     ccol__rw_lock_destroy(srv->routes_lock);
    9783            0 :     ccol__cond_var_destroy(srv->quiesce_done_cv);
    9784            0 :     ccol__cond_var_destroy(srv->requests_done_cv);
    9785            0 :     ccol__cond_var_destroy(srv->resolve_cv);
    9786            0 :     ccol__mutex_destroy(srv->idle_mutex);
    9787            0 :     ccol__mutex_destroy(srv->diverted_mutex);
    9788            0 :     ccol__mutex_destroy(srv->wait_mutex);
    9789            0 :     ccol__mutex_destroy(srv->mutex);
    9790            0 :     clog_close(logger);
    9791            0 :     ccol__mem_free(mprocs, srv->m_procs);
    9792            0 :     ccol__mem_free(mprocs, srv);
    9793            0 :     return CHTTPSVR_NULL;
    9794              :   }
    9795              : 
    9796          561 :   atomic_store(&root->owner, h);
    9797          561 :   return h;
    9798              : }
    9799              : 
    9800              : // The three thread pools of a server (worker, reject and the lazily created
    9801              : // streaming pool), taken out of the server together. Every detach point needs
    9802              : // all three, and one return value keeps a call site from detaching one and
    9803              : // forgetting another.
    9804              : typedef struct {
    9805              :   cthrpool worker;
    9806              :   cthrpool reject;
    9807              :   cthrpool stream;
    9808              : } detached_pools;
    9809              : 
    9810              : // How long wait_in_flight_bounded waits for in-flight requests:
    9811              : // CHTTPSVR_GRACEFUL_WAIT_MS before it forces a shutdown(2) on every diverted
    9812              : // connection, then CHTTPSVR_FORCE_UNBLOCK_GRACE_MS for those workers to unwind
    9813              : // through their error paths.
    9814              : #define CHTTPSVR_FORCE_UNBLOCK_GRACE_MS 5000
    9815              : #define CHTTPSVR_GRACEFUL_WAIT_MS 30000
    9816              : 
    9817              : // Bound on drain_and_close_all_connections's wait for every connection of a
    9818              : // server to be freed.
    9819              : #define CHTTPSVR_DRAIN_CONNECTIONS_WAIT_MS 30000
    9820              : 
    9821              : #ifdef RUNNING_UNIT_TESTS
    9822              : // Test overrides of the three bounds above, set by the two setters below. 0
    9823              : // means the real value. They are process-wide and let a test run the escalation
    9824              : // in well under a second.
    9825              : static _Atomic unsigned g_wait_in_flight_graceful_ms_for_tests = 0;
    9826              : static _Atomic unsigned g_wait_in_flight_grace_ms_for_tests = 0;
    9827           16 : void chttpsvr__set_wait_in_flight_bounds_for_tests(unsigned graceful_ms,
    9828              :                                                    unsigned grace_ms) {
    9829           16 :   atomic_store(&g_wait_in_flight_graceful_ms_for_tests, graceful_ms);
    9830           16 :   atomic_store(&g_wait_in_flight_grace_ms_for_tests, grace_ms);
    9831           16 : }
    9832              : 
    9833              : static _Atomic unsigned g_drain_connections_wait_ms_for_tests = 0;
    9834            2 : void chttpsvr__set_drain_connections_wait_ms_for_tests(unsigned ms) {
    9835            2 :   atomic_store(&g_drain_connections_wait_ms_for_tests, ms);
    9836            2 : }
    9837              : #endif
    9838              : 
    9839              : // Adds ms milliseconds to *ts and normalizes tv_nsec; the bounded waits below
    9840              : // use it to build their deadlines.
    9841         5291 : static void timespec_add_ms(struct timespec *ts, unsigned ms) {
    9842         5291 :   ts->tv_sec += (time_t)(ms / 1000);
    9843         5291 :   ts->tv_nsec += (long)(ms % 1000) * 1000000L;
    9844         4694 :   if (ts->tv_nsec >= 1000000000L) {
    9845            2 :     ts->tv_nsec -= 1000000000L;
    9846            2 :     ts->tv_sec += 1;
    9847              :   }
    9848              : }
    9849              : 
    9850              : // Waits for srv->in_flight_requests to reach 0 on requests_done_cv. After the
    9851              : // graceful bound it calls force_unblock_diverted_connections, so a worker
    9852              : // blocked for ever in a socket read or write (a timeout of 0 and a peer that
    9853              : // stalls) gets an I/O error, and then waits one more grace period. Without
    9854              : // that, the cthrpool_shutdown_drain that every caller runs next, which has no
    9855              : // timeout, could hang on such a task. The caller holds srv->mutex; it is
    9856              : // released around the shutdown pass, so no I/O happens under the lock. A
    9857              : // request that remains after both waits is blocked in something this library
    9858              : // can't reach, and the pool drain waits for it.
    9859          563 : static void wait_in_flight_bounded(struct chttpserver *srv) {
    9860          572 :   if (srv->in_flight_requests <= 0) return;
    9861              : 
    9862           13 :   unsigned graceful_ms = CHTTPSVR_GRACEFUL_WAIT_MS;
    9863           13 :   unsigned grace_ms = CHTTPSVR_FORCE_UNBLOCK_GRACE_MS;
    9864              : #ifdef RUNNING_UNIT_TESTS
    9865           13 :   unsigned override_graceful_ms =
    9866           13 :       atomic_load(&g_wait_in_flight_graceful_ms_for_tests);
    9867           13 :   unsigned override_grace_ms =
    9868           13 :       atomic_load(&g_wait_in_flight_grace_ms_for_tests);
    9869           13 :   if (override_graceful_ms) graceful_ms = override_graceful_ms;
    9870           13 :   if (override_grace_ms) grace_ms = override_grace_ms;
    9871              : #endif
    9872              : 
    9873           13 :   struct timespec deadline;
    9874           13 :   clock_gettime(CLOCK_MONOTONIC, &deadline);
    9875           13 :   timespec_add_ms(&deadline, graceful_ms);
    9876           22 :   bool timed_out = false;
    9877           22 :   while (srv->in_flight_requests > 0) {
    9878           13 :     if (ccol__cond_var_timedwait(srv->requests_done_cv, srv->mutex, deadline) ==
    9879              :         ETIMEDOUT) {
    9880              :       timed_out = true;
    9881              :       break;
    9882              :     }
    9883              :   }
    9884           13 :   if (!timed_out || srv->in_flight_requests <= 0) return;
    9885              : 
    9886            4 :   ccol__mutex_unlock(srv->mutex);
    9887            4 :   force_unblock_diverted_connections(srv);
    9888            4 :   ccol__mutex_lock(srv->mutex);
    9889            4 :   if (srv->in_flight_requests <= 0) return;
    9890              : 
    9891            4 :   struct timespec grace_deadline;
    9892            4 :   clock_gettime(CLOCK_MONOTONIC, &grace_deadline);
    9893            4 :   timespec_add_ms(&grace_deadline, grace_ms);
    9894            8 :   while (srv->in_flight_requests > 0) {
    9895            4 :     if (ccol__cond_var_timedwait(srv->requests_done_cv, srv->mutex,
    9896              :                                  grace_deadline) == ETIMEDOUT)
    9897              :       break;
    9898              :   }
    9899              : }
    9900              : 
    9901              : // Drains and destroys each pool of pools that exists, streaming pool first.
    9902              : // Each drain waits for every queued and running task of that pool.
    9903          603 : static void destroy_detached_pools(detached_pools pools) {
    9904          603 :   if (pools.stream) {
    9905           33 :     cthrpool_shutdown_drain(pools.stream);
    9906           33 :     cthrpool_destroy(pools.stream);
    9907              :   }
    9908          603 :   if (pools.worker) {
    9909          323 :     cthrpool_shutdown_drain(pools.worker);
    9910          323 :     cthrpool_destroy(pools.worker);
    9911              :   }
    9912          603 :   if (pools.reject) {
    9913          323 :     cthrpool_shutdown_drain(pools.reject);
    9914          323 :     cthrpool_destroy(pools.reject);
    9915              :   }
    9916          603 : }
    9917              : 
    9918              : // One set of pools that a restart took out of service. They drain on a thread
    9919              : // of their own with no forced unblock, so a restart neither waits for nor cuts
    9920              : // off a request of the previous run. The records form the list
    9921              : // srv->retired_pools. Each task of these pools references srv, so every
    9922              : // teardown of srv waits for all records through retired_pools_reap. Nothing
    9923              : // reaches these pools through srv after the detach: Every submit reads the
    9924              : // current pool under srv->mutex, and a submit that read an old pool lands
    9925              : // before its drain or is refused like a full pool.
    9926              : typedef struct chttpsvr_retired_pools {
    9927              :   struct chttpsvr_retired_pools *next;
    9928              :   struct chttpserver *srv;
    9929              :   detached_pools pools;
    9930              :   ccol__thread_id thread;
    9931              :   // has_thread is set when a drain thread was started for this record; done is
    9932              :   // set under srv->mutex once that thread has finished.
    9933              :   bool has_thread;
    9934              :   bool done;
    9935              : } chttpsvr_retired_pools;
    9936              : 
    9937              : #ifdef RUNNING_UNIT_TESTS
    9938              : // Test counters of retired pool sets that finished draining (above) and that
    9939              : // started draining (below), with their readers.
    9940              : static _Atomic size_t g_retired_drained_for_tests = 0;
    9941            2 : size_t chttpsvr__retired_drained_for_tests(void) {
    9942            2 :   return atomic_load(&g_retired_drained_for_tests);
    9943              : }
    9944              : #endif
    9945              : 
    9946              : #ifdef RUNNING_UNIT_TESTS
    9947              : static _Atomic size_t g_retired_drain_started_for_tests = 0;
    9948            2 : size_t chttpsvr__retired_drain_started_for_tests(void) {
    9949            2 :   return atomic_load(&g_retired_drain_started_for_tests);
    9950              : }
    9951              : #endif
    9952              : 
    9953              : // The drain thread of a retired pool set: It drains and destroys the pools and
    9954              : // then sets rec->done under srv->mutex, its last touch of srv. The creating
    9955              : // thread holds srv->mutex until it has stored this thread in rec, so a reaper
    9956              : // that sees done can always join it.
    9957           40 : static void *retired_pools_drain_fn(void *arg) {
    9958           40 :   chttpsvr_retired_pools *rec = (chttpsvr_retired_pools *)arg;
    9959              : #ifdef RUNNING_UNIT_TESTS
    9960           40 :   atomic_fetch_add(&g_retired_drain_started_for_tests, 1);
    9961              : #endif
    9962           40 :   destroy_detached_pools(rec->pools);
    9963              : #ifdef RUNNING_UNIT_TESTS
    9964           40 :   atomic_fetch_add(&g_retired_drained_for_tests, 1);
    9965              : #endif
    9966           40 :   struct chttpserver *srv = rec->srv;
    9967           40 :   ccol__mutex_lock(srv->mutex);
    9968           40 :   rec->done = true;
    9969           40 :   ccol__mutex_unlock(srv->mutex);
    9970           40 :   return NULL;
    9971              : }
    9972              : 
    9973              : // Starts the drain thread of rec and records it. The caller holds srv->mutex,
    9974              : // which the thread takes as its last step, so rec->thread is stored before the
    9975              : // thread can report itself done. A failed thread creation leaves has_thread
    9976              : // false, and retired_pools_reap tries again.
    9977           40 : static void retired_pools_spawn_locked(chttpsvr_retired_pools *rec) {
    9978           40 :   ccol__thread_id t;
    9979           40 :   if (ccol__thread_create(t, retired_pools_drain_fn, rec) == 0) {
    9980           40 :     rec->thread = t;
    9981           40 :     rec->has_thread = true;
    9982              :   }
    9983           40 : }
    9984              : 
    9985              : // Joins and frees every retired pool set of srv whose drain has finished, and
    9986              : // starts a drain thread for any set without one. With wait_all it takes every
    9987              : // set and waits for each; its caller is a teardown that has already ended or
    9988              : // unblocked every request, so each drain ends, and a set without a thread is
    9989              : // drained right here. The list is taken under srv->mutex and the joins and
    9990              : // frees happen after it is released.
    9991         1132 : static void retired_pools_reap(struct chttpserver *srv, bool wait_all) {
    9992         1132 :   ccol__mutex_lock(srv->mutex);
    9993         1132 :   chttpsvr_retired_pools *keep = NULL, *finish = NULL;
    9994         1132 :   chttpsvr_retired_pools *r = srv->retired_pools;
    9995         1132 :   srv->retired_pools = NULL;
    9996         1183 :   while (r) {
    9997           51 :     chttpsvr_retired_pools *next = r->next;
    9998           51 :     if (!wait_all && !r->has_thread) retired_pools_spawn_locked(r);
    9999           20 :     if (wait_all || r->done) {
   10000           37 :       r->next = finish;
   10001           37 :       finish = r;
   10002              :     } else {
   10003           14 :       r->next = keep;
   10004           14 :       keep = r;
   10005              :     }
   10006              :     r = next;
   10007              :   }
   10008         1132 :   srv->retired_pools = keep;
   10009         1132 :   ccol__mutex_unlock(srv->mutex);
   10010         1169 :   while (finish) {
   10011           37 :     chttpsvr_retired_pools *next = finish->next;
   10012           37 :     if (finish->has_thread)
   10013           37 :       ccol__thread_join(finish->thread);
   10014              :     else
   10015            0 :       destroy_detached_pools(finish->pools);
   10016           37 :     ccol__mem_free(srv->m_procs, finish);
   10017              :     finish = next;
   10018              :   }
   10019         1132 : }
   10020              : 
   10021              : #ifdef RUNNING_UNIT_TESTS
   10022              : // Test hook: The worker pool the latest retire_pools call took out of service,
   10023              : // and a reader that tells whether that pool's shutdown has started (after which
   10024              : // submits to it are refused). A pool that doesn't resolve was destroyed, which
   10025              : // counts as started. The caller must hold a task of that pool so it can't be
   10026              : // destroyed while the reader looks at it.
   10027              : static _Atomic cthrpool g_last_retired_worker_pool_for_tests = CTHRPOOL_NULL;
   10028              : 
   10029            1 : bool chttpsvr__retired_worker_shutdown_started_for_tests(void) {
   10030            1 :   cthrpool h = atomic_load(&g_last_retired_worker_pool_for_tests);
   10031            1 :   if (h == CTHRPOOL_NULL) return false;
   10032            1 :   struct cthread_pool *pool = cthrpool__resolve_for_tests(h);
   10033            1 :   if (!pool) return true;
   10034            1 :   bool started = false;
   10035            1 :   cthrpool__shutdown_state_for_tests(pool, &started, NULL, NULL);
   10036            1 :   return started;
   10037              : }
   10038              : #endif
   10039              : 
   10040              : // Takes pools out of service without waiting: It allocates a
   10041              : // chttpsvr_retired_pools record, starts its drain thread and links it into
   10042              : // srv->retired_pools under srv->mutex. A set with no pool does nothing. When
   10043              : // the record can't be allocated, the pools drain on the calling thread, again
   10044              : // without a forced unblock.
   10045          343 : static void retire_pools(struct chttpserver *srv, detached_pools pools) {
   10046          343 :   if (!pools.worker && !pools.reject && !pools.stream) return;
   10047              : #ifdef RUNNING_UNIT_TESTS
   10048           40 :   if (pools.worker)
   10049           40 :     atomic_store(&g_last_retired_worker_pool_for_tests, pools.worker);
   10050              : #endif
   10051           80 :   chttpsvr_retired_pools *rec =
   10052           40 :       (chttpsvr_retired_pools *)ccol__mem_alloc(srv->m_procs, sizeof(*rec));
   10053           40 :   if (!rec) {
   10054            0 :     destroy_detached_pools(pools);
   10055            0 :     return;
   10056              :   }
   10057           40 :   rec->srv = srv;
   10058           40 :   rec->pools = pools;
   10059           40 :   rec->has_thread = false;
   10060           40 :   rec->done = false;
   10061           40 :   ccol__mutex_lock(srv->mutex);
   10062           40 :   retired_pools_spawn_locked(rec);
   10063           40 :   rec->next = srv->retired_pools;
   10064           40 :   srv->retired_pools = rec;
   10065           40 :   ccol__mutex_unlock(srv->mutex);
   10066              : }
   10067              : 
   10068              : // Detaches srv's current pools under srv->mutex, starts a new streaming run so
   10069              : // no queued streaming request goes to them, and retires them. The failure paths
   10070              : // of chttpsvr_start use it. With no worker pool there's no run, so the
   10071              : // stream_token_start call gives a queued streaming request its 503 at once.
   10072           21 : static void retire_current_pools(struct chttpserver *srv) {
   10073           21 :   ccol__mutex_lock(srv->mutex);
   10074           21 :   detached_pools out = {srv->worker_pool, srv->reject_pool, srv->stream_pool};
   10075           21 :   srv->worker_pool = CTHRPOOL_NULL;
   10076           21 :   srv->reject_pool = CTHRPOOL_NULL;
   10077           21 :   srv->stream_pool = CTHRPOOL_NULL;
   10078           21 :   stream_new_run_locked(srv);
   10079           21 :   ccol__mutex_unlock(srv->mutex);
   10080           21 :   retire_pools(srv, out);
   10081           21 :   stream_token_start(srv);
   10082           21 : }
   10083              : 
   10084              : // The drain step of a teardown: It gives every body-memory waiter and every
   10085              : // queued streaming request its answer, closes the idle keep-alive connections
   10086              : // (the server is draining, so they would get nothing more), waits for in-flight
   10087              : // requests through wait_in_flight_bounded, and detaches the pools, all in one
   10088              : // srv->mutex critical section with a final idle-close pass. Holding the lock
   10089              : // from the wait to that pass keeps a keep-alive connection from being diverted
   10090              : // again after the pass and leaking once the engine goes. Parked connections
   10091              : // carry on, since they hold a request being served.
   10092              : // It then polls, every millisecond up to CHTTPSVR_DRAIN_CONNECTIONS_WAIT_MS,
   10093              : // until srv->current_connections reaches 0, repeating the idle-close pass. That
   10094              : // count covers connections the idle list can't see (one in its handshake on the
   10095              : // reactor, one a dispatch claimed and closes itself), which the reactor may be
   10096              : // touching when srv is freed. A poll is used because a broadcast from every
   10097              : // conn_free would cost the hot close path. It gives the detached pools to the
   10098              : // caller.
   10099          563 : static detached_pools drain_and_close_all_connections(struct chttpserver *srv) {
   10100          563 :   mem_admission_close(srv);
   10101          563 :   stream_queue_flush(srv);
   10102          563 :   close_idle_connections(srv, false);
   10103          563 :   ccol__mutex_lock(srv->mutex);
   10104          563 :   wait_in_flight_bounded(srv);
   10105          563 :   detached_pools out = {srv->worker_pool, srv->reject_pool, srv->stream_pool};
   10106          563 :   srv->worker_pool = CTHRPOOL_NULL;
   10107          563 :   srv->reject_pool = CTHRPOOL_NULL;
   10108          563 :   srv->stream_pool = CTHRPOOL_NULL;
   10109          563 :   stream_new_run_locked(srv);
   10110          563 :   close_all_idle_connections(srv);
   10111          563 :   mem_wait_flush(srv);
   10112          563 :   ccol__mutex_unlock(srv->mutex);
   10113              : 
   10114          563 :   unsigned drain_wait_ms = CHTTPSVR_DRAIN_CONNECTIONS_WAIT_MS;
   10115              : #ifdef RUNNING_UNIT_TESTS
   10116          563 :   unsigned override_drain_wait_ms =
   10117          563 :       atomic_load(&g_drain_connections_wait_ms_for_tests);
   10118          563 :   if (override_drain_wait_ms) drain_wait_ms = override_drain_wait_ms;
   10119              : #endif
   10120          563 :   struct timespec poll_deadline;
   10121          563 :   clock_gettime(CLOCK_MONOTONIC, &poll_deadline);
   10122          563 :   timespec_add_ms(&poll_deadline, drain_wait_ms);
   10123          719 :   while (atomic_load(&srv->current_connections) > 0) {
   10124          157 :     struct timespec now;
   10125          157 :     clock_gettime(CLOCK_MONOTONIC, &now);
   10126          157 :     if (now.tv_sec > poll_deadline.tv_sec ||
   10127           49 :         (now.tv_sec == poll_deadline.tv_sec &&
   10128           49 :          now.tv_nsec >= poll_deadline.tv_nsec))
   10129              :       break;
   10130          156 :     struct timespec nap = {0, 1000000L};
   10131          156 :     nanosleep(&nap, NULL);
   10132          156 :     close_all_idle_connections(srv);
   10133          156 :     mem_wait_flush(srv);
   10134          156 :     stream_queue_flush(srv);
   10135              :   }
   10136          563 :   return out;
   10137              : }
   10138              : 
   10139              : // The full teardown of a server, run exactly once: Stop listening, drain
   10140              : // requests and connections, reap retired pools, drop the engine reference,
   10141              : // destroy the pools, unregister from servers_bundler.servers, and start the
   10142              : // engine reaper when that reference was the last. chttpsvr__destroy and the
   10143              : // force-stop pass of chttpsvr_engine_stop (engine_force_stop_quiesce_all) can
   10144              : // both call it, at the same time. The first caller claims it through
   10145              : // srv->quiesce_state and sets draining; a later caller counts itself in
   10146              : // quiesce_waiters and blocks until CHTTPSVR_QS_QUIESCED, because
   10147              : // chttpsvr__destroy destroys srv->mutex and frees srv right after this returns.
   10148              : // The winner first waits for pending_resolve_count to reach 0, so a
   10149              : // chttpsvr_start that holds an engine reference can't go on using a reactor
   10150              : // torn down under it. The drain comes before the engine release, since the
   10151              : // reaper destroys the reactor. The unregister comes after the release, so a
   10152              : // concurrent reap finds srv and waits for this quiesce, and the reaper starts
   10153              : // only after it, because a reaper that runs inline would otherwise wait for
   10154              : // this very thread. At the end the winner waits for quiesce_waiters to fall to
   10155              : // 0, so no loser touches srv->mutex or quiesce_done_cv after its caller
   10156              : // destroys them.
   10157          585 : static void quiesce_server_once(struct chttpserver *srv) {
   10158          585 :   ccol__mutex_lock(srv->mutex);
   10159          585 :   switch (srv->quiesce_state) {
   10160           22 :     case CHTTPSVR_QS_QUIESCING:
   10161              :     case CHTTPSVR_QS_QUIESCED: {
   10162           22 :       srv->quiesce_waiters++;
   10163           25 :       while (srv->quiesce_state != CHTTPSVR_QS_QUIESCED)
   10164            3 :         ccol__cond_var_wait(srv->quiesce_done_cv, srv->mutex);
   10165           22 :       srv->quiesce_waiters--;
   10166           22 :       ccol__cond_var_broadcast(srv->quiesce_done_cv);
   10167           22 :       ccol__mutex_unlock(srv->mutex);
   10168           22 :       return;
   10169              :     }
   10170          563 :     case CHTTPSVR_QS_NOT_QUIESCED:
   10171          563 :       srv->quiesce_state = CHTTPSVR_QS_QUIESCING;
   10172          563 :       srv_begin_draining(srv);
   10173              : #ifdef RUNNING_UNIT_TESTS
   10174          563 :       quiesce_claimed_signal_fire_if_armed();
   10175              : #endif
   10176          563 :       break;
   10177              :   }
   10178          568 :   while (atomic_load(&srv->pending_resolve_count) > 0)
   10179            5 :     ccol__cond_var_wait(srv->resolve_cv, srv->mutex);
   10180          563 :   ccol__mutex_unlock(srv->mutex);
   10181              : 
   10182              : #ifdef RUNNING_UNIT_TESTS
   10183          563 :   quiesce_teardown_race_hook_wait_if_armed();
   10184              : #endif
   10185              : 
   10186          563 :   chttpsvr_stop_internal(srv);
   10187              : 
   10188          563 :   detached_pools old_pools = drain_and_close_all_connections(srv);
   10189          563 :   retired_pools_reap(srv, true);
   10190              : 
   10191          563 :   bool should_release_engine = false;
   10192          563 :   uintptr_t engine_gen = 0;
   10193          563 :   ccol__mutex_lock(srv->mutex);
   10194          563 :   if (srv->contributed_to_engine) {
   10195          284 :     srv->contributed_to_engine = false;
   10196          284 :     should_release_engine = true;
   10197          284 :     engine_gen = srv->engine_gen;
   10198          284 :     srv->engine_gen = 0;
   10199              :   }
   10200          563 :   ccol__mutex_unlock(srv->mutex);
   10201          563 :   bool should_reap = should_release_engine && engine_release_begin(engine_gen);
   10202              : 
   10203          563 :   destroy_detached_pools(old_pools);
   10204          563 :   servers_unregister(srv);
   10205          563 :   if (should_reap) spawn_reaper();
   10206              : 
   10207          563 :   ccol__mutex_lock(srv->mutex);
   10208          563 :   srv->quiesce_state = CHTTPSVR_QS_QUIESCED;
   10209          563 :   ccol__cond_var_broadcast(srv->quiesce_done_cv);
   10210          569 :   while (srv->quiesce_waiters > 0)
   10211            6 :     ccol__cond_var_wait(srv->quiesce_done_cv, srv->mutex);
   10212          563 :   ccol__mutex_unlock(srv->mutex);
   10213              : }
   10214              : 
   10215              : // Destroys the server behind srv. It resolves the handle and clears the slot's
   10216              : // in_use flag in one critical section of the slot table, so a second destroy
   10217              : // reaches the fatal stale-handle error; a call from a handler running on this
   10218              : // server's own pools is fatal too, since its drain would wait for itself. It
   10219              : // then waits for every pinned resolve, quiesces the server, waits for
   10220              : // servers_bundler_pins and listener_dispatch_pins (a force-stop pass and a
   10221              : // listener dispatch can hold a bare pointer to raw), and releases the TLS
   10222              : // context. Last it drops the application's raw->lifetime_refs reference;
   10223              : // whoever drops the last one, this call or a conn_on_removed, runs
   10224              : // chttpsvr_finish_destroy.
   10225          563 : void chttpsvr__destroy(chttpsvr srv) {
   10226          563 :   if (!srv) return;
   10227              : 
   10228          563 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   10229          563 :   uint32_t idx = (uint32_t)(srv >> 32);
   10230          563 :   uint32_t gen = (uint32_t)(srv & 0xFFFFFFFFu);
   10231          563 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   10232          563 :   chttpsvr_slot *slot = NULL;
   10233          563 :   struct chttpserver *raw = NULL;
   10234         1126 :   if (chttpsvr_slot_table.slots &&
   10235          563 :       idx < cvector_size(chttpsvr_slot_table.slots)) {
   10236          563 :     chttpsvr_slot *s =
   10237          563 :         (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx);
   10238          563 :     if (s->in_use && s->generation == gen) {
   10239          561 :       slot = s;
   10240          561 :       raw = s->ptr;
   10241              :     }
   10242              :   }
   10243          561 :   if (!raw) {
   10244            2 :     ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10245            2 :     ccol__fatal_err(
   10246              :         "chttpsvr_destroy: handle is stale or already destroyed "
   10247              :         "(double-destroy / use-after-destroy of a chttpsvr handle)");
   10248              :   }
   10249          561 :   if (chttpsvr_is_self_call(raw)) {
   10250            1 :     ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10251            1 :     ccol__fatal_err(
   10252              :         "chttpsvr_destroy: called from within a request handler (or "
   10253              :         "middleware) running on this very server's own worker pool; "
   10254              :         "destroying it here would deadlock waiting for this exact "
   10255              :         "in-flight request to finish, then abort when the pool's own "
   10256              :         "self-destroy guard fires. Destroy the server from a different "
   10257              :         "thread instead, or call chttpsvr_engine_stop() (documented "
   10258              :         "safe to call from within a handler) if a full shutdown is the "
   10259              :         "actual goal.");
   10260              :   }
   10261          560 :   slot->in_use = false;
   10262          560 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10263              : 
   10264          560 :   ccol__mutex_lock(raw->mutex);
   10265          560 :   while (atomic_load(&raw->pending_resolve_count) > 0)
   10266            0 :     ccol__cond_var_wait(raw->resolve_cv, raw->mutex);
   10267          560 :   ccol__mutex_unlock(raw->mutex);
   10268              : 
   10269          560 :   quiesce_server_once(raw);
   10270              : 
   10271          560 :   ccol__mutex_lock(raw->mutex);
   10272          563 :   while (atomic_load(&raw->servers_bundler_pins) > 0 ||
   10273          560 :          atomic_load(&raw->listener_dispatch_pins) > 0)
   10274            3 :     ccol__cond_var_wait(raw->resolve_cv, raw->mutex);
   10275          560 :   ccol__mutex_unlock(raw->mutex);
   10276              : 
   10277          560 :   if (raw->tls_ctx) {
   10278           11 :     ctls_ctx_release(raw->tls_ctx);
   10279           11 :     raw->tls_ctx = NULL;
   10280              :   }
   10281              : 
   10282          560 :   if (atomic_fetch_sub(&raw->lifetime_refs, 1) == 1)
   10283          557 :     chttpsvr_finish_destroy(raw);
   10284              : }
   10285              : 
   10286              : #ifdef RUNNING_UNIT_TESTS
   10287              : // Test hooks: A test names one server whose chttpsvr_finish_destroy it watches
   10288              : // and asks whether that ran. The second counter records route teardowns that
   10289              : // found a connection of the server allocated; it must stay 0, since such a
   10290              : // connection could read its matched route.
   10291              : static _Atomic(struct chttpserver *) g_finish_destroy_watch_for_tests = NULL;
   10292              : static _Atomic size_t g_route_teardown_with_live_connections_for_tests = 0;
   10293            2 : size_t chttpsvr__route_teardown_with_live_connections_for_tests(void) {
   10294            2 :   return atomic_load(&g_route_teardown_with_live_connections_for_tests);
   10295              : }
   10296              : static _Atomic bool g_finish_destroy_watch_hit_for_tests = false;
   10297            2 : void chttpsvr__watch_finish_destroy_for_tests(chttpsvr h) {
   10298            2 :   atomic_store(&g_finish_destroy_watch_hit_for_tests, false);
   10299            2 :   atomic_store(&g_finish_destroy_watch_for_tests,
   10300              :                chttpsvr__resolve_for_tests(h));
   10301            2 : }
   10302            5 : bool chttpsvr__watched_finish_destroy_ran_for_tests(void) {
   10303            5 :   return atomic_load(&g_finish_destroy_watch_hit_for_tests);
   10304              : }
   10305              : #endif
   10306              : 
   10307              : static void chttpsvr_release_slot_table_if_deferred_locked(void);
   10308              : 
   10309              : // The final teardown of a server, run by whoever drops the last
   10310              : // raw->lifetime_refs reference (chttpsvr__destroy or conn_on_removed). It frees
   10311              : // the routers and their route and middleware data here, because a connection a
   10312              : // slow handler owns reads its matched route until its conn_free, and each such
   10313              : // connection holds a reference. No router call can reach the routers either,
   10314              : // since their owner handle doesn't resolve. It then destroys the locks, closes
   10315              : // the logger and frees raw. The slot is released last, under the slot table
   10316              : // mutex and fetched again by index (a concurrent create may have moved the slot
   10317              : // array): ptr goes NULL, the generation moves past the stale handle's, and the
   10318              : // index returns to the free list. When the exit-time destructor deferred the
   10319              : // table release, this may be the call that does it.
   10320          559 : static void chttpsvr_finish_destroy(struct chttpserver *raw) {
   10321              : #ifdef RUNNING_UNIT_TESTS
   10322          559 :   if (atomic_load(&g_finish_destroy_watch_for_tests) == raw) {
   10323            2 :     atomic_store(&g_finish_destroy_watch_for_tests, NULL);
   10324            2 :     atomic_store(&g_finish_destroy_watch_hit_for_tests, true);
   10325              :   }
   10326              : #endif
   10327              : #ifdef RUNNING_UNIT_TESTS
   10328          559 :   if (atomic_load(&raw->current_connections) > 0)
   10329            0 :     atomic_fetch_add(&g_route_teardown_with_live_connections_for_tests, 1);
   10330              : #endif
   10331         1507 :   for (size_t i = 0; i < raw->router_count; i++) {
   10332          948 :     destroy_router(raw->routers[i], raw->m_procs);
   10333              :   }
   10334          559 :   chttpsvr_router_shells_release(raw->routers, raw->router_count,
   10335              :                                  raw->root_router);
   10336          559 :   raw->root_router = NULL;
   10337          559 :   ccol__mem_free(raw->m_procs, raw->routers);
   10338              : 
   10339          559 :   ccol__mutex_destroy(raw->mutex);
   10340          559 :   ccol__mutex_destroy(raw->idle_mutex);
   10341          559 :   ccol__mutex_destroy(raw->diverted_mutex);
   10342          559 :   ccol__mutex_destroy(raw->wait_mutex);
   10343          559 :   ccol__cond_var_destroy(raw->requests_done_cv);
   10344          559 :   ccol__cond_var_destroy(raw->resolve_cv);
   10345          559 :   ccol__cond_var_destroy(raw->quiesce_done_cv);
   10346          559 :   ccol__rw_lock_destroy(raw->routes_lock);
   10347              : 
   10348          559 :   clog_close(raw->cl);
   10349          559 :   raw->cl = CLOG_NULL;
   10350              : 
   10351          559 :   uint32_t idx = raw->self_slot_idx;
   10352          559 :   ccol_memmgmt_procs *mp = raw->m_procs;
   10353          559 :   ccol__mem_free(mp, raw);
   10354          559 :   ccol__mem_free(mp, mp);
   10355              : 
   10356          559 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   10357          559 :   chttpsvr_slot *slot2 =
   10358          559 :       (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx);
   10359          559 :   slot2->ptr = NULL;
   10360          559 :   slot2->generation++;
   10361          559 :   cvector_push_back(chttpsvr_slot_table.free_indices, &idx);
   10362          559 :   chttpsvr_release_slot_table_if_deferred_locked();
   10363          559 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10364          559 : }
   10365              : 
   10366              : // Tells whether slot belongs to a server, so the table must not be released
   10367              : // under it. It reads ptr and not in_use, because in_use is cleared as the first
   10368              : // step of chttpsvr__destroy, while ptr stays set until the final locked release
   10369              : // of the slot, which indexes the table.
   10370           19 : static bool chttpsvr_slot_live(const chttpsvr_slot *slot) {
   10371           19 :   return slot->ptr != NULL;
   10372              : }
   10373              : 
   10374              : #ifdef RUNNING_UNIT_TESTS
   10375              : // Test hooks: The first asks chttpsvr_slot_live about the slot of h, the second
   10376              : // sets that slot's in_use flag, so a test can build the window between the two
   10377              : // fields without racing a real teardown.
   10378            3 : bool chttpsvr__slot_live_for_tests(chttpsvr h) {
   10379            3 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   10380            3 :   uint32_t idx = (uint32_t)(h >> 32);
   10381            3 :   bool live = false;
   10382            3 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   10383            6 :   if (chttpsvr_slot_table.slots &&
   10384            3 :       idx < cvector_size(chttpsvr_slot_table.slots))
   10385            6 :     live = chttpsvr_slot_live(
   10386            3 :         (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx));
   10387            3 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10388            3 :   return live;
   10389              : }
   10390              : 
   10391            2 : void chttpsvr__slot_set_in_use_for_tests(chttpsvr h, bool in_use) {
   10392            2 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   10393            2 :   uint32_t idx = (uint32_t)(h >> 32);
   10394            2 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   10395            4 :   if (chttpsvr_slot_table.slots &&
   10396            2 :       idx < cvector_size(chttpsvr_slot_table.slots))
   10397            2 :     ((chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx))->in_use =
   10398              :         in_use;
   10399            2 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10400            2 : }
   10401              : #endif
   10402              : 
   10403              : // Tells whether any slot of the table names a server. The caller holds the
   10404              : // table's mutex and the table exists.
   10405            8 : static bool chttpsvr_any_slot_live_locked(void) {
   10406            8 :   size_t slot_count = cvector_size(chttpsvr_slot_table.slots);
   10407           23 :   for (size_t i = 0; i < slot_count; i++)
   10408           32 :     if (chttpsvr_slot_live(
   10409           16 :             (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, i)))
   10410              :       return true;
   10411              :   return false;
   10412              : }
   10413              : 
   10414              : // Frees the slot table's arrays and sets their pointers to NULL, which every
   10415              : // resolve, acquire and fork handler tests, so a later stale handle resolves to
   10416              : // nothing and a create fails cleanly. It also deletes the worker key: With no
   10417              : // server left no worker thread of any server is left, so a dlclose() doesn't
   10418              : // leak the key. The caller holds the table's mutex, the table exists and no
   10419              : // slot is live.
   10420            7 : static void chttpsvr_release_slot_table_locked(void) {
   10421            7 :   cvector__destroy(chttpsvr_slot_table.slots);
   10422            7 :   cvector__destroy(chttpsvr_slot_table.free_indices);
   10423            7 :   chttpsvr_slot_table.slots = NULL;
   10424            7 :   chttpsvr_slot_table.free_indices = NULL;
   10425            7 :   chttpsvr_slot_table.release_deferred = false;
   10426            7 :   ccol__call_once(chttpsvr_worker_key_bundle.once,
   10427              :                   chttpsvr_worker_key_init_globals);
   10428            7 :   ccol__mutex_lock(chttpsvr_worker_key_bundle.mutex);
   10429            7 :   if (atomic_exchange(&chttpsvr_worker_key_bundle.ready, false))
   10430            7 :     ccol__thread_ls_key_delete(chttpsvr_worker_key_bundle.key);
   10431            7 :   ccol__mutex_unlock(chttpsvr_worker_key_bundle.mutex);
   10432            7 : }
   10433              : 
   10434              : // Does the table release the exit-time destructor deferred, once the last
   10435              : // server is gone. The caller holds the table's mutex. It is out of line so the
   10436              : // destroy path keeps its shape.
   10437              : static __attribute__((noinline)) void
   10438          559 : chttpsvr_release_slot_table_if_deferred_locked(void) {
   10439          560 :   if (chttpsvr_slot_table.release_deferred && chttpsvr_slot_table.slots &&
   10440            1 :       !chttpsvr_any_slot_live_locked())
   10441            1 :     chttpsvr_release_slot_table_locked();
   10442          559 : }
   10443              : 
   10444              : // Frees the slot table at process exit or unload so memtest doesn't report it,
   10445              : // but only when no slot is live. A server the application hasn't destroyed may
   10446              : // be used from a later destructor or atexit handler, so then the release is
   10447              : // deferred to the destroy of the last server. A process that never entered the
   10448              : // initialization returns at once, since initializing here would build the slot
   10449              : // tables of clogger and cthreadpool after their own destructors ran.
   10450            7 : __attribute__((destructor)) static void cleanup_chttpsvr_slot_table(void) {
   10451            7 :   if (!atomic_load(&chttpsvr_slot_table_entered)) return;
   10452            7 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   10453            7 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   10454            7 :   if (chttpsvr_slot_table.slots) {
   10455            7 :     if (chttpsvr_any_slot_live_locked())
   10456            1 :       chttpsvr_slot_table.release_deferred = true;
   10457              :     else
   10458            6 :       chttpsvr_release_slot_table_locked();
   10459              :   }
   10460            7 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   10461              : }
   10462              : 
   10463              : // Starts or restarts the server behind h with cfg (NULL means
   10464              : // CHTTPSVR_CONFIG_DEFAULT). It refuses a cfg->tls without both cert_path and
   10465              : // key_path, so a TLS setting never silently gives plain HTTP, and a negative
   10466              : // streaming_thread_count other than CHTTPSVR_STREAMING_POOL_OFF. A call from
   10467              : // one of the server's own handlers gives ccol_not_permitted, and a server that
   10468              : // is starting or running too.
   10469              : // Under raw->mutex it waits out a concurrent stop (keeping its pin) and a
   10470              : // quiesce in progress (dropping its pin first, since the quiesce waits for
   10471              : // pins, and counting itself in quiesce_waiters before the drop so raw stays
   10472              : // alive), resolving h again after each wait. It then claims
   10473              : // CHTTPSVR_LC_STARTING and resets quiesce_state and draining. It builds the new
   10474              : // pools, stores the settings in milliseconds, swaps the pools in under
   10475              : // srv->mutex and retires the previous run's, builds the TLS context, registers
   10476              : // srv (before engine_acquire, so a concurrent force-stop finds it), takes an
   10477              : // engine reference, starts the idle sweep, binds the listen socket and
   10478              : // registers the listener with one extra lifetime_refs reference. listen_fd is
   10479              : // published before that registration, since a connection can arrive at once.
   10480              : // When a reap is in progress it unwinds, waits on srv_engine_bundler.stopped_cv
   10481              : // with no pin held and retries. Every failure path undoes its steps, retires
   10482              : // the new pools and sets the lifecycle back to idle.
   10483          337 : ccol_retval chttpsvr_start(chttpsvr h, const chttpsvr_config *cfg) {
   10484          337 :   if (cfg && cfg->tls && !(cfg->tls->cert_path && cfg->tls->key_path))
   10485              :     return ccol_invalid_args;
   10486          331 :   if (cfg && cfg->streaming_thread_count < CHTTPSVR_STREAMING_POOL_OFF)
   10487              :     return ccol_invalid_args;
   10488              : 
   10489          333 :   struct chttpserver *raw = chttpsvr_resolve(h);
   10490          333 :   if (!raw) return ccol_invalid_args;
   10491              : 
   10492          332 :   if (!chttpsvr_worker_key_ensure()) {
   10493            1 :     SRV_ENGINE_LOG(clog_error,
   10494              :                    "chttpsvr_start: no thread-specific key is available "
   10495              :                    "(the process holds PTHREAD_KEYS_MAX keys)");
   10496            1 :     chttpsvr_resolve_unpin(raw);
   10497            1 :     return ccol_unexpected_failure;
   10498              :   }
   10499              : 
   10500              : #ifdef RUNNING_UNIT_TESTS
   10501          331 :   start_resolve_race_hook_wait_if_armed();
   10502              : #endif
   10503              : 
   10504          331 :   if (chttpsvr_is_self_call(raw)) {
   10505            2 :     chttpsvr_resolve_unpin(raw);
   10506            2 :     return ccol_not_permitted;
   10507              :   }
   10508              : 
   10509          329 :   chttpsvr_config default_cfg = CHTTPSVR_CONFIG_DEFAULT;
   10510          329 :   if (!cfg) cfg = &default_cfg;
   10511              : 
   10512          329 :   ccol__mutex_lock(raw->mutex);
   10513          341 :   for (;;) {
   10514          335 :     switch (raw->lifecycle) {
   10515            2 :       case CHTTPSVR_LC_STARTING:
   10516              :       case CHTTPSVR_LC_RUNNING:
   10517            2 :         ccol__mutex_unlock(raw->mutex);
   10518            2 :         chttpsvr_resolve_unpin(raw);
   10519          329 :         return ccol_not_permitted;
   10520            2 :       case CHTTPSVR_LC_STOPPING: {
   10521              : #ifdef RUNNING_UNIT_TESTS
   10522            2 :         start_stopping_wait_signal_fire_if_armed();
   10523              : #endif
   10524            4 :         while (raw->lifecycle == CHTTPSVR_LC_STOPPING)
   10525            2 :           ccol__cond_var_wait(raw->resolve_cv, raw->mutex);
   10526            6 :         continue;
   10527              :       }
   10528              :       case CHTTPSVR_LC_IDLE:
   10529              :         break;
   10530              :     }
   10531          331 :     switch (raw->quiesce_state) {
   10532            3 :       case CHTTPSVR_QS_QUIESCING:
   10533            3 :         raw->quiesce_waiters++;
   10534            3 :         ccol__mutex_unlock(raw->mutex);
   10535            3 :         chttpsvr_resolve_unpin(raw);
   10536              : #ifdef RUNNING_UNIT_TESTS
   10537            3 :         start_quiescing_unpinned_race_hook_wait_if_armed();
   10538              : #endif
   10539            3 :         ccol__mutex_lock(raw->mutex);
   10540            5 :         while (raw->quiesce_state != CHTTPSVR_QS_QUIESCED)
   10541            2 :           ccol__cond_var_wait(raw->quiesce_done_cv, raw->mutex);
   10542            3 :         raw->quiesce_waiters--;
   10543            3 :         ccol__cond_var_broadcast(raw->quiesce_done_cv);
   10544            3 :         ccol__mutex_unlock(raw->mutex);
   10545            3 :         raw = chttpsvr_resolve(h);
   10546            3 :         if (!raw) return ccol_invalid_args;
   10547            2 :         ccol__mutex_lock(raw->mutex);
   10548            2 :         continue;
   10549              :       case CHTTPSVR_QS_NOT_QUIESCED:
   10550              :       case CHTTPSVR_QS_QUIESCED:
   10551              :         break;
   10552              :     }
   10553          328 :     raw->lifecycle = CHTTPSVR_LC_STARTING;
   10554          328 :     raw->quiesce_state = CHTTPSVR_QS_NOT_QUIESCED;
   10555          328 :     __atomic_store_n(&raw->draining, false, __ATOMIC_RELAXED);
   10556          328 :     ccol__mutex_unlock(raw->mutex);
   10557              : 
   10558          328 :     retired_pools_reap(raw, false);
   10559              : 
   10560          328 :     int nthreads = cfg->worker_thread_count;
   10561          328 :     if (nthreads <= 0) {
   10562          289 :       long cpus = sysconf(_SC_NPROCESSORS_ONLN);
   10563          289 :       nthreads = (cpus > 0) ? (int)cpus : 1;
   10564              :     }
   10565          328 :     size_t queue_cap;
   10566          328 :     if (cfg->worker_queue_capacity == CHTTPSVR_QUEUE_UNBOUNDED) {
   10567              :       queue_cap = 0;
   10568          328 :     } else if (cfg->worker_queue_capacity == 0) {
   10569          319 :       queue_cap = (size_t)1024 * (size_t)nthreads;
   10570              :     } else {
   10571              :       queue_cap = cfg->worker_queue_capacity;
   10572              :     }
   10573              : 
   10574          328 :     char *pool_err = NULL;
   10575          328 :     cthrpool new_pool = cthrpool_create_mp((size_t)nthreads, queue_cap,
   10576              :                                            raw->m_procs, &pool_err);
   10577          328 :     if (!new_pool) {
   10578            3 :       ccol__mutex_lock(raw->mutex);
   10579            3 :       raw->lifecycle = CHTTPSVR_LC_IDLE;
   10580            3 :       ccol__mutex_unlock(raw->mutex);
   10581            3 :       chttpsvr_resolve_unpin(raw);
   10582            3 :       return ccol_not_enough_memory;
   10583              :     }
   10584              : 
   10585          325 :     int reject_nthreads = nthreads / 2;
   10586          325 :     if (reject_nthreads < CHTTPSVR_REJECT_POOL_MIN_THREADS)
   10587           35 :       reject_nthreads = CHTTPSVR_REJECT_POOL_MIN_THREADS;
   10588          325 :     char *reject_pool_err = NULL;
   10589          325 :     cthrpool new_reject_pool = cthrpool_create_mp(
   10590              :         (size_t)reject_nthreads, CHTTPSVR_REJECT_POOL_QUEUE_CAP, raw->m_procs,
   10591              :         &reject_pool_err);
   10592          325 :     if (!new_reject_pool) {
   10593            3 :       cthrpool_shutdown_drain(new_pool);
   10594            3 :       cthrpool_destroy(new_pool);
   10595            3 :       ccol__mutex_lock(raw->mutex);
   10596            3 :       raw->lifecycle = CHTTPSVR_LC_IDLE;
   10597            3 :       ccol__mutex_unlock(raw->mutex);
   10598            3 :       chttpsvr_resolve_unpin(raw);
   10599            3 :       return ccol_not_enough_memory;
   10600              :     }
   10601              : 
   10602          322 :     unsigned stream_read_ms = cfg_us_to_ms(cfg->stream_read_timeout_us);
   10603          322 :     atomic_store(&raw->stream_read_timeout_ms, stream_read_ms);
   10604          322 :     atomic_store(&raw->max_body_read_duration_ms,
   10605              :                  cfg_us_to_ms(cfg->max_body_read_duration_us));
   10606          322 :     atomic_store(&raw->response_write_timeout_ms,
   10607              :                  cfg->response_write_timeout_us
   10608              :                      ? cfg_us_to_ms(cfg->response_write_timeout_us)
   10609              :                      : stream_read_ms);
   10610          322 :     atomic_store(&raw->max_response_write_duration_ms,
   10611              :                  cfg_us_to_ms(cfg->max_response_write_duration_us));
   10612          322 :     atomic_store(&raw->max_header_read_duration_ms,
   10613              :                  cfg_us_to_ms(cfg->max_header_read_duration_us));
   10614          322 :     atomic_store(&raw->idle_timeout_ms,
   10615              :                  cfg_us_to_ms(cfg->idle_timeout_us ? cfg->idle_timeout_us
   10616              :                                                    : cfg->read_timeout_us));
   10617          322 :     atomic_store(&raw->max_body_size, cfg->max_body_size);
   10618          322 :     atomic_store(&raw->max_header_bytes, cfg->max_header_bytes);
   10619          322 :     atomic_store(&raw->max_connections, cfg->max_connections);
   10620          322 :     raw->enable_keepalive = cfg->enable_keepalive;
   10621              :     {
   10622          322 :       atomic_store(&raw->min_rate_bps, cfg->min_transfer_rate_bps
   10623              :                                            ? cfg->min_transfer_rate_bps
   10624              :                                            : CHTTPSVR_DEFAULT_MIN_RATE_BPS);
   10625          322 :       atomic_store(&raw->rate_grace_ms,
   10626              :                    cfg->min_transfer_rate_grace_us
   10627              :                        ? cfg_us_to_ms(cfg->min_transfer_rate_grace_us)
   10628              :                        : CHTTPSVR_DEFAULT_RATE_GRACE_MS);
   10629          322 :       atomic_store(&raw->mem_cap, cfg->max_partial_body_memory
   10630              :                                       ? cfg->max_partial_body_memory
   10631              :                                       : CHTTPSVR_DEFAULT_PARTIAL_BODY_MEMORY);
   10632          322 :       uint64_t mem_wait_us = cfg->body_memory_wait_timeout_us;
   10633          322 :       atomic_store(&raw->mem_wait_ms, mem_wait_us
   10634              :                                           ? cfg_deadline_us_to_ms(mem_wait_us)
   10635              :                                           : CHTTPSVR_DEFAULT_MEMORY_WAIT_MS);
   10636          322 :       int st = cfg->streaming_thread_count;
   10637          322 :       if (st == 0) st = nthreads;
   10638          322 :       if (st < 0) st = -1;
   10639          322 :       atomic_store(&raw->stream_threads, st);
   10640          322 :       size_t qcap;
   10641          322 :       if (cfg->streaming_queue_capacity == CHTTPSVR_QUEUE_UNBOUNDED)
   10642              :         qcap = SIZE_MAX;
   10643          322 :       else if (cfg->streaming_queue_capacity == 0)
   10644          321 :         qcap = st > 0 ? (size_t)4 * (size_t)st : 0;
   10645              :       else
   10646              :         qcap = cfg->streaming_queue_capacity;
   10647          322 :       atomic_store(&raw->stream_qcap, qcap);
   10648          322 :       atomic_store(&raw->stream_qtimeout_ms,
   10649              :                    cfg->streaming_queue_timeout_us
   10650              :                        ? cfg_deadline_us_to_ms(cfg->streaming_queue_timeout_us)
   10651              :                        : CHTTPSVR_DEFAULT_STREAM_QUEUE_TIMEOUT_MS);
   10652          322 :       ccol__mutex_lock(raw->wait_mutex);
   10653          322 :       raw->mem_admission_closed = false;
   10654          322 :       ccol__mutex_unlock(raw->wait_mutex);
   10655              :     }
   10656              : 
   10657          322 :     ccol__mutex_lock(raw->mutex);
   10658          322 :     detached_pools previous = {raw->worker_pool, raw->reject_pool,
   10659          322 :                                raw->stream_pool};
   10660          322 :     raw->worker_pool = new_pool;
   10661          322 :     raw->reject_pool = new_reject_pool;
   10662          322 :     raw->stream_pool = CTHRPOOL_NULL;
   10663          322 :     stream_new_run_locked(raw);
   10664          322 :     ccol__mutex_unlock(raw->mutex);
   10665              : #ifdef RUNNING_UNIT_TESTS
   10666          322 :     start_hold_for_tests();
   10667              : #endif
   10668          322 :     retire_pools(raw, previous);
   10669          322 :     stream_token_start(raw);
   10670              : 
   10671          322 :     if (raw->tls_ctx) {
   10672            1 :       ctls_ctx_release(raw->tls_ctx);
   10673            1 :       raw->tls_ctx = NULL;
   10674              :     }
   10675          322 :     if (cfg->tls && cfg->tls->cert_path && cfg->tls->key_path) {
   10676           18 :       ctls_ctx *tls_ctx = ctls_ctx_new_mp(raw->m_procs, NULL);
   10677           18 :       if (!tls_ctx) {
   10678            0 :         retire_current_pools(raw);
   10679            0 :         ccol__mutex_lock(raw->mutex);
   10680            0 :         raw->lifecycle = CHTTPSVR_LC_IDLE;
   10681            0 :         ccol__mutex_unlock(raw->mutex);
   10682            0 :         chttpsvr_resolve_unpin(raw);
   10683            0 :         return ccol_not_enough_memory;
   10684              :       }
   10685           36 :       ccol_retval tls_rv = ctls_ctx_cert_add(tls_ctx, NULL, cfg->tls->cert_path,
   10686           18 :                                              cfg->tls->key_path, NULL, NULL);
   10687           18 :       if (tls_rv != ccol_success) {
   10688            3 :         ctls_ctx_release(tls_ctx);
   10689            3 :         retire_current_pools(raw);
   10690            3 :         ccol__mutex_lock(raw->mutex);
   10691            3 :         raw->lifecycle = CHTTPSVR_LC_IDLE;
   10692            3 :         ccol__mutex_unlock(raw->mutex);
   10693            3 :         chttpsvr_resolve_unpin(raw);
   10694            3 :         return tls_rv;
   10695              :       }
   10696           15 :       if (cfg->tls->client_cert_optional &&
   10697            7 :           (tls_rv = ctls_ctx_peer_cert_optional(tls_ctx, true)) !=
   10698              :               ccol_success) {
   10699            0 :         ctls_ctx_release(tls_ctx);
   10700            0 :         retire_current_pools(raw);
   10701            0 :         ccol__mutex_lock(raw->mutex);
   10702            0 :         raw->lifecycle = CHTTPSVR_LC_IDLE;
   10703            0 :         ccol__mutex_unlock(raw->mutex);
   10704            0 :         chttpsvr_resolve_unpin(raw);
   10705            0 :         return tls_rv;
   10706              :       }
   10707           15 :       if (cfg->tls->ca_bundle_path &&
   10708           13 :           (tls_rv = ctls_ctx_trust(tls_ctx, cfg->tls->ca_bundle_path, NULL)) !=
   10709              :               ccol_success) {
   10710            2 :         ctls_ctx_release(tls_ctx);
   10711            2 :         retire_current_pools(raw);
   10712            2 :         ccol__mutex_lock(raw->mutex);
   10713            2 :         raw->lifecycle = CHTTPSVR_LC_IDLE;
   10714            2 :         ccol__mutex_unlock(raw->mutex);
   10715            2 :         chttpsvr_resolve_unpin(raw);
   10716            2 :         return tls_rv;
   10717              :       }
   10718           13 :       raw->tls_ctx = tls_ctx;
   10719              :     }
   10720              : 
   10721          317 :     if (!servers_register(raw)) {
   10722            1 :       SRV_ENGINE_LOG(clog_error,
   10723              :                      "chttpsvr_start: the server registry cannot grow");
   10724            1 :       if (raw->tls_ctx) {
   10725            0 :         ctls_ctx_release(raw->tls_ctx);
   10726            0 :         raw->tls_ctx = NULL;
   10727              :       }
   10728            1 :       retire_current_pools(raw);
   10729            1 :       ccol__mutex_lock(raw->mutex);
   10730            1 :       raw->lifecycle = CHTTPSVR_LC_IDLE;
   10731            1 :       ccol__mutex_unlock(raw->mutex);
   10732            1 :       chttpsvr_resolve_unpin(raw);
   10733            1 :       return ccol_not_enough_memory;
   10734              :     }
   10735              : 
   10736          316 :     bool need_acquire;
   10737          316 :     ccol__mutex_lock(raw->mutex);
   10738          316 :     need_acquire = !raw->contributed_to_engine;
   10739          316 :     if (need_acquire) raw->contributed_to_engine = true;
   10740          316 :     ccol__mutex_unlock(raw->mutex);
   10741              : 
   10742          316 :     if (need_acquire) {
   10743              : #ifdef RUNNING_UNIT_TESTS
   10744          298 :       engine_stopping_race_hook_wait_if_armed();
   10745              : #endif
   10746          298 :       bool currently_stopping = false;
   10747          298 :       uintptr_t engine_gen = 0;
   10748          298 :       ccol_retval engine_rc = engine_acquire(&currently_stopping, &engine_gen);
   10749          298 :       if (engine_rc == ccol_success) {
   10750          295 :         ccol__mutex_lock(raw->mutex);
   10751          295 :         raw->engine_gen = engine_gen;
   10752          295 :         ccol__mutex_unlock(raw->mutex);
   10753              :       }
   10754          298 :       if (currently_stopping) {
   10755            2 :         ccol__mutex_lock(raw->mutex);
   10756            2 :         raw->contributed_to_engine = false;
   10757            2 :         raw->lifecycle = CHTTPSVR_LC_IDLE;
   10758            2 :         ccol__mutex_unlock(raw->mutex);
   10759            2 :         servers_unregister(raw);
   10760            2 :         if (raw->tls_ctx) {
   10761            0 :           ctls_ctx_release(raw->tls_ctx);
   10762            0 :           raw->tls_ctx = NULL;
   10763              :         }
   10764            2 :         retire_current_pools(raw);
   10765            2 :         chttpsvr_resolve_unpin(raw);
   10766            2 :         ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   10767            2 :         ccol__mutex_lock(srv_engine_bundler.mutex);
   10768            4 :         while (srv_engine_bundler.stopping)
   10769            2 :           ccol__cond_var_wait(srv_engine_bundler.stopped_cv,
   10770              :                               srv_engine_bundler.mutex);
   10771            2 :         ccol__mutex_unlock(srv_engine_bundler.mutex);
   10772            2 :         raw = chttpsvr_resolve(h);
   10773            3 :         if (!raw) return ccol_invalid_args;
   10774            2 :         ccol__mutex_lock(raw->mutex);
   10775            2 :         continue;
   10776              :       }
   10777          296 :       if (engine_rc != ccol_success) {
   10778            2 :         clog_error(raw->cl,
   10779              :                    engine_rc == ccol_not_enough_memory
   10780              :                        ? "the shared reactor engine could not be created"
   10781              :                        : "the engine-stop watcher thread could not be "
   10782              :                          "started");
   10783            1 :         ccol__mutex_lock(raw->mutex);
   10784            1 :         raw->contributed_to_engine = false;
   10785            1 :         raw->lifecycle = CHTTPSVR_LC_IDLE;
   10786            1 :         ccol__mutex_unlock(raw->mutex);
   10787            1 :         servers_unregister(raw);
   10788            1 :         if (raw->tls_ctx) {
   10789            0 :           ctls_ctx_release(raw->tls_ctx);
   10790            0 :           raw->tls_ctx = NULL;
   10791              :         }
   10792            1 :         retire_current_pools(raw);
   10793            1 :         chttpsvr_resolve_unpin(raw);
   10794            1 :         return engine_rc;
   10795              :       }
   10796              :     }
   10797              : #ifdef RUNNING_UNIT_TESTS
   10798          313 :     start_race_hook_wait_if_armed();
   10799              : #endif
   10800          313 :     if (!idle_sweep_start_if_needed()) {
   10801            1 :       SRV_ENGINE_LOG(clog_error,
   10802              :                      "idle-timeout sweep thread could not be started");
   10803            1 :       if (raw->tls_ctx) {
   10804            0 :         ctls_ctx_release(raw->tls_ctx);
   10805            0 :         raw->tls_ctx = NULL;
   10806              :       }
   10807            1 :       retire_current_pools(raw);
   10808            1 :       chttpsvr_undo_start_registration(raw, need_acquire);
   10809            1 :       ccol__mutex_lock(raw->mutex);
   10810            1 :       raw->lifecycle = CHTTPSVR_LC_IDLE;
   10811            1 :       ccol__mutex_unlock(raw->mutex);
   10812            1 :       chttpsvr_resolve_unpin(raw);
   10813            1 :       return ccol_unexpected_failure;
   10814              :     }
   10815              : 
   10816          312 :     bool is_unix = false;
   10817          312 :     chttpsvr_unix_bind unix_bind;
   10818          312 :     int lfd =
   10819          624 :         make_listen_socket(cfg->host, cfg->port, cfg->enable_reuseport,
   10820          312 :                            cfg->ipv6_only, &is_unix, &unix_bind, raw->m_procs);
   10821          312 :     uint16_t bound_port = 0;
   10822          312 :     char bound_host[INET6_ADDRSTRLEN] = "";
   10823          598 :     if (lfd >= 0 && !is_unix &&
   10824          286 :         !listen_sockname(lfd, &bound_port, bound_host, sizeof(bound_host))) {
   10825            0 :       int e = errno;
   10826            0 :       close(lfd);
   10827            0 :       lfd = -1;
   10828            0 :       errno = e;
   10829              :     }
   10830            0 :     if (lfd < 0) {
   10831           11 :       int listen_errno = errno;
   10832              : #ifdef RUNNING_UNIT_TESTS
   10833           11 :       atomic_store(&g_last_listen_errno_for_tests, listen_errno);
   10834              : #endif
   10835           21 :       SRV_ENGINE_LOG(
   10836              :           clog_error, "listen socket setup failed host=%s port=%u errno=%d",
   10837              :           cfg->host ? cfg->host : "(any)", (unsigned)cfg->port, listen_errno);
   10838           11 :       if (raw->tls_ctx) {
   10839            1 :         ctls_ctx_release(raw->tls_ctx);
   10840            1 :         raw->tls_ctx = NULL;
   10841              :       }
   10842           11 :       retire_current_pools(raw);
   10843           11 :       chttpsvr_undo_start_registration(raw, need_acquire);
   10844           11 :       ccol__mutex_lock(raw->mutex);
   10845           11 :       raw->lifecycle = CHTTPSVR_LC_IDLE;
   10846           11 :       ccol__mutex_unlock(raw->mutex);
   10847           11 :       chttpsvr_resolve_unpin(raw);
   10848           11 :       return ccol_unexpected_failure;
   10849              :     }
   10850              : 
   10851          301 :     atomic_store(&raw->listen_fd, lfd);
   10852          301 :     atomic_store(&raw->is_unix_socket, is_unix);
   10853              : 
   10854          301 :     ccol__call_once(srv_parser_bundler.once, init_parser_settings);
   10855          301 :     char *reg_err = NULL;
   10856          301 :     atomic_fetch_add(&raw->lifetime_refs, 1);
   10857          602 :     ceventloop_reg lreg = ceventloop_add(
   10858          301 :         srv_engine_bundler.reactor, cselectable_fd(lfd, cselect_read),
   10859          301 :         (ceventloop_handlers){.on_readable = listener_on_readable,
   10860              :                               .on_removed = listener_on_removed},
   10861              :         raw, &reg_err);
   10862          301 :     if (!lreg) {
   10863            0 :       atomic_fetch_sub(&raw->lifetime_refs, 1);
   10864            0 :       atomic_store(&raw->listen_fd, -1);
   10865            0 :       close(lfd);
   10866            0 :       unix_bind_cleanup(&unix_bind, raw->m_procs);
   10867            0 :       if (raw->tls_ctx) {
   10868            0 :         ctls_ctx_release(raw->tls_ctx);
   10869            0 :         raw->tls_ctx = NULL;
   10870              :       }
   10871            0 :       retire_current_pools(raw);
   10872            0 :       chttpsvr_undo_start_registration(raw, need_acquire);
   10873            0 :       ccol__mutex_lock(raw->mutex);
   10874            0 :       raw->lifecycle = CHTTPSVR_LC_IDLE;
   10875            0 :       ccol__mutex_unlock(raw->mutex);
   10876            0 :       chttpsvr_resolve_unpin(raw);
   10877            0 :       return ccol_unexpected_failure;
   10878              :     }
   10879              : 
   10880          301 :     ccol__mutex_lock(raw->mutex);
   10881          301 :     raw->unix_bind = unix_bind;
   10882          301 :     raw->bound_port = bound_port;
   10883          301 :     memcpy(raw->bound_host, bound_host, sizeof(bound_host));
   10884          301 :     raw->listen_reg = lreg;
   10885          301 :     raw->lifecycle = CHTTPSVR_LC_RUNNING;
   10886          301 :     ccol__mutex_unlock(raw->mutex);
   10887              : 
   10888          301 :     chttpsvr_resolve_unpin(raw);
   10889          301 :     return ccol_success;
   10890              :   }
   10891              : }
   10892              : 
   10893              : // Stops a running server on an already resolved raw pointer: It closes the
   10894              : // listener and goes back to the idle state, and it leaves open connections and
   10895              : // pools alone. chttpsvr_stop() calls it after resolving a handle, and
   10896              : // quiesce_server_once calls it on a pointer it got from the server registry.
   10897              : // Under raw->mutex it moves lifecycle from RUNNING to STOPPING and takes
   10898              : // listen_fd, listen_reg and unix_bind out of the server; any other state makes
   10899              : // it return at once. After ceventloop_remove() it waits on resolve_cv until
   10900              : // listener_dispatch_pins is 0, because a dispatch already in flight may be
   10901              : // about to accept4() on the fd we close, and that number can be reused by an
   10902              : // unrelated open(). Only reactor threads hold that pin, so the wait can't
   10903              : // deadlock on itself. At the end it sets lifecycle to IDLE and broadcasts
   10904              : // resolve_cv, which wakes a chttpsvr_start() waiting for the stop to finish.
   10905          639 : static void chttpsvr_stop_internal(struct chttpserver *raw) {
   10906          639 :   ccol__mutex_lock(raw->mutex);
   10907          639 :   bool was_started = false;
   10908          639 :   switch (raw->lifecycle) {
   10909          300 :     case CHTTPSVR_LC_RUNNING:
   10910          300 :       was_started = true;
   10911          300 :       break;
   10912              :     case CHTTPSVR_LC_IDLE:
   10913              :     case CHTTPSVR_LC_STARTING:
   10914              :     case CHTTPSVR_LC_STOPPING:
   10915              :       was_started = false;
   10916              :       break;
   10917              :   }
   10918          639 :   int lfd = atomic_load(&raw->listen_fd);
   10919          639 :   ceventloop_reg lreg = raw->listen_reg;
   10920          639 :   chttpsvr_unix_bind unix_bind = raw->unix_bind;
   10921          639 :   if (was_started) {
   10922          300 :     raw->lifecycle = CHTTPSVR_LC_STOPPING;
   10923          300 :     atomic_store(&raw->listen_fd, -1);
   10924          300 :     raw->listen_reg = CEVENTLOOP_REG_NULL;
   10925          300 :     raw->unix_bind.path = NULL;
   10926          300 :     raw->unix_bind.dir_fd = -1;
   10927              :   }
   10928          639 :   ccol__mutex_unlock(raw->mutex);
   10929          639 :   if (!was_started) return;
   10930              : 
   10931              : #ifdef RUNNING_UNIT_TESTS
   10932          300 :   stop_race_hook_wait_if_armed();
   10933              : #endif
   10934              : 
   10935          300 :   if (lreg) ceventloop_remove(srv_engine_bundler.reactor, lreg);
   10936          300 :   ccol__mutex_lock(raw->mutex);
   10937          301 :   while (atomic_load(&raw->listener_dispatch_pins) > 0)
   10938            1 :     ccol__cond_var_wait(raw->resolve_cv, raw->mutex);
   10939          300 :   ccol__mutex_unlock(raw->mutex);
   10940          300 :   close(lfd);
   10941          300 :   unix_bind_cleanup(&unix_bind, raw->m_procs);
   10942              : 
   10943          300 :   ccol__mutex_lock(raw->mutex);
   10944          300 :   raw->lifecycle = CHTTPSVR_LC_IDLE;
   10945          300 :   ccol__cond_var_broadcast(raw->resolve_cv);
   10946          300 :   ccol__mutex_unlock(raw->mutex);
   10947              : }
   10948              : 
   10949              : // Stops listening on h; see chttpsvr_stop_internal. A handle that doesn't
   10950              : // resolve is ignored.
   10951           78 : void chttpsvr_stop(chttpsvr h) {
   10952           78 :   struct chttpserver *raw = chttpsvr_resolve(h);
   10953           78 :   if (!raw) return;
   10954           76 :   chttpsvr_stop_internal(raw);
   10955           76 :   chttpsvr_resolve_unpin(raw);
   10956              : }
   10957              : 
   10958              : // chttpsvr_bound_address() copies into a buffer of CHTTPSVR_BOUND_ADDRESS_SIZE
   10959              : // bytes, so a unix:// address and every numeric address must fit in it.
   10960              : _Static_assert(sizeof(CHTTPSVR_UNIX_PREFIX) - 1 +
   10961              :                        sizeof(((struct sockaddr_un *)0)->sun_path) <=
   10962              :                    CHTTPSVR_BOUND_ADDRESS_SIZE,
   10963              :                "CHTTPSVR_BOUND_ADDRESS_SIZE must hold a unix:// address");
   10964              : _Static_assert(INET6_ADDRSTRLEN <= CHTTPSVR_BOUND_ADDRESS_SIZE,
   10965              :                "CHTTPSVR_BOUND_ADDRESS_SIZE must hold a numeric address");
   10966              : 
   10967              : // Tells in *running_out whether h is in the RUNNING state, read under
   10968              : // raw->mutex, so a caller can check a server without starting or stopping it.
   10969              : // It gives ccol_invalid_args for a NULL running_out or a handle that doesn't
   10970              : // resolve.
   10971           19 : ccol_retval chttpsvr_is_running(chttpsvr h, bool *running_out) {
   10972           19 :   if (running_out) *running_out = false;
   10973           18 :   if (!running_out) return ccol_invalid_args;
   10974           18 :   struct chttpserver *raw = chttpsvr_resolve(h);
   10975           18 :   if (!raw) return ccol_invalid_args;
   10976           16 :   ccol__mutex_lock(raw->mutex);
   10977           16 :   *running_out = raw->lifecycle == CHTTPSVR_LC_RUNNING;
   10978           16 :   ccol__mutex_unlock(raw->mutex);
   10979           16 :   chttpsvr_resolve_unpin(raw);
   10980           16 :   return ccol_success;
   10981              : }
   10982              : 
   10983              : // Gives the port the listener of h is bound to, which a caller needs after
   10984              : // binding port 0. It reads lifecycle, is_unix_socket and bound_port under
   10985              : // raw->mutex and gives ccol_not_permitted when the server doesn't run or
   10986              : // listens on a unix socket, ccol_invalid_args for a bad handle or a NULL
   10987              : // port_out (*port_out is 0 then).
   10988           19 : ccol_retval chttpsvr_bound_port(chttpsvr h, uint16_t *port_out) {
   10989           19 :   if (port_out) *port_out = 0;
   10990           18 :   if (!port_out) return ccol_invalid_args;
   10991           18 :   struct chttpserver *raw = chttpsvr_resolve(h);
   10992           18 :   if (!raw) return ccol_invalid_args;
   10993           17 :   ccol_retval rv = ccol_not_permitted;
   10994           17 :   ccol__mutex_lock(raw->mutex);
   10995           17 :   if (raw->lifecycle == CHTTPSVR_LC_RUNNING &&
   10996           15 :       !atomic_load(&raw->is_unix_socket)) {
   10997           14 :     *port_out = raw->bound_port;
   10998           14 :     rv = ccol_success;
   10999              :   }
   11000           17 :   ccol__mutex_unlock(raw->mutex);
   11001           17 :   chttpsvr_resolve_unpin(raw);
   11002           17 :   return rv;
   11003              : }
   11004              : 
   11005              : // Writes the address the listener of h is bound to into buf ("unix://" plus the
   11006              : // path for a unix socket, the numeric host otherwise), so a caller can log or
   11007              : // advertise it. It reads the bound state under raw->mutex. Gives
   11008              : // ccol_not_permitted when the server doesn't run, ccol_msg_too_large when buf
   11009              : // is too short, and ccol_invalid_args for a bad handle or an empty buffer; buf
   11010              : // holds an empty string on every failure.
   11011            9 : ccol_retval chttpsvr_bound_address(chttpsvr h, char *buf, size_t buflen) {
   11012            9 :   if (buf && buflen) buf[0] = '\0';
   11013            9 :   if (!buf || !buflen) return ccol_invalid_args;
   11014            7 :   struct chttpserver *raw = chttpsvr_resolve(h);
   11015            7 :   if (!raw) return ccol_invalid_args;
   11016            6 :   ccol_retval rv = ccol_not_permitted;
   11017            6 :   ccol__mutex_lock(raw->mutex);
   11018            6 :   if (raw->lifecycle == CHTTPSVR_LC_RUNNING) {
   11019            5 :     const char *prefix = "";
   11020            5 :     const char *text = raw->bound_host;
   11021            5 :     if (atomic_load(&raw->is_unix_socket)) {
   11022            1 :       prefix = CHTTPSVR_UNIX_PREFIX;
   11023            1 :       text = raw->unix_bind.path;
   11024              :     }
   11025            5 :     size_t prefix_len = strlen(prefix);
   11026            5 :     size_t text_len = strlen(text);
   11027            5 :     if (prefix_len + text_len < buflen) {
   11028            4 :       memcpy(buf, prefix, prefix_len);
   11029            4 :       memcpy(buf + prefix_len, text, text_len + 1);
   11030            4 :       rv = ccol_success;
   11031              :     } else {
   11032              :       rv = ccol_msg_too_large;
   11033              :     }
   11034              :   }
   11035            6 :   ccol__mutex_unlock(raw->mutex);
   11036            6 :   chttpsvr_resolve_unpin(raw);
   11037            6 :   return rv;
   11038              : }
   11039              : 
   11040              : // Installs the logger that the shared engine logs through, or with CLOG_NULL
   11041              : // releases the installed one. A caller uses it to send engine diagnostics where
   11042              : // its own logs go. It works under srv_engine_bundler.mutex: A new logger is a
   11043              : // derived child of cl, stored in user_log, and a running engine switches to it
   11044              : // at once (the fallback logger it ran with is closed). A release is refused
   11045              : // with ccol_not_permitted while a reactor exists or a stop runs, because the
   11046              : // engine logs through it. A closed or stale cl gives the code of
   11047              : // clog__derive_checked and changes nothing.
   11048           13 : ccol_retval chttpsvr_set_engine_logger(clog cl) {
   11049           13 :   if (!cl) {
   11050            5 :     ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   11051            5 :     ccol__mutex_lock(srv_engine_bundler.mutex);
   11052            5 :     if (srv_engine_bundler.reactor || srv_engine_bundler.stopping) {
   11053            2 :       ccol__mutex_unlock(srv_engine_bundler.mutex);
   11054            2 :       return ccol_not_permitted;
   11055              :     }
   11056            3 :     clog old_user = srv_engine_bundler.user_log;
   11057            3 :     srv_engine_bundler.user_log = CLOG_NULL;
   11058            3 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
   11059            3 :     if (old_user) clog_close(old_user);
   11060            3 :     return ccol_success;
   11061              :   }
   11062            8 :   ccol_retval derive_rv = ccol_success;
   11063            8 :   clog derived = clog__derive_checked(cl, &derive_rv);
   11064            8 :   if (!derived) return derive_rv;
   11065            7 :   clog_set_field(derived, "component", "http-server-engine");
   11066            7 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   11067            7 :   ccol__mutex_lock(srv_engine_bundler.mutex);
   11068            7 :   clog old_user = srv_engine_bundler.user_log;
   11069            7 :   clog old_fallback = CLOG_NULL;
   11070            7 :   srv_engine_bundler.user_log = derived;
   11071            7 :   if (srv_engine_bundler.log) {
   11072            2 :     if (srv_engine_bundler.log != old_user)
   11073            0 :       old_fallback = srv_engine_bundler.log;
   11074            2 :     srv_engine_bundler.log = derived;
   11075              :   }
   11076            7 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
   11077            7 :   if (old_user) clog_close(old_user);
   11078            7 :   if (old_fallback) clog_close(old_fallback);
   11079              :   return ccol_success;
   11080              : }
   11081              : 
   11082              : // Sets the allocator the shared engine uses (NULL for the default), so a caller
   11083              : // can account for the engine's memory. It copies *mp into
   11084              : // srv_engine_bundler.mprocs_storage under the engine mutex. Gives
   11085              : // ccol_invalid_args for a procs struct with a NULL function and
   11086              : // ccol_not_permitted once a reactor exists.
   11087            5 : ccol_retval chttpsvr_set_engine_mem_mgmt_procs(ccol_memmgmt_procs *mp) {
   11088            5 :   if (mp && (!mp->malloc || !mp->free || !mp->calloc || !mp->realloc))
   11089              :     return ccol_invalid_args;
   11090            4 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   11091            4 :   ccol__mutex_lock(srv_engine_bundler.mutex);
   11092            4 :   if (srv_engine_bundler.reactor) {
   11093            2 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
   11094            2 :     return ccol_not_permitted;
   11095              :   }
   11096            2 :   if (mp) {
   11097            2 :     srv_engine_bundler.mprocs_storage = *mp;
   11098            2 :     srv_engine_bundler.mprocs = &srv_engine_bundler.mprocs_storage;
   11099              :   } else {
   11100            0 :     srv_engine_bundler.mprocs = NULL;
   11101              :   }
   11102            2 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
   11103            2 :   return ccol_success;
   11104              : }
   11105              : 
   11106              : // Sets how many reactor threads the next engine creates, so a caller can size
   11107              : // the reactor before the first start. It writes
   11108              : // srv_engine_bundler.num_reactor_threads under the engine mutex and gives
   11109              : // ccol_not_permitted once a reactor exists.
   11110            3 : ccol_retval chttpsvr_set_engine_num_reactor_threads(size_t num_threads) {
   11111            3 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   11112            3 :   ccol__mutex_lock(srv_engine_bundler.mutex);
   11113            3 :   if (srv_engine_bundler.reactor) {
   11114            2 :     ccol__mutex_unlock(srv_engine_bundler.mutex);
   11115            2 :     return ccol_not_permitted;
   11116              :   }
   11117            1 :   srv_engine_bundler.num_reactor_threads = num_threads;
   11118            1 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
   11119            1 :   return ccol_success;
   11120              : }
   11121              : 
   11122              : #ifdef RUNNING_UNIT_TESTS
   11123              : // Test hook: The reactor thread count that was wired into the reactor created
   11124              : // last, read under the engine mutex, so a test can check how a configured count
   11125              : // was resolved.
   11126            2 : size_t chttpsvr__engine_num_reactor_threads_for_tests(void) {
   11127            2 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   11128            2 :   ccol__mutex_lock(srv_engine_bundler.mutex);
   11129            2 :   size_t n = srv_engine_bundler.last_resolved_num_reactor_threads;
   11130            2 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
   11131            2 :   return n;
   11132              : }
   11133              : #endif
   11134              : 
   11135              : #ifdef RUNNING_UNIT_TESTS
   11136              : // Test hook: How many rejection responses ran on a reject pool thread in the
   11137              : // whole process. A test compares it before and after its own window, since
   11138              : // other tests can cause rejections too.
   11139           13 : size_t chttpsvr__reject_pool_task_count_for_tests(void) {
   11140           13 :   return atomic_load(&g_reject_task_run_count_for_tests);
   11141              : }
   11142              : #endif
   11143              : 
   11144              : #ifdef RUNNING_UNIT_TESTS
   11145              : // Test hook: Resolves h to its server under the slot table mutex without a pin,
   11146              : // so a test has no unpin to forget (a missed unpin would make every later
   11147              : // destroy of that server hang). It gives NULL in the same cases as
   11148              : // chttpsvr_resolve, a released table included.
   11149         3193 : struct chttpserver *chttpsvr__resolve_for_tests(chttpsvr h) {
   11150         3193 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   11151         3193 :   if (h == 0) return NULL;
   11152         3193 :   uint32_t idx = (uint32_t)(h >> 32);
   11153         3193 :   uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
   11154         3193 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   11155         3193 :   struct chttpserver *raw = NULL;
   11156         6386 :   if (chttpsvr_slot_table.slots &&
   11157         3193 :       idx < cvector_size(chttpsvr_slot_table.slots)) {
   11158         3193 :     chttpsvr_slot *slot =
   11159         3193 :         (chttpsvr_slot *)cvector_at(chttpsvr_slot_table.slots, idx);
   11160         3193 :     if (slot->in_use && slot->generation == gen) raw = slot->ptr;
   11161              :   }
   11162         3193 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   11163         3193 :   return raw;
   11164              : }
   11165              : 
   11166              : // Test hook: How many slots the handle table holds, so a test can check that a
   11167              : // create and destroy loop reuses freed slots instead of growing the table.
   11168            2 : size_t chttpsvr__slot_table_capacity_for_tests(void) {
   11169            2 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   11170            2 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   11171            4 :   size_t n =
   11172            2 :       chttpsvr_slot_table.slots ? cvector_size(chttpsvr_slot_table.slots) : 0;
   11173            2 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   11174            2 :   return n;
   11175              : }
   11176              : 
   11177              : // Test hook: How many servers are registered with the engine, read under
   11178              : // servers_bundler.mutex, so a test can see that a teardown or a fork fixup
   11179              : // really unregistered a server.
   11180          201 : size_t chttpsvr__servers_bundler_count_for_tests(void) {
   11181          201 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   11182          201 :   ccol__mutex_lock(servers_bundler.mutex);
   11183          201 :   size_t n = servers_bundler.count;
   11184          201 :   ccol__mutex_unlock(servers_bundler.mutex);
   11185          201 :   return n;
   11186              : }
   11187              : 
   11188              : // Test hook: The idle timeout in ms that chttpsvr_start() stored for h, so a
   11189              : // test can check the conversion from microseconds (a huge value must saturate
   11190              : // at UINT_MAX - 1, never wrap to 0, which means off) without waiting for it.
   11191              : // Gives 0 for an invalid handle.
   11192            4 : unsigned chttpsvr__idle_timeout_ms_for_tests(chttpsvr h) {
   11193            4 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11194            4 :   if (!raw) return 0;
   11195            4 :   return atomic_load(&raw->idle_timeout_ms);
   11196              : }
   11197              : 
   11198              : // Test hook: Copies into out every duration chttpsvr_start() resolved for h, in
   11199              : // ms, in the order the header lists, so a test can pin the conversion from
   11200              : // microseconds, the defaults and the form of CHTTPSVR_NO_DEADLINE without
   11201              : // waiting. Gives false for an invalid handle.
   11202            3 : bool chttpsvr__resolved_ms_for_tests(chttpsvr h, unsigned out[9]) {
   11203            3 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11204            3 :   if (!raw) return false;
   11205            3 :   out[0] = atomic_load(&raw->stream_read_timeout_ms);
   11206            3 :   out[1] = atomic_load(&raw->max_body_read_duration_ms);
   11207            3 :   out[2] = atomic_load(&raw->response_write_timeout_ms);
   11208            3 :   out[3] = atomic_load(&raw->max_response_write_duration_ms);
   11209            3 :   out[4] = atomic_load(&raw->max_header_read_duration_ms);
   11210            3 :   out[5] = atomic_load(&raw->idle_timeout_ms);
   11211            3 :   out[6] = atomic_load(&raw->rate_grace_ms);
   11212            3 :   out[7] = atomic_load(&raw->mem_wait_ms);
   11213            3 :   out[8] = atomic_load(&raw->stream_qtimeout_ms);
   11214            3 :   return true;
   11215              : }
   11216              : 
   11217              : // Test hook: The in_flight_requests count of h, read under raw->mutex like
   11218              : // everywhere else, so a test can wait until a request has really reached a
   11219              : // worker instead of sleeping. Gives -1 for an invalid handle.
   11220           47 : int chttpsvr__in_flight_requests_for_tests(chttpsvr h) {
   11221           47 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11222           47 :   if (!raw) return -1;
   11223           47 :   ccol__mutex_lock(raw->mutex);
   11224           47 :   int n = raw->in_flight_requests;
   11225           47 :   ccol__mutex_unlock(raw->mutex);
   11226           47 :   return n;
   11227              : }
   11228              : 
   11229              : // Test hook: Marks the calling thread as a worker of h through the worker key,
   11230              : // so a test in a forked child can reach the self-call guard of
   11231              : // chttpsvr_destroy() without a live reactor (fork() copies none of its
   11232              : // threads). There is no unmark, since the child ends right after. Does nothing
   11233              : // when h doesn't resolve.
   11234            2 : void chttpsvr__mark_self_as_worker_for_tests(chttpsvr h) {
   11235            2 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11236            2 :   if (raw && chttpsvr_worker_key_ensure()) chttpsvr_mark_worker_thread(raw);
   11237            2 : }
   11238              : 
   11239              : // Test hooks for the body-memory and streaming-queue state of h, so the
   11240              : // slow-client tests can see how much memory is reserved, who holds it, who
   11241              : // waits for it and what the streaming queue holds. Each reads its fields under
   11242              : // raw->wait_mutex (the pool fields under raw->mutex) and gives 0 or false for
   11243              : // an invalid handle. mem_holders also reports in *exempt_out whether one holder
   11244              : // runs past the limit under the progress rule.
   11245           51 : size_t chttpsvr__mem_in_use_for_tests(chttpsvr h) {
   11246           51 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11247           51 :   if (!raw) return 0;
   11248           51 :   ccol__mutex_lock(raw->wait_mutex);
   11249           51 :   size_t n = raw->mem_in_use;
   11250           51 :   ccol__mutex_unlock(raw->wait_mutex);
   11251           51 :   return n;
   11252              : }
   11253              : 
   11254           11 : size_t chttpsvr__mem_holders_for_tests(chttpsvr h, bool *exempt_out) {
   11255           11 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11256           11 :   if (exempt_out) *exempt_out = false;
   11257           11 :   if (!raw) return 0;
   11258           11 :   ccol__mutex_lock(raw->wait_mutex);
   11259           11 :   size_t n = raw->mem_holders;
   11260           11 :   if (exempt_out) *exempt_out = raw->mem_exempt_active;
   11261           11 :   ccol__mutex_unlock(raw->wait_mutex);
   11262           11 :   return n;
   11263              : }
   11264              : 
   11265              : // Test hook: For the request a buffered handler holds, the body memory
   11266              : // reservation of its connection (read under wait_mutex) and the capacity of its
   11267              : // body buffer, so a test can check that the reservation covers the buffer.
   11268            2 : void chttpsvr__req_body_memory_for_tests(chttpsvr_req *req, size_t *charged,
   11269              :                                          size_t *held) {
   11270            2 :   chttpsvr_conn *conn = req->conn;
   11271            2 :   ccol__mutex_lock(conn->srv->wait_mutex);
   11272            2 :   *charged = conn->mem_charged;
   11273            2 :   ccol__mutex_unlock(conn->srv->wait_mutex);
   11274            2 :   *held = conn->body.cap;
   11275            2 : }
   11276              : 
   11277           23 : size_t chttpsvr__mem_waiting_for_tests(chttpsvr h) {
   11278           23 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11279           23 :   if (!raw) return 0;
   11280           23 :   ccol__mutex_lock(raw->wait_mutex);
   11281           23 :   size_t n = raw->mem_waiting;
   11282           23 :   ccol__mutex_unlock(raw->wait_mutex);
   11283           23 :   return n;
   11284              : }
   11285              : 
   11286           18 : size_t chttpsvr__stream_queue_len_for_tests(chttpsvr h) {
   11287           18 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11288           18 :   if (!raw) return 0;
   11289           18 :   ccol__mutex_lock(raw->wait_mutex);
   11290           18 :   size_t n = raw->sq_len;
   11291           18 :   ccol__mutex_unlock(raw->wait_mutex);
   11292           18 :   return n;
   11293              : }
   11294              : 
   11295            3 : bool chttpsvr__stream_pool_created_for_tests(chttpsvr h) {
   11296            3 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11297            3 :   if (!raw) return false;
   11298            3 :   ccol__mutex_lock(raw->mutex);
   11299            3 :   bool created = raw->stream_pool != CTHRPOOL_NULL;
   11300            3 :   ccol__mutex_unlock(raw->mutex);
   11301            3 :   return created;
   11302              : }
   11303              : 
   11304              : // Test hook: How many tasks the worker pool, or the streaming pool, of h runs
   11305              : // right now, so a test can check that a parked connection holds no thread.
   11306           35 : size_t chttpsvr__pool_active_for_tests(chttpsvr h, bool streaming) {
   11307           35 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11308           35 :   if (!raw) return 0;
   11309           35 :   ccol__mutex_lock(raw->mutex);
   11310           35 :   cthrpool pool = streaming ? raw->stream_pool : raw->worker_pool;
   11311           35 :   ccol__mutex_unlock(raw->mutex);
   11312           35 :   return pool ? cthrpool_active_count(pool) : 0;
   11313              : }
   11314              : 
   11315              : // Test hook: How many connections of h are parked on a body (kind 1) or on a
   11316              : // response (kind 2), counted on the parked list under idle_mutex.
   11317         2944 : size_t chttpsvr__parked_count_for_tests(chttpsvr h, int kind) {
   11318         2944 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11319         2944 :   if (!raw) return 0;
   11320         2944 :   size_t n = 0;
   11321         2944 :   ccol__mutex_lock(raw->idle_mutex);
   11322         5863 :   for (chttpsvr_conn *c = raw->parked_head; c; c = c->parked_next)
   11323         2919 :     if (c->park == (uint8_t)kind) n++;
   11324         2944 :   ccol__mutex_unlock(raw->idle_mutex);
   11325         2944 :   return n;
   11326              : }
   11327              : 
   11328              : // Test hook: A rough measure of what the connections parked on a response or
   11329              : // lingering still hold (body capacity, one per header field, one per target,
   11330              : // query and parameter array, plus the response for a lingering one), counted
   11331              : // under idle_mutex. A test expects 0, because that state must be dropped when a
   11332              : // write parks or lingers.
   11333            3 : size_t chttpsvr__parked_request_state_for_tests(chttpsvr h) {
   11334            3 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11335            3 :   if (!raw) return 0;
   11336            3 :   size_t n = 0;
   11337            3 :   ccol__mutex_lock(raw->idle_mutex);
   11338            8 :   for (chttpsvr_conn *c = raw->parked_head; c; c = c->parked_next) {
   11339            5 :     if (c->park != CONN_PARK_WRITE && c->park != CONN_PARK_LINGER) continue;
   11340            5 :     n += c->body.cap + c->hdr_count + (c->path != NULL) +
   11341            5 :          (c->decoded_path != NULL) + (c->raw_query != NULL) +
   11342            5 :          (c->matched_param_values != NULL);
   11343            5 :     if (c->park == CONN_PARK_LINGER)
   11344            2 :       n += c->resp.body_cap + c->resp.header_count;
   11345              :   }
   11346            3 :   ccol__mutex_unlock(raw->idle_mutex);
   11347            3 :   return n;
   11348              : }
   11349              : 
   11350              : // Test hook: How many connections sit in the idle list of h, counted under
   11351              : // idle_mutex.
   11352           45 : size_t chttpsvr__idle_count_for_tests(chttpsvr h) {
   11353           45 :   struct chttpserver *raw = chttpsvr__resolve_for_tests(h);
   11354           45 :   if (!raw) return 0;
   11355           45 :   size_t n = 0;
   11356           45 :   ccol__mutex_lock(raw->idle_mutex);
   11357         6101 :   for (chttpsvr_conn *c = raw->idle_head; c; c = c->idle_next) n++;
   11358           45 :   ccol__mutex_unlock(raw->idle_mutex);
   11359           45 :   return n;
   11360              : }
   11361              : 
   11362              : // Test hook: Runs one sweep tick for h on the calling thread with the clock
   11363              : // read ahead_ms later, and gives how many connections it looked at. A test uses
   11364              : // it to expire an idle limit without sleeping. The sweep thread keeps running;
   11365              : // the claims of the lists make the two safe together.
   11366           17 : size_t chttpsvr__sweep_ahead_for_tests(chttpsvr h, unsigned ahead_ms) {
   11367           17 :   struct chttpserver *raw = chttpsvr_resolve(h);
   11368           17 :   if (!raw) return 0;
   11369           17 :   struct timespec now;
   11370           17 :   clock_gettime(CLOCK_MONOTONIC, &now);
   11371           17 :   timespec_add_ms(&now, ahead_ms);
   11372           17 :   size_t visited = sweep_server(raw, now);
   11373           17 :   chttpsvr_resolve_unpin(raw);
   11374           17 :   return visited;
   11375              : }
   11376              : 
   11377              : // Test hook: One sweep tick for h right away.
   11378           16 : size_t chttpsvr__sweep_now_for_tests(chttpsvr h) {
   11379           16 :   return chttpsvr__sweep_ahead_for_tests(h, 0);
   11380              : }
   11381              : #endif
   11382              : 
   11383              : // Asks the shared engine to stop every server; see engine_force_stop, which
   11384              : // keeps it async-signal-safe so a signal handler can call it.
   11385           24 : void chttpsvr_engine_stop(void) { engine_force_stop(); }
   11386              : 
   11387              : // Blocks until the shared engine has stopped and its reaper is joined, so
   11388              : // main() can wait for a stop that a signal asked for. A call from a handler or
   11389              : // middleware of any server is fatal: The engine stop drains every worker pool
   11390              : // with no timeout, and this call would keep that drain from finishing.
   11391           58 : void chttpsvr_engine_wait(void) {
   11392           58 :   if (chttpsvr_is_any_worker_call()) {
   11393            1 :     ccol__fatal_err(
   11394              :         "chttpsvr_engine_wait: called from within a request handler (or "
   11395              :         "middleware) running on some server's own worker pool; blocking "
   11396              :         "here would deadlock the shared engine's shutdown, which can "
   11397              :         "never finish draining this exact server's worker pool while "
   11398              :         "this in-flight request is what would eventually let it return. "
   11399              :         "Call chttpsvr_engine_wait() from a different thread instead.");
   11400              :   }
   11401           57 :   engine_wait_until_stopped();
   11402           57 : }
   11403              : 
   11404              : // Adds a buffered route for method and pattern to the root router of h, so fn
   11405              : // runs on the worker pool with the whole body in memory. It reads
   11406              : // raw->root_router, which needs no lock, because a concurrent
   11407              : // chttpsvr_subrouter() may realloc raw->routers. Gives ccol_invalid_args for a
   11408              : // NULL pattern or fn or a bad handle, else the code of router_add_route.
   11409          701 : ccol_retval chttpsvr_register_handler(chttpsvr h, chttp_method method,
   11410              :                                       const char *pattern,
   11411              :                                       chttpsvr_handler_fn fn, void *ctx) {
   11412          701 :   if (!pattern || !fn) return ccol_invalid_args;
   11413          699 :   struct chttpserver *raw = chttpsvr_resolve(h);
   11414          699 :   if (!raw) return ccol_invalid_args;
   11415          697 :   ccol_retval rv =
   11416          697 :       router_add_route(raw->root_router, method, pattern, fn, ctx, false);
   11417          697 :   chttpsvr_resolve_unpin(raw);
   11418          697 :   return rv;
   11419              : }
   11420              : 
   11421              : // Adds a streaming route to the root router of h, so fn runs on the streaming
   11422              : // pool and reads the body with chttpsvr_req_read(). Same arguments and codes as
   11423              : // chttpsvr_register_handler.
   11424          158 : ccol_retval chttpsvr_register_streaming_handler(chttpsvr h, chttp_method method,
   11425              :                                                 const char *pattern,
   11426              :                                                 chttpsvr_handler_fn fn,
   11427              :                                                 void *ctx) {
   11428          158 :   if (!pattern || !fn) return ccol_invalid_args;
   11429          156 :   struct chttpserver *raw = chttpsvr_resolve(h);
   11430          156 :   if (!raw) return ccol_invalid_args;
   11431          155 :   ccol_retval rv =
   11432          155 :       router_add_route(raw->root_router, method, pattern, fn, ctx, true);
   11433          155 :   chttpsvr_resolve_unpin(raw);
   11434          155 :   return rv;
   11435              : }
   11436              : 
   11437              : // Adds fn as a global middleware of h (on its root router), so it runs before
   11438              : // every handler of the server. Gives ccol_invalid_args for a NULL fn or a bad
   11439              : // handle, else the code of router_add_mw.
   11440        52272 : ccol_retval chttpsvr_use(chttpsvr h, chttpsvr_middleware_fn fn, void *ctx) {
   11441        52272 :   if (!fn) return ccol_invalid_args;
   11442        52271 :   struct chttpserver *raw = chttpsvr_resolve(h);
   11443        52271 :   if (!raw) return ccol_invalid_args;
   11444        52271 :   ccol_retval rv = router_add_mw(raw->root_router, fn, ctx);
   11445        52271 :   chttpsvr_resolve_unpin(raw);
   11446        52271 :   return rv;
   11447              : }
   11448              : 
   11449              : // Mounts a new sub-router of h at prefix and gives it, or NULL for a prefix
   11450              : // that doesn't start with '/' or holds "//", a bad handle, or a failed
   11451              : // allocation. A caller groups routes and middleware under a common path with
   11452              : // it.
   11453              : // Under the write side of raw->routes_lock it grows raw->routers when needed
   11454              : // and inserts the router among the sub-routers (index 1 up; the root at index 0
   11455              : // never moves) in descending order of prefix segment count, the order
   11456              : // find_route tries them in; equal counts keep registration order. It also
   11457              : // raises raw->max_prefix_seg_count. The router's owner field is set to h before
   11458              : // it's visible.
   11459          396 : chttpsvr_router *chttpsvr_subrouter(chttpsvr h, const char *prefix) {
   11460          396 :   if (!prefix || prefix[0] != '/') return NULL;
   11461          394 :   if (strstr(prefix, "//")) return NULL;
   11462              : 
   11463          392 :   struct chttpserver *raw = chttpsvr_resolve(h);
   11464          392 :   if (!raw) return NULL;
   11465              : 
   11466          391 :   chttpsvr_router *r = create_router(raw, prefix, raw->m_procs);
   11467          391 :   if (!r) {
   11468            1 :     chttpsvr_resolve_unpin(raw);
   11469            1 :     return NULL;
   11470              :   }
   11471          390 :   atomic_store(&r->owner, h);
   11472              : 
   11473          390 :   ccol__rw_lock_wrlock(raw->routes_lock);
   11474          390 :   if (raw->router_count >= raw->router_cap) {
   11475           78 :     if (raw->router_cap > (SIZE_MAX - 2) / 2 ||
   11476           78 :         raw->router_cap * 2 + 2 > SIZE_MAX / sizeof(chttpsvr_router *)) {
   11477            0 :       ccol__rw_lock_unlock(raw->routes_lock);
   11478            0 :       destroy_router(r, raw->m_procs);
   11479            0 :       chttpsvr_resolve_unpin(raw);
   11480            0 :       return NULL;
   11481              :     }
   11482           78 :     size_t nc = raw->router_cap * 2 + 2;
   11483           78 :     chttpsvr_router **nr = (chttpsvr_router **)ccol__mem_realloc(
   11484              :         raw->m_procs, raw->routers, nc * sizeof(chttpsvr_router *));
   11485           78 :     if (!nr) {
   11486            1 :       ccol__rw_lock_unlock(raw->routes_lock);
   11487            1 :       destroy_router(r, raw->m_procs);
   11488            1 :       chttpsvr_resolve_unpin(raw);
   11489            1 :       return NULL;
   11490              :     }
   11491           77 :     raw->routers = nr;
   11492           77 :     raw->router_cap = nc;
   11493              :   }
   11494              :   {
   11495          389 :     size_t pos = raw->router_count;
   11496          423 :     while (pos > 1 &&
   11497          350 :            raw->routers[pos - 1]->prefix_seg_count < r->prefix_seg_count) {
   11498           34 :       raw->routers[pos] = raw->routers[pos - 1];
   11499           34 :       pos--;
   11500              :     }
   11501          389 :     raw->routers[pos] = r;
   11502          389 :     raw->router_count++;
   11503              :   }
   11504          389 :   if (r->prefix_seg_count > raw->max_prefix_seg_count)
   11505           73 :     raw->max_prefix_seg_count = r->prefix_seg_count;
   11506          389 :   ccol__rw_lock_unlock(raw->routes_lock);
   11507          389 :   chttpsvr_resolve_unpin(raw);
   11508          389 :   return r;
   11509              : }
   11510              : 
   11511              : // Resolves and pins the server that owns router, for the chttpsvr_router_*
   11512              : // calls. The router's shell is never freed, so its owner field is always safe
   11513              : // to read. Gives NULL when the owner is gone; otherwise the caller must call
   11514              : // chttpsvr_resolve_unpin() once.
   11515          183 : static struct chttpserver *chttpsvr_router_reader_enter(
   11516              :     chttpsvr_router *router) {
   11517          183 :   chttpsvr owner = atomic_load(&router->owner);
   11518          183 :   return chttpsvr_resolve(owner);
   11519              : }
   11520              : 
   11521              : // Adds a buffered route to a sub-router while its server is pinned, so a
   11522              : // destroyed server is refused with ccol_invalid_args instead of a write into
   11523              : // freed memory.
   11524           97 : ccol_retval chttpsvr_router_register_handler(chttpsvr_router *router,
   11525              :                                              chttp_method method,
   11526              :                                              const char *pattern,
   11527              :                                              chttpsvr_handler_fn fn,
   11528              :                                              void *ctx) {
   11529           97 :   if (!router || !pattern || !fn) return ccol_invalid_args;
   11530           94 :   struct chttpserver *raw = chttpsvr_router_reader_enter(router);
   11531           94 :   if (!raw) return ccol_invalid_args;
   11532           93 :   ccol_retval rv = router_add_route(router, method, pattern, fn, ctx, false);
   11533           93 :   chttpsvr_resolve_unpin(raw);
   11534           93 :   return rv;
   11535              : }
   11536              : 
   11537              : // Adds a streaming route to a sub-router; same rules as
   11538              : // chttpsvr_router_register_handler.
   11539           12 : ccol_retval chttpsvr_router_register_streaming_handler(chttpsvr_router *router,
   11540              :                                                        chttp_method method,
   11541              :                                                        const char *pattern,
   11542              :                                                        chttpsvr_handler_fn fn,
   11543              :                                                        void *ctx) {
   11544           12 :   if (!router || !pattern || !fn) return ccol_invalid_args;
   11545            9 :   struct chttpserver *raw = chttpsvr_router_reader_enter(router);
   11546            9 :   if (!raw) return ccol_invalid_args;
   11547            9 :   ccol_retval rv = router_add_route(router, method, pattern, fn, ctx, true);
   11548            9 :   chttpsvr_resolve_unpin(raw);
   11549            9 :   return rv;
   11550              : }
   11551              : 
   11552              : // Adds a middleware to a sub-router, which runs for every route mounted under
   11553              : // its prefix; same rules as chttpsvr_router_register_handler.
   11554           81 : ccol_retval chttpsvr_router_use(chttpsvr_router *router,
   11555              :                                 chttpsvr_middleware_fn fn, void *ctx) {
   11556           81 :   if (!router || !fn) return ccol_invalid_args;
   11557           80 :   struct chttpserver *raw = chttpsvr_router_reader_enter(router);
   11558           80 :   if (!raw) return ccol_invalid_args;
   11559           80 :   ccol_retval rv = router_add_mw(router, fn, ctx);
   11560           80 :   chttpsvr_resolve_unpin(raw);
   11561           80 :   return rv;
   11562              : }
   11563              : 
   11564              : // Gives the method of the request (CHTTP_GET for a NULL req).
   11565           12 : chttp_method chttpsvr_req_method(const chttpsvr_req *req) {
   11566           12 :   if (!req) return CHTTP_GET;
   11567           11 :   return req->conn->method;
   11568              : }
   11569              : 
   11570              : // Gives the percent-decoded path of the request, which the router matched
   11571              : // against.
   11572           24 : const char *chttpsvr_req_path(const chttpsvr_req *req) {
   11573           24 :   if (!req) return NULL;
   11574           23 :   return req->conn->decoded_path;
   11575              : }
   11576              : 
   11577              : // The public digest buffer is filled by ctls, so both lengths must agree.
   11578              : _Static_assert(CHTTPSVR_PEER_CERT_SHA256_LEN == CTLS_SHA256_LEN,
   11579              :                "the public digest length must match the one of ctls");
   11580              : 
   11581              : // Tells whether the TLS client presented a certificate that the trust store
   11582              : // verified, so a handler can refuse anonymous clients when client certificates
   11583              : // are optional.
   11584            8 : bool chttpsvr_req_peer_cert_verified(const chttpsvr_req *req) {
   11585            8 :   if (!req) return false;
   11586           10 :   return req->conn->tls && ctls_conn_peer_cert_verified(req->conn->tls);
   11587              : }
   11588              : 
   11589              : // Gives the DER bytes of the verified client certificate and their length in
   11590              : // *len_out, or NULL (and 0) when there is none, so a handler can identify the
   11591              : // client. The bytes belong to the connection.
   11592            5 : const void *chttpsvr_req_peer_cert_der(const chttpsvr_req *req,
   11593              :                                        size_t *len_out) {
   11594            5 :   if (len_out) *len_out = 0;
   11595            5 :   if (!req || !req->conn->tls) return NULL;
   11596            2 :   return ctls_conn_peer_cert_der(req->conn->tls, len_out);
   11597              : }
   11598              : 
   11599              : // Writes the SHA-256 digest of the verified client certificate to out, so a
   11600              : // handler can pin a client by fingerprint. Gives ccol_key_not_found when there
   11601              : // is no verified certificate, ccol_not_enough_memory when the digest can't be
   11602              : // computed, ccol_invalid_args for NULL arguments; out is zeroed on failure.
   11603            5 : ccol_retval chttpsvr_req_peer_cert_sha256(
   11604              :     const chttpsvr_req *req, unsigned char out[CHTTPSVR_PEER_CERT_SHA256_LEN]) {
   11605            5 :   if (out) memset(out, 0, CHTTPSVR_PEER_CERT_SHA256_LEN);
   11606            5 :   if (!req || !out) return ccol_invalid_args;
   11607            3 :   if (!req->conn->tls || !ctls_conn_peer_cert_verified(req->conn->tls))
   11608            2 :     return ccol_key_not_found;
   11609            1 :   return ctls_conn_peer_cert_sha256(req->conn->tls, out)
   11610              :              ? ccol_success
   11611            1 :              : ccol_not_enough_memory;
   11612              : }
   11613              : 
   11614              : // Gives the subject name of the verified client certificate, or NULL, so a
   11615              : // handler can log or authorize by name.
   11616            4 : const char *chttpsvr_req_peer_cert_subject(const chttpsvr_req *req) {
   11617            4 :   if (!req || !req->conn->tls) return NULL;
   11618            2 :   return ctls_conn_peer_cert_subject(req->conn->tls);
   11619              : }
   11620              : 
   11621              : // Gives the value of the request header name, compared without letter case, or
   11622              : // NULL. When a name repeats, every occurrence is kept in arrival order and the
   11623              : // last one wins, so we scan backwards.
   11624           64 : const char *chttpsvr_req_header(const chttpsvr_req *req, const char *name) {
   11625           64 :   if (!req || !name) return NULL;
   11626           62 :   chttpsvr_conn *conn = req->conn;
   11627          149 :   for (size_t i = conn->hdr_count; i-- > 0;) {
   11628          222 :     if (ccol_ascii_casecmp(conn->hdr_names[i], name) == 0)
   11629           24 :       return conn->hdr_values[i];
   11630              :   }
   11631              :   return NULL;
   11632              : }
   11633              : 
   11634              : // Gives the body of a buffered route and its length in *len_out, so a handler
   11635              : // can read it as one stable buffer. A streaming route gets NULL and 0: Its
   11636              : // conn->body is a live read cursor that chttpsvr_req_read() drains, and its
   11637              : // pointer and length would mix delivered and undelivered bytes. conn and the
   11638              : // matched route are checked as a defence, though documented use never gives
   11639              : // NULL there.
   11640           83 : const void *chttpsvr_req_body(const chttpsvr_req *req, size_t *len_out) {
   11641           83 :   if (!req) {
   11642            2 :     if (len_out) *len_out = 0;
   11643            2 :     return NULL;
   11644              :   }
   11645           81 :   chttpsvr_conn *conn = req->conn;
   11646           81 :   if (!conn || !conn->matched_route || conn->matched_route->is_streaming) {
   11647            3 :     if (len_out) *len_out = 0;
   11648            3 :     return NULL;
   11649              :   }
   11650           78 :   if (len_out) *len_out = conn->body.len;
   11651           78 :   return conn->body.buf;
   11652              : }
   11653              : 
   11654              : // Gives the value of the named path parameter of the matched route (":name" in
   11655              : // its pattern), or NULL, so a handler can read the parts of the path it routed
   11656              : // on.
   11657           68 : const char *chttpsvr_req_param(const chttpsvr_req *req, const char *name) {
   11658           68 :   if (!req || !name) return NULL;
   11659           66 :   chttpsvr_conn *conn = req->conn;
   11660           66 :   if (!conn || !conn->matched_route) return NULL;
   11661           66 :   int count = conn->matched_route->param_count;
   11662           96 :   for (int i = 0; i < count; i++) {
   11663           96 :     if (req->param_names[i] && strcmp(req->param_names[i], name) == 0) {
   11664           66 :       return conn->matched_param_values[i];
   11665              :     }
   11666              :   }
   11667              :   return NULL;
   11668              : }
   11669              : 
   11670              : // Gives a NULL-terminated array of every value of the query key key and their
   11671              : // number in *count_out, or NULL with 0 when the key is absent or memory runs
   11672              : // out. A handler uses it for a key that may repeat. The query is parsed once
   11673              : // per request (ensure_qparams); the array lives in req->qresult, which the next
   11674              : // call reuses. A failed growth sets req->qresult_oom, which
   11675              : // chttpsvr_req_query_oom() reports.
   11676          105 : const char **chttpsvr_req_query(chttpsvr_req *req, const char *key,
   11677              :                                 size_t *count_out) {
   11678          105 :   if (!req || !key) {
   11679            3 :     if (count_out) *count_out = 0;
   11680            3 :     return NULL;
   11681              :   }
   11682              : 
   11683          102 :   chttpsvr_qparams *qp = ensure_qparams(req);
   11684          102 :   if (!qp) {
   11685            0 :     if (count_out) *count_out = 0;
   11686            0 :     return NULL;
   11687              :   }
   11688              : 
   11689              :   size_t n = 0;
   11690          604 :   for (size_t i = 0; i < qp->count; i++) {
   11691          502 :     if (strcmp(qp->keys[i], key) == 0) n++;
   11692              :   }
   11693          102 :   if (n == 0) {
   11694           48 :     if (count_out) *count_out = 0;
   11695           48 :     return NULL;
   11696              :   }
   11697              : 
   11698           54 :   if (n + 1 > req->qresult_cap) {
   11699           26 :     const char **nr = (const char **)ccol__mem_realloc(
   11700              :         req->m_procs, req->qresult, (n + 1) * sizeof(char *));
   11701           26 :     if (!nr) {
   11702            2 :       req->qresult_oom = true;
   11703            2 :       if (count_out) *count_out = 0;
   11704            2 :       return NULL;
   11705              :     }
   11706           24 :     req->qresult = nr;
   11707           24 :     req->qresult_cap = n + 1;
   11708              :   }
   11709              :   size_t idx = 0;
   11710          357 :   for (size_t i = 0; i < qp->count; i++) {
   11711          305 :     if (strcmp(qp->keys[i], key) == 0) req->qresult[idx++] = qp->values[i];
   11712              :   }
   11713           52 :   req->qresult[idx] = NULL;
   11714           52 :   if (count_out) *count_out = n;
   11715              :   return req->qresult;
   11716              : }
   11717              : 
   11718              : // Gives in *val_out the one value of the query key key, for a handler that
   11719              : // expects a key at most once. Gives ccol_key_not_found when it's absent,
   11720              : // ccol_key_already_present when it repeats, ccol_not_enough_memory when the
   11721              : // query couldn't be parsed, ccol_invalid_args for NULL arguments; *val_out is
   11722              : // NULL on every failure.
   11723           93 : ccol_retval chttpsvr_req_query_one(chttpsvr_req *req, const char *key,
   11724              :                                    const char **val_out) {
   11725           93 :   if (!req || !key) {
   11726            4 :     if (val_out) *val_out = NULL;
   11727            4 :     return ccol_invalid_args;
   11728              :   }
   11729              : 
   11730           89 :   chttpsvr_qparams *qp = ensure_qparams(req);
   11731           89 :   if (!qp) {
   11732            0 :     if (val_out) *val_out = NULL;
   11733            0 :     return ccol_not_enough_memory;
   11734              :   }
   11735           89 :   if (req->qparams_parse_oom) {
   11736           15 :     if (val_out) *val_out = NULL;
   11737           15 :     return ccol_not_enough_memory;
   11738              :   }
   11739              : 
   11740              :   size_t n = 0;
   11741              :   const char *found_val = NULL;
   11742          201 :   for (size_t i = 0; i < qp->count; i++) {
   11743          127 :     if (strcmp(qp->keys[i], key) == 0) {
   11744           73 :       n++;
   11745           73 :       found_val = qp->values[i];
   11746              :     }
   11747              :   }
   11748           74 :   if (n == 0) {
   11749            2 :     if (val_out) *val_out = NULL;
   11750            2 :     return ccol_key_not_found;
   11751              :   }
   11752           72 :   if (n > 1) {
   11753            1 :     if (val_out) *val_out = NULL;
   11754            1 :     return ccol_key_already_present;
   11755              :   }
   11756           71 :   if (val_out) *val_out = found_val;
   11757              :   return ccol_success;
   11758              : }
   11759              : 
   11760              : // Gives the query string as it arrived, undecoded, or NULL when the target had
   11761              : // none.
   11762            3 : const char *chttpsvr_req_raw_query(const chttpsvr_req *req) {
   11763            3 :   if (!req) return NULL;
   11764            2 :   return req->conn->raw_query;
   11765              : }
   11766              : 
   11767              : // Tells whether a query lookup of this request ran out of memory, so a handler
   11768              : // can tell "absent" from "not enough memory" after a NULL from
   11769              : // chttpsvr_req_query().
   11770            4 : bool chttpsvr_req_query_oom(const chttpsvr_req *req) {
   11771            4 :   if (!req) return false;
   11772            3 :   return req->qresult_oom || req->qparams_parse_oom;
   11773              : }
   11774              : 
   11775              : // Starting capacity of the overflow block of chttpsvr_req_set_context(), which
   11776              : // doubles from there.
   11777              : #define CHTTPSVR_CTX_MORE_FIRST_CAP 4u
   11778              : 
   11779              : // Stores value under the address key in the request, replacing the value of a
   11780              : // key already there, so middleware can pass data to the handler. The first pair
   11781              : // lives inside the request with no allocation; later pairs go into
   11782              : // req->ctx_more, a doubling block from the server's allocator that the request
   11783              : // scratch frees. Gives ccol_invalid_args for NULL arguments and
   11784              : // ccol_not_enough_memory when the block can't grow.
   11785           33 : ccol_retval chttpsvr_req_set_context(chttpsvr_req *req, const void *key,
   11786              :                                      void *value) {
   11787           33 :   if (!req || !key) return ccol_invalid_args;
   11788           31 :   if (!req->ctx_first.key || req->ctx_first.key == key) {
   11789            8 :     req->ctx_first.key = key;
   11790            8 :     req->ctx_first.value = value;
   11791            8 :     return ccol_success;
   11792              :   }
   11793           23 :   chttpsvr_ctx_more *more = req->ctx_more;
   11794           23 :   size_t count = more ? more->count : 0;
   11795           67 :   for (size_t i = 0; i < count; i++) {
   11796           47 :     if (more->pairs[i].key == key) {
   11797            3 :       more->pairs[i].value = value;
   11798            3 :       return ccol_success;
   11799              :     }
   11800              :   }
   11801           20 :   if (!more || count == more->cap) {
   11802            8 :     size_t cap = more ? more->cap : 0;
   11803            8 :     if (cap > (SIZE_MAX - sizeof(chttpsvr_ctx_more)) /
   11804              :                   (2 * sizeof(chttpsvr_ctx_pair)))
   11805              :       return ccol_not_enough_memory;
   11806            8 :     size_t new_cap = cap ? cap * 2 : CHTTPSVR_CTX_MORE_FIRST_CAP;
   11807            8 :     chttpsvr_ctx_more *grown = (chttpsvr_ctx_more *)ccol__mem_realloc(
   11808              :         req->m_procs, more,
   11809              :         sizeof(chttpsvr_ctx_more) + new_cap * sizeof(chttpsvr_ctx_pair));
   11810            8 :     if (!grown) return ccol_not_enough_memory;
   11811            7 :     if (!more) grown->count = 0;
   11812            7 :     grown->cap = new_cap;
   11813            7 :     req->ctx_more = more = grown;
   11814              :   }
   11815           19 :   more->pairs[more->count].key = key;
   11816           19 :   more->pairs[more->count].value = value;
   11817           19 :   more->count++;
   11818           19 :   return ccol_success;
   11819              : }
   11820              : 
   11821              : // Gives the value stored under key by chttpsvr_req_set_context(), or NULL.
   11822           33 : void *chttpsvr_req_context(const chttpsvr_req *req, const void *key) {
   11823           33 :   if (!req || !key) return NULL;
   11824           31 :   if (req->ctx_first.key == key) return req->ctx_first.value;
   11825           26 :   const chttpsvr_ctx_more *more = req->ctx_more;
   11826           26 :   if (!more) return NULL;
   11827           57 :   for (size_t i = 0; i < more->count; i++)
   11828           52 :     if (more->pairs[i].key == key) return more->pairs[i].value;
   11829              :   return NULL;
   11830              : }
   11831              : 
   11832              : // Sets the status code of the response; send_response turns a code outside 200
   11833              : // to 999 into 500.
   11834          120 : void chttpsvr_resp_set_status(chttpsvr_resp *resp, int status_code) {
   11835          120 :   if (resp) resp->status_code = status_code;
   11836          120 : }
   11837              : 
   11838              : // Tells whether value is a Content-Length a response may carry: One or more
   11839              : // ASCII digits (RFC 9110 section 8.6) whose number fits a signed 64-bit
   11840              : // integer, the widest length that Go, curl and our own parser accept.
   11841           29 : static bool resp_content_length_valid(const char *value) {
   11842           29 :   static const char max_cl[] = "9223372036854775807";
   11843           29 :   size_t n = 0;
   11844          187 :   for (const char *p = value; *p; p++, n++)
   11845          170 :     if (*p < '0' || *p > '9') return false;
   11846           17 :   if (n == 0) return false;
   11847           63 :   while (n > 1 && *value == '0') {
   11848           48 :     value++;
   11849           48 :     n--;
   11850              :   }
   11851           30 :   return n < sizeof(max_cl) - 1 ||
   11852            4 :          (n == sizeof(max_cl) - 1 && strcmp(value, max_cl) <= 0);
   11853              : }
   11854              : 
   11855              : // Checks a response header before either setter stores it, because
   11856              : // send_response writes name and value to the wire as they are. The name must be
   11857              : // a non-empty token of tchar bytes (the classifier the parser uses), so it
   11858              : // can't build a malformed line. The value may hold no control byte other than
   11859              : // HTAB and no DEL, which stops CRLF injection when a handler reflects request
   11860              : // data. Transfer-Encoding is refused, since the server never transfer-codes a
   11861              : // body and the field would contradict its Content-Length, and a Content-Length
   11862              : // must pass resp_content_length_valid. Gives ccol_success or ccol_invalid_args.
   11863          567 : static ccol_retval resp_header_validate(const char *name, const char *value) {
   11864          567 :   if (!*name) return ccol_invalid_args;
   11865         6032 :   for (const char *p = name; *p; p++) {
   11866         5474 :     if (!chttp1_is_tchar((unsigned char)*p)) return ccol_invalid_args;
   11867              :   }
   11868       142854 :   for (const unsigned char *p = (const unsigned char *)value; *p; p++) {
   11869       142306 :     if ((*p < 0x20 && *p != '\t') || *p == 0x7F) return ccol_invalid_args;
   11870              :   }
   11871          548 :   if (ccol_ascii_casecmp(name, "transfer-encoding") == 0)
   11872              :     return ccol_invalid_args;
   11873          572 :   if (ccol_ascii_casecmp(name, "content-length") == 0 &&
   11874           29 :       !resp_content_length_valid(value))
   11875              :     return ccol_invalid_args;
   11876              :   return ccol_success;
   11877              : }
   11878              : 
   11879              : // Tells whether a response carries at most one field of this name:
   11880              : // send_response decides Connection itself and reads a handler's Content-Length
   11881              : // and Date as single values, so chttpsvr_resp_add_header replaces these instead
   11882              : // of appending.
   11883           47 : static bool resp_header_is_singleton(const char *name) {
   11884           47 :   return ccol_ascii_casecmp(name, "connection") == 0 ||
   11885           94 :          ccol_ascii_casecmp(name, "content-length") == 0 ||
   11886           42 :          ccol_ascii_casecmp(name, "date") == 0;
   11887              : }
   11888              : 
   11889              : // Appends one field line with copies of name and value, growing resp->headers
   11890              : // when needed, for chttpsvr_resp_add_header and for a first set. The caller has
   11891              : // validated both. Gives ccol_not_enough_memory and changes nothing when a
   11892              : // growth or a copy fails.
   11893          488 : static ccol_retval resp_header_append(chttpsvr_resp *resp, const char *name,
   11894              :                                       const char *value) {
   11895          488 :   ccol_memmgmt_procs *mp = resp->m_procs;
   11896          488 :   if (resp->header_count >= resp->header_cap) {
   11897          339 :     if (resp->header_cap > (SIZE_MAX - 8) / 2) return ccol_not_enough_memory;
   11898          339 :     size_t new_cap = resp->header_cap * 2 + 8;
   11899          339 :     if (new_cap > SIZE_MAX / sizeof(resp_header)) return ccol_not_enough_memory;
   11900          339 :     resp_header *nh = (resp_header *)ccol__mem_realloc(
   11901              :         mp, resp->headers, new_cap * sizeof(resp_header));
   11902          339 :     if (!nh) return ccol_not_enough_memory;
   11903          338 :     resp->headers = nh;
   11904          338 :     resp->header_cap = new_cap;
   11905              :   }
   11906              : 
   11907          487 :   char *n_name = ccol_strdup(mp, name);
   11908          487 :   char *n_val = ccol_strdup(mp, value);
   11909          487 :   if (!n_name || !n_val) {
   11910            6 :     ccol__mem_free(mp, n_name);
   11911            6 :     ccol__mem_free(mp, n_val);
   11912            6 :     return ccol_not_enough_memory;
   11913              :   }
   11914          481 :   resp->headers[resp->header_count].name = n_name;
   11915          481 :   resp->headers[resp->header_count].value = n_val;
   11916          481 :   resp->header_count++;
   11917          481 :   return ccol_success;
   11918              : }
   11919              : 
   11920              : // Makes value the single value of name, for chttpsvr_resp_set_header and the
   11921              : // singleton fields. The first field of that name keeps its place and the letter
   11922              : // case of its name, later ones are dropped, and the other fields keep their
   11923              : // order. The new value is copied first, so a failed allocation leaves every
   11924              : // field as it was. The caller has validated name and value.
   11925          489 : static ccol_retval resp_header_replace(chttpsvr_resp *resp, const char *name,
   11926              :                                        const char *value) {
   11927          489 :   ccol_memmgmt_procs *mp = resp->m_procs;
   11928          489 :   size_t first = resp->header_count;
   11929          855 :   for (size_t i = 0; i < resp->header_count; i++) {
   11930          810 :     if (ccol_ascii_casecmp(resp->headers[i].name, name) == 0) {
   11931              :       first = i;
   11932              :       break;
   11933              :     }
   11934              :   }
   11935          489 :   if (first == resp->header_count) return resp_header_append(resp, name, value);
   11936              : 
   11937           39 :   char *new_val = ccol_strdup(mp, value);
   11938            1 :   if (!new_val) return ccol_not_enough_memory;
   11939           38 :   ccol__mem_free(mp, resp->headers[first].value);
   11940           38 :   resp->headers[first].value = new_val;
   11941           38 :   size_t kept = first + 1;
   11942           44 :   for (size_t i = first + 1; i < resp->header_count; i++) {
   11943           12 :     if (ccol_ascii_casecmp(resp->headers[i].name, name) == 0) {
   11944            4 :       ccol__mem_free(mp, resp->headers[i].name);
   11945            4 :       ccol__mem_free(mp, resp->headers[i].value);
   11946            4 :       continue;
   11947              :     }
   11948            2 :     resp->headers[kept++] = resp->headers[i];
   11949              :   }
   11950           38 :   resp->header_count = kept;
   11951           38 :   return ccol_success;
   11952              : }
   11953              : 
   11954              : // Validates name and value and makes value the only field of that name in the
   11955              : // response, replacing earlier ones. Gives ccol_invalid_args for NULL or refused
   11956              : // arguments and ccol_not_enough_memory when a copy fails.
   11957          506 : ccol_retval chttpsvr_resp_set_header(chttpsvr_resp *resp, const char *name,
   11958              :                                      const char *value) {
   11959          506 :   if (!resp || !name || !value) return ccol_invalid_args;
   11960          502 :   ccol_retval rv = resp_header_validate(name, value);
   11961          502 :   if (rv != ccol_success) return rv;
   11962          480 :   return resp_header_replace(resp, name, value);
   11963              : }
   11964              : 
   11965              : // Validates name and value and appends one more field line, for a field that
   11966              : // may repeat such as Set-Cookie. Connection, Content-Length and Date stay
   11967              : // single-valued, so for them it replaces. Same codes as
   11968              : // chttpsvr_resp_set_header.
   11969           71 : ccol_retval chttpsvr_resp_add_header(chttpsvr_resp *resp, const char *name,
   11970              :                                      const char *value) {
   11971           71 :   if (!resp || !name || !value) return ccol_invalid_args;
   11972           65 :   ccol_retval rv = resp_header_validate(name, value);
   11973           65 :   if (rv != ccol_success) return rv;
   11974           47 :   if (resp_header_is_singleton(name))
   11975            9 :     return resp_header_replace(resp, name, value);
   11976           38 :   return resp_header_append(resp, name, value);
   11977              : }
   11978              : 
   11979              : // Appends len bytes of data to the response body, which send_response writes
   11980              : // after the handler returns. The buffer grows to at least twice its size plus
   11981              : // 256 bytes, so many small writes stay cheap. Gives ccol_invalid_args for a
   11982              : // NULL resp or NULL data with a non-zero len, and ccol_not_enough_memory when
   11983              : // the growth fails or would overflow; the body is unchanged then.
   11984         3037 : ccol_retval chttpsvr_resp_write(chttpsvr_resp *resp, const void *data,
   11985              :                                 size_t len) {
   11986         3037 :   if (!resp || (!data && len > 0)) return ccol_invalid_args;
   11987         3036 :   if (len == 0) return ccol_success;
   11988              : 
   11989         3035 :   ccol_memmgmt_procs *mp = resp->m_procs;
   11990              : 
   11991         3035 :   if (len > resp->body_cap - resp->body_len) {
   11992         1044 :     if (len > SIZE_MAX - resp->body_len) return ccol_not_enough_memory;
   11993         1044 :     size_t min_cap = resp->body_len + len;
   11994         1044 :     size_t new_cap = min_cap;
   11995         1044 :     if (resp->body_cap <= (SIZE_MAX - 256) / 2) {
   11996         1044 :       size_t doubled = resp->body_cap * 2 + 256;
   11997         1044 :       if (doubled > new_cap) new_cap = doubled;
   11998              :     }
   11999         1044 :     char *nb = (char *)ccol__mem_realloc(mp, resp->body, new_cap);
   12000         1044 :     if (!nb) return ccol_not_enough_memory;
   12001         1043 :     resp->body = nb;
   12002         1043 :     resp->body_cap = new_cap;
   12003              :   }
   12004         3034 :   memcpy(resp->body + resp->body_len, data, len);
   12005         3034 :   resp->body_len += len;
   12006         3034 :   return ccol_success;
   12007              : }
   12008              : 
   12009              : // Appends the NUL-terminated str to the response body; see chttpsvr_resp_write.
   12010          785 : ccol_retval chttpsvr_resp_write_str(chttpsvr_resp *resp, const char *str) {
   12011          785 :   if (!resp || !str) return ccol_invalid_args;
   12012          783 :   return chttpsvr_resp_write(resp, str, strlen(str));
   12013              : }
   12014              : 
   12015              : // Formats with printf rules and appends the result to the response body. A
   12016              : // result under 256 bytes is formatted on the stack; a longer one is formatted
   12017              : // again into a heap buffer from the response's allocator. Gives
   12018              : // ccol_invalid_args for NULL arguments or a format error,
   12019              : // ccol_not_enough_memory when an allocation fails.
   12020          147 : ccol_retval chttpsvr_resp_printf(chttpsvr_resp *resp, const char *fmt, ...) {
   12021          147 :   if (!resp || !fmt) return ccol_invalid_args;
   12022              : 
   12023          147 :   ccol_memmgmt_procs *mp = resp->m_procs;
   12024          147 :   char stack_buf[256];
   12025          147 :   va_list ap, ap2;
   12026          147 :   va_start(ap, fmt);
   12027          147 :   va_copy(ap2, ap);
   12028              : 
   12029          147 :   int n = vsnprintf(stack_buf, sizeof(stack_buf), fmt, ap);
   12030          147 :   va_end(ap);
   12031          147 :   if (n < 0) {
   12032            0 :     va_end(ap2);
   12033            0 :     return ccol_invalid_args;
   12034              :   }
   12035              : 
   12036          147 :   if ((size_t)n < sizeof(stack_buf)) {
   12037          118 :     va_end(ap2);
   12038          118 :     return chttpsvr_resp_write(resp, stack_buf, (size_t)n);
   12039              :   }
   12040              : 
   12041           29 :   char *heap_buf = (char *)ccol__mem_alloc(mp, (size_t)n + 1);
   12042           29 :   if (!heap_buf) {
   12043            2 :     va_end(ap2);
   12044            2 :     return ccol_not_enough_memory;
   12045              :   }
   12046           27 :   int n2 = vsnprintf(heap_buf, (size_t)n + 1, fmt, ap2);
   12047           27 :   va_end(ap2);
   12048           27 :   if (n2 < 0) {
   12049            0 :     ccol__mem_free(mp, heap_buf);
   12050            0 :     return ccol_invalid_args;
   12051              :   }
   12052           27 :   ccol_retval rv = chttpsvr_resp_write(resp, heap_buf, (size_t)n2);
   12053           27 :   ccol__mem_free(mp, heap_buf);
   12054              :   return rv;
   12055              : }
   12056              : 
   12057              : // Appends len bytes of JSON text to the body and sets Content-Type to
   12058              : // application/json, so a handler that answers JSON needs one call. Gives
   12059              : // ccol_invalid_args for NULL arguments or a len of 0, else the code of the
   12060              : // write or the header set.
   12061            3 : ccol_retval chttpsvr_resp_write_json(chttpsvr_resp *resp, const char *json,
   12062              :                                      size_t len) {
   12063            3 :   if (!resp || !json || len == 0) return ccol_invalid_args;
   12064            1 :   ccol_retval rv = chttpsvr_resp_write(resp, json, len);
   12065            1 :   if (rv != ccol_success) return rv;
   12066            1 :   return chttpsvr_resp_set_header(resp, "content-type", "application/json");
   12067              : }
   12068              : 
   12069              : #ifdef RUNNING_UNIT_TESTS
   12070              : // Test hook: Runs the exit-time destructors of the module now (router shells,
   12071              : // slot table, stop watcher), in a forked child, so the test can then destroy a
   12072              : // server as a late application destructor would.
   12073            1 : void chttpsvr__run_exit_cleanup_for_tests(void) {
   12074            1 :   cleanup_chttpsvr_router_shells();
   12075            1 :   cleanup_chttpsvr_slot_table();
   12076            1 :   cleanup_engine_stop_watcher();
   12077            1 : }
   12078              : 
   12079              : // Test hook: How many router shells the registry holds and whether its array is
   12080              : // allocated, read under the registry mutex, so a test can see what a destroy
   12081              : // and the exit cleanup free.
   12082            5 : void chttpsvr__router_shell_registry_state_for_tests(size_t *count,
   12083              :                                                      bool *array) {
   12084            5 :   ccol__call_once(chttpsvr_router_shell_registry.once,
   12085              :                   chttpsvr_router_shell_registry_init_globals);
   12086            5 :   ccol__mutex_lock(chttpsvr_router_shell_registry.mutex);
   12087            5 :   *count = chttpsvr_router_shell_registry.count;
   12088            5 :   *array = chttpsvr_router_shell_registry.shells != NULL;
   12089            5 :   ccol__mutex_unlock(chttpsvr_router_shell_registry.mutex);
   12090            5 : }
   12091              : 
   12092              : // Test hook: true once the arrays of the slot table have been released, read
   12093              : // under its mutex.
   12094            2 : bool chttpsvr__slot_table_released_for_tests(void) {
   12095            2 :   ccol__call_once(chttpsvr_slot_table.once, chttpsvr_slot_table_init_globals);
   12096            2 :   ccol__mutex_lock(chttpsvr_slot_table.mutex);
   12097            2 :   bool released = chttpsvr_slot_table.slots == NULL;
   12098            2 :   ccol__mutex_unlock(chttpsvr_slot_table.mutex);
   12099            2 :   return released;
   12100              : }
   12101              : 
   12102              : // Test hook: true while a logger of chttpsvr_set_engine_logger() is installed,
   12103              : // read under the engine mutex.
   12104            2 : bool chttpsvr__engine_user_log_set_for_tests(void) {
   12105            2 :   ccol__call_once(srv_engine_bundler.once, engine_globals_init);
   12106            2 :   ccol__mutex_lock(srv_engine_bundler.mutex);
   12107            2 :   bool set = srv_engine_bundler.user_log != CLOG_NULL;
   12108            2 :   ccol__mutex_unlock(srv_engine_bundler.mutex);
   12109            2 :   return set;
   12110              : }
   12111              : #endif
        

Generated by: LCOV version 2.0-1