LCOV - code coverage report
Current view: top level - src - chttp1_parser.c (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 94.2 % 891 839
Test Date: 2026-11-15 18:57:05 Functions: 100.0 % 47 47
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              : #include <errno.h>
      26              : #include <internal/cascii.h>
      27              : #include <internal/chttp1_parser.h>
      28              : #include <internal/csock.h>
      29              : #include <internal/ctls.h>
      30              : #include <poll.h>
      31              : #include <stdint.h>
      32              : #include <stdlib.h>
      33              : #include <string.h>
      34              : #include <sys/socket.h>
      35              : #include <sys/uio.h>
      36              : #include <unistd.h>
      37              : 
      38              : // The default header count and total header byte caps, which keep a peer from
      39              : // growing the header block without bound. Trailers count against them too.
      40              : // They don't affect the struct layout, so they stay private.
      41              : #define CHTTP1_MAX_HEADER_COUNT 100
      42              : #define CHTTP1_MAX_TOTAL_HEADER_BYTES (64 * 1024)
      43              : 
      44              : // How many blank lines a request may send before its request line. RFC 7230
      45              : // section 3.5 has a server ignore a stray CRLF after a POST body, but an
      46              : // endless stream of them is still malformed input.
      47              : #define CHTTP1_MAX_LEADING_BLANK_LINES 25
      48              : 
      49              : // Bits of chttp1_parser.flags: The facts the header block established, which
      50              : // the framing rules and the accessors read. F_CHUNKED says the latest
      51              : // Transfer-Encoding line that names a coding ends in chunked;
      52              : // F_CHUNKED_APPLIED says chunked appeared anywhere in the merged list so far
      53              : // (it survives a later line that clears F_CHUNKED). F_CHUNK_TOO_LARGE goes
      54              : // with a rejection by max_chunk_size_override, F_OTHER_CODING marks a coding
      55              : // other than chunked, and F_HEADERS_DONE says the header block ended and the
      56              : // framing is known.
      57              : #define F_CHUNKED 0x01u
      58              : #define F_CONTENT_LENGTH 0x02u
      59              : #define F_TRANSFER_ENCODING 0x04u
      60              : #define F_CONNECTION_CLOSE 0x08u
      61              : #define F_CONNECTION_KEEP_ALIVE 0x10u
      62              : #define F_EXPECT_100_CONTINUE 0x20u
      63              : #define F_CHUNK_TOO_LARGE 0x40u
      64              : #define F_CHUNKED_APPLIED 0x80u
      65              : #define F_OTHER_CODING 0x100u
      66              : #define F_HEADERS_DONE 0x200u
      67              : 
      68              : // How many bytes of chunk framing (size lines, extensions, CRLFs) one message
      69              : // may carry beyond what its data earns, so a peer can't send megabytes of
      70              : // extensions around a few bytes of data; see parse_chunk_size_line().
      71              : #define CHTTP1_MAX_CHUNK_OVERHEAD_EXCESS (16u * 1024u)
      72              : 
      73              : // Small character helpers
      74              : //
      75              : // True for an ASCII decimal digit; the version, status and number parsers use
      76              : // it.
      77        57121 : static bool is_digit(unsigned char c) { return c >= '0' && c <= '9'; }
      78              : 
      79              : // True for optional white space (SP or HTAB), which the header, token and
      80              : // chunk-extension scanners skip.
      81        67141 : static bool is_ows(unsigned char c) { return c == ' ' || c == '\t'; }
      82              : 
      83              : // Tells whether c is a tchar of RFC 7230 section 3.2.6. The parser checks
      84              : // methods and header names with it, and the two HTTP modules check caller
      85              : // header names, so they all agree on what a token is.
      86       861014 : bool chttp1_is_tchar(unsigned char c) {
      87       861014 :   if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || is_digit(c))
      88              :     return true;
      89        16277 :   switch (c) {
      90              :     case '!':
      91              :     case '#':
      92              :     case '$':
      93              :     case '%':
      94              :     case '&':
      95              :     case '\'':
      96              :     case '*':
      97              :     case '+':
      98              :     case '-':
      99              :     case '.':
     100              :     case '^':
     101              :     case '_':
     102              :     case '`':
     103              :     case '|':
     104              :     case '~':
     105              :       return true;
     106              :     default:
     107              :       return false;
     108              :   }
     109              : }
     110              : 
     111              : // Tells whether a header value must not hold byte c: Every control byte
     112              : // except HTAB, and DEL. It's the only check that catches a bare CR or a NUL,
     113              : // since accumulate_line() leaves those in the line as content.
     114      9068513 : static bool is_invalid_value_byte(unsigned char c) {
     115      9068499 :   return (c < 0x20 && c != '\t') || c == 0x7f;
     116              : }
     117              : 
     118              : // Tells whether a request-target must not hold byte c. It's stricter than a
     119              : // header value: HTAB and SP are refused too (RFC 7230 sections 3.1.1 and 5.3),
     120              : // or "GET /a<HTAB>b" would reach routing as one target while a front end that
     121              : // splits on white space reads another request.
     122       523581 : static bool is_invalid_target_byte(unsigned char c) {
     123       523581 :   return c <= 0x20 || c == 0x7f;
     124              : }
     125              : 
     126              : // Overflow-checked integer parsing
     127              : //
     128              : // Parses exactly len bytes of s as an unsigned decimal number into *out, for
     129              : // Content-Length. It refuses an empty span, a non-digit and a value above
     130              : // UINT64_MAX, so a huge length can't wrap.
     131         3646 : static bool parse_uint64_decimal(const char *s, size_t len, uint64_t *out) {
     132         3646 :   if (len == 0) return false;
     133              :   uint64_t v = 0;
     134         9048 :   for (size_t i = 0; i < len; i++) {
     135         5406 :     unsigned char c = (unsigned char)s[i];
     136         5406 :     if (!is_digit(c)) return false;
     137         5404 :     unsigned d = (unsigned)(c - '0');
     138         5404 :     if (v > UINT64_MAX / 10) return false;
     139         5403 :     v *= 10;
     140         5403 :     if (v > UINT64_MAX - d) return false;
     141         5403 :     v += d;
     142              :   }
     143              :   *out = v;
     144              :   return true;
     145              : }
     146              : 
     147              : // Parses exactly len bytes of s as a hex number into *out, for chunk sizes,
     148              : // with the same refusals as parse_uint64_decimal().
     149         5701 : static bool parse_uint64_hex(const char *s, size_t len, uint64_t *out) {
     150         5701 :   if (len == 0) return false;
     151              :   uint64_t v = 0;
     152        11584 :   for (size_t i = 0; i < len; i++) {
     153         5888 :     unsigned char c = (unsigned char)s[i];
     154         5888 :     unsigned d;
     155         5888 :     if (c >= '0' && c <= '9')
     156         5843 :       d = (unsigned)(c - '0');
     157           45 :     else if (c >= 'a' && c <= 'f')
     158           23 :       d = (unsigned)(c - 'a' + 10);
     159           22 :     else if (c >= 'A' && c <= 'F')
     160           18 :       d = (unsigned)(c - 'A' + 10);
     161              :     else
     162              :       return false;
     163         5884 :     if (v > UINT64_MAX / 16) return false;
     164         5883 :     v *= 16;
     165         5883 :     if (v > UINT64_MAX - d) return false;
     166         5883 :     v += d;
     167              :   }
     168         5696 :   *out = v;
     169         5696 :   return true;
     170              : }
     171              : 
     172              : // Line accumulation
     173              : //
     174              : // The outcome of accumulate_line().
     175              : typedef enum {
     176              :   LINE_NEED_MORE,
     177              :   LINE_READY,
     178              :   LINE_TOO_LONG,
     179              :   LINE_BAD_EOL
     180              : } line_result;
     181              : 
     182              : // Gives the buffer of the current line: line_spill once the line spilled,
     183              : // else line_buf. Every line reader goes through it, so a spilled line reads
     184              : // the same as a short one.
     185        73304 : static inline char *line_ptr(chttp1_parser *parser) {
     186        71575 :   return parser->line_spill ? parser->line_spill : parser->line_buf;
     187              : }
     188              : 
     189              : // Moves the line that fills line_buf into a CHTTP1_MAX_SPILL_LINE_LEN heap
     190              : // buffer from line_spill_mp, so a response header line can grow past
     191              : // CHTTP1_MAX_LINE_LEN. It gives false when spilling isn't enabled, a spill
     192              : // buffer exists already, header_budget_left couldn't hold a longer line, or
     193              : // the allocation fails. On success it sets parser->line_spill.
     194          408 : static bool line_spill_grow(chttp1_parser *parser, size_t header_budget_left) {
     195          408 :   if (!parser->line_spill_enabled || parser->line_spill) return false;
     196          403 :   if (header_budget_left <= CHTTP1_MAX_LINE_LEN) return false;
     197          804 :   char *heap =
     198          402 :       (char *)ccol__mem_alloc(parser->line_spill_mp, CHTTP1_MAX_SPILL_LINE_LEN);
     199          402 :   if (!heap) return false;
     200          402 :   memcpy(heap, parser->line_buf, parser->line_len);
     201          402 :   parser->line_spill = heap;
     202          402 :   return true;
     203              : }
     204              : 
     205              : // Gives the usable size of the spill buffer for a line: spill_budget when it's
     206              : // smaller than the buffer. That makes a line fail as soon as it passes the
     207              : // header budget, before the buffer is full.
     208         1342 : static inline size_t spill_cap(size_t spill_budget) {
     209         1342 :   return spill_budget && spill_budget < CHTTP1_MAX_SPILL_LINE_LEN
     210              :              ? spill_budget
     211          940 :              : (size_t)CHTTP1_MAX_SPILL_LINE_LEN;
     212              : }
     213              : 
     214              : // Appends input from *pp up to end to the current line, until CRLF, a full
     215              : // buffer or the end of input. Every line-based state of the parser uses it,
     216              : // so lines can span execute() calls. *pp always moves to show what was
     217              : // consumed: To end for NEED_MORE and TOO_LONG, past the line end for READY and
     218              : // BAD_EOL. On READY parser->line_len is the content without the CRLF.
     219              : // spill_budget is 0 for a line that must fit line_buf, or the remaining header
     220              : // budget for a response header or trailer line that may spill (it may set
     221              : // line_spill). Every LF not preceded by CR is BAD_EOL (the parser has no
     222              : // lenient mode); a bare CR stays content for the caller's control byte check.
     223              : // The buffer, capacity and length live in locals because a store through the
     224              : // char buffer could alias the parser fields.
     225        47128 : static line_result accumulate_line(chttp1_parser *parser, const char **pp,
     226              :                                    const char *end, size_t spill_budget) {
     227        47128 :   const char *p = *pp;
     228        47128 :   char *buf = line_ptr(parser);
     229        94256 :   size_t cap = parser->line_spill ? spill_cap(spill_budget)
     230        47128 :                                   : (size_t)CHTTP1_MAX_LINE_LEN;
     231        47128 :   size_t len = parser->line_len;
     232     10952616 :   while (p < end) {
     233     10946135 :     if (len >= cap) {
     234          409 :       parser->line_len = len;
     235          409 :       if (spill_budget && line_spill_grow(parser, spill_budget)) {
     236          402 :         buf = parser->line_spill;
     237          402 :         cap = spill_cap(spill_budget);
     238          402 :         continue;
     239              :       }
     240            8 :       *pp = end;
     241            8 :       return LINE_TOO_LONG;
     242              :     }
     243     10945726 :     char c = *p++;
     244     10945726 :     buf[len++] = c;
     245     10945726 :     if (c == '\n') {
     246        40640 :       if (len < 2 || buf[len - 2] != '\r') {
     247            1 :         parser->line_len = len;
     248            1 :         *pp = p;
     249            1 :         return LINE_BAD_EOL;
     250              :       }
     251        40639 :       parser->line_len = len - 2;
     252        40639 :       *pp = p;
     253        40639 :       return LINE_READY;
     254              :     }
     255              :   }
     256         6481 :   parser->line_len = len;
     257         6481 :   *pp = p;
     258         6481 :   return LINE_NEED_MORE;
     259              : }
     260              : 
     261              : // Lets the line parsers tell malformed input from an error a callback
     262              : // reported.
     263              : typedef enum { PH_OK, PH_ERROR, PH_USER } ph_result;
     264              : 
     265              : // Status line
     266              : //
     267              : // Parses the response status line "HTTP/d.d SP 3DIGIT [SP reason]" in the
     268              : // current line. Any digit is accepted as the major and the minor, and any
     269              : // 3-digit status, since nonstandard codes exist. The reason and its space are
     270              : // optional, because servers send "HTTP/1.1 304". It sets http_major,
     271              : // http_minor and status_code, or parser->reason and false on failure.
     272         4493 : static bool parse_status_line(chttp1_parser *parser) {
     273         4493 :   const char *s = line_ptr(parser);
     274         4493 :   size_t len = parser->line_len;
     275              : 
     276         4493 :   if (len < 8 || memcmp(s, "HTTP/", 5) != 0) {
     277            3 :     parser->reason = "Invalid HTTP version";
     278            3 :     return false;
     279              :   }
     280         4490 :   size_t i = 5;
     281         4490 :   if (!is_digit((unsigned char)s[i])) {
     282            0 :     parser->reason = "Invalid HTTP version";
     283            0 :     return false;
     284              :   }
     285         4490 :   parser->http_major = (uint8_t)(s[i] - '0');
     286         4490 :   i++;
     287         4490 :   if (s[i] != '.') {
     288            0 :     parser->reason = "Invalid HTTP version";
     289            0 :     return false;
     290              :   }
     291         4490 :   i++;
     292         4490 :   if (!is_digit((unsigned char)s[i])) {
     293            0 :     parser->reason = "Invalid HTTP version";
     294            0 :     return false;
     295              :   }
     296         4490 :   parser->http_minor = (uint8_t)(s[i] - '0');
     297         4490 :   i++;
     298         4490 :   if (i >= len || s[i] != ' ') {
     299            0 :     parser->reason = "Invalid HTTP version";
     300            0 :     return false;
     301              :   }
     302         4490 :   i++;
     303              : 
     304         4490 :   if (i + 3 > len || !is_digit((unsigned char)s[i]) ||
     305         4490 :       !is_digit((unsigned char)s[i + 1]) ||
     306         4489 :       !is_digit((unsigned char)s[i + 2])) {
     307            2 :     parser->reason = "Invalid status code";
     308            2 :     return false;
     309              :   }
     310         4488 :   parser->status_code =
     311         4488 :       (s[i] - '0') * 100 + (s[i + 1] - '0') * 10 + (s[i + 2] - '0');
     312         4488 :   i += 3;
     313              : 
     314         4488 :   if (i < len) {
     315         4487 :     if (s[i] != ' ') {
     316            1 :       parser->reason = "Invalid status line";
     317            1 :       return false;
     318              :     }
     319              :     i++;
     320       680940 :     for (; i < len; i++) {
     321      1352908 :       if (is_invalid_value_byte((unsigned char)s[i])) {
     322            0 :         parser->reason = "Invalid character in reason phrase";
     323            0 :         return false;
     324              :       }
     325              :     }
     326              :   }
     327              :   return true;
     328              : }
     329              : 
     330              : // Parses the request line "method SP target SP HTTP/d.d" in line_buf and
     331              : // fires on_request_line, for request mode. The method must be a token and the
     332              : // target free of CTL, DEL and white space; an unknown method or the form of
     333              : // the target is the caller's business. It sets http_major and http_minor and
     334              : // gives PH_OK, PH_ERROR (with parser->reason) or PH_USER when the callback
     335              : // fails.
     336         2209 : static ph_result parse_request_line(chttp1_parser *parser) {
     337         2209 :   const char *s = parser->line_buf;
     338         2209 :   size_t len = parser->line_len;
     339              : 
     340         2209 :   size_t i = 0;
     341         9524 :   while (i < len && s[i] != ' ') i++;
     342         2209 :   if (i == 0 || i >= len) {
     343            0 :     parser->reason = "Invalid request line";
     344            0 :     return PH_ERROR;
     345              :   }
     346              :   const char *method = s;
     347              :   size_t method_len = i;
     348         9522 :   for (size_t j = 0; j < method_len; j++) {
     349         7314 :     if (!chttp1_is_tchar((unsigned char)method[j])) {
     350            1 :       parser->reason = "Invalid method";
     351            1 :       return PH_ERROR;
     352              :     }
     353              :   }
     354         2208 :   i++;
     355              : 
     356         2208 :   size_t target_start = i;
     357       525807 :   while (i < len && s[i] != ' ') i++;
     358         2208 :   if (i == target_start || i >= len) {
     359            2 :     parser->reason = "Invalid request line";
     360            2 :     return PH_ERROR;
     361              :   }
     362         2206 :   const char *target = s + target_start;
     363         2206 :   size_t target_len = i - target_start;
     364       525783 :   for (size_t j = 0; j < target_len; j++) {
     365       523581 :     if (is_invalid_target_byte((unsigned char)target[j])) {
     366            4 :       parser->reason = "Invalid character in request target";
     367            4 :       return PH_ERROR;
     368              :     }
     369              :   }
     370         2202 :   i++;
     371              : 
     372         2202 :   if (len - i < 8 || memcmp(s + i, "HTTP/", 5) != 0) {
     373            1 :     parser->reason = "Invalid HTTP version";
     374            1 :     return PH_ERROR;
     375              :   }
     376         2201 :   i += 5;
     377         2201 :   if (!is_digit((unsigned char)s[i])) {
     378            0 :     parser->reason = "Invalid HTTP version";
     379            0 :     return PH_ERROR;
     380              :   }
     381         2201 :   parser->http_major = (uint8_t)(s[i] - '0');
     382         2201 :   i++;
     383         2201 :   if (s[i] != '.') {
     384            0 :     parser->reason = "Invalid HTTP version";
     385            0 :     return PH_ERROR;
     386              :   }
     387         2201 :   i++;
     388         2201 :   if (!is_digit((unsigned char)s[i])) {
     389            0 :     parser->reason = "Invalid HTTP version";
     390            0 :     return PH_ERROR;
     391              :   }
     392         2201 :   parser->http_minor = (uint8_t)(s[i] - '0');
     393         2201 :   i++;
     394         2201 :   if (i != len) {
     395            0 :     parser->reason = "Invalid request line";
     396            0 :     return PH_ERROR;
     397              :   }
     398              : 
     399         2201 :   if (parser->settings && parser->settings->on_request_line) {
     400         2116 :     int err = parser->settings->on_request_line(parser, method, method_len,
     401              :                                                 target, target_len);
     402         2116 :     if (err != 0) return PH_USER;
     403              :   }
     404              :   return PH_OK;
     405              : }
     406              : 
     407              : // Header and trailer lines
     408              : //
     409              : // True for a hex digit, either case; the Host check uses it for IPv6 literals
     410              : // and percent escapes.
     411           18 : static bool is_hexdig(unsigned char c) {
     412           18 :   return is_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
     413              : }
     414              : 
     415              : // True for an unreserved or sub-delims byte of RFC 3986 sections 2.2 and 2.3,
     416              : // the characters a reg-name may hold; the Host check uses it.
     417         8050 : static bool is_unreserved_or_sub_delim(unsigned char c) {
     418         8050 :   if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || is_digit(c))
     419              :     return true;
     420         2085 :   switch (c) {
     421              :     case '-':
     422              :     case '.':
     423              :     case '_':
     424              :     case '~':
     425              :     case '!':
     426              :     case '$':
     427              :     case '&':
     428              :     case '\'':
     429              :     case '(':
     430              :     case ')':
     431              :     case '*':
     432              :     case '+':
     433              :     case ',':
     434              :     case ';':
     435              :     case '=':
     436              :       return true;
     437              :     default:
     438              :       return false;
     439              :   }
     440              : }
     441              : 
     442              : // Tells whether a Host value (v, len) is uri-host [":" port] (RFC 9112
     443              : // section 3.2, RFC 3986 section 3.2.2). A value outside the grammar ("a/b",
     444              : // "u@h", white space) can name different authorities to different
     445              : // recipients, which smuggling and cache poisoning need, so the parser refuses
     446              : // it. An IPv4 address passes as a reg-name; inside brackets only the IPv6 or
     447              : // IPvFuture characters are checked. An empty host is refused.
     448         2164 : static bool host_value_is_valid(const char *v, size_t len) {
     449         2164 :   size_t i = 0;
     450         2164 :   if (len == 0) return false;
     451         2163 :   if (v[0] == '[') {
     452              :     size_t close = 1;
     453           42 :     while (close < len && v[close] != ']') close++;
     454            9 :     if (close >= len || close == 1) return false;
     455            8 :     const char *lit = v + 1;
     456            8 :     size_t lit_len = close - 1;
     457            8 :     if (lit[0] == 'v' || lit[0] == 'V') {
     458              :       size_t j = 1;
     459            4 :       while (j < lit_len && is_hexdig((unsigned char)lit[j])) j++;
     460            2 :       if (j == 1 || j >= lit_len || lit[j] != '.') return false;
     461            2 :       j++;
     462            2 :       if (j >= lit_len) return false;
     463            4 :       for (; j < lit_len; j++) {
     464            3 :         unsigned char c = (unsigned char)lit[j];
     465            3 :         if (!is_unreserved_or_sub_delim(c) && c != ':') return false;
     466              :       }
     467              :     } else {
     468              :       bool colon = false;
     469           25 :       for (size_t j = 0; j < lit_len; j++) {
     470           20 :         unsigned char c = (unsigned char)lit[j];
     471           20 :         if (c == ':')
     472              :           colon = true;
     473           20 :         else if (!is_hexdig(c) && c != '.')
     474              :           return false;
     475              :       }
     476            5 :       if (!colon) return false;
     477              :     }
     478            5 :     i = close + 1;
     479              :   } else {
     480        10194 :     while (i < len && v[i] != ':') {
     481         8049 :       unsigned char c = (unsigned char)v[i];
     482         8049 :       if (c == '%') {
     483            3 :         if (i + 2 >= len || !is_hexdig((unsigned char)v[i + 1]) ||
     484            2 :             !is_hexdig((unsigned char)v[i + 2]))
     485              :           return false;
     486            1 :         i += 3;
     487            1 :         continue;
     488              :       }
     489         8047 :       if (!is_unreserved_or_sub_delim(c)) return false;
     490         8039 :       i++;
     491              :     }
     492         2145 :     if (i == 0) return false;
     493              :   }
     494         2149 :   if (i == len) return true;
     495          210 :   if (v[i] != ':') return false;
     496         1241 :   for (i++; i < len; i++)
     497         1033 :     if (!is_digit((unsigned char)v[i])) return false;
     498              :   return true;
     499              : }
     500              : 
     501              : // Compares a header name with a lowercase literal, ignoring ASCII case in any
     502              : // locale, so process_header_line() can find the fields it interprets.
     503        44147 : static bool header_name_is(const char *name, size_t name_len,
     504              :                            const char *literal) {
     505        44147 :   size_t lit_len = strlen(literal);
     506        44147 :   return name_len == lit_len &&
     507         9778 :          ccol_ascii_ncasecmp(name, literal, lit_len) == 0;
     508              : }
     509              : 
     510              : // Scans one Transfer-Encoding value (v, len, OWS already trimmed) and answers
     511              : // every question the framing rules ask about chunked on that line. It's one
     512              : // function on purpose: Two scanners with their own idea of a token boundary
     513              : // could disagree about one header, and their answers drive opposite
     514              : // decisions, which is the ambiguity request smuggling needs. A new question
     515              : // about the list goes here.
     516              : //
     517              : // Empty elements are ignored (RFC 7230 sections 7 and 4.1), so "chunked,"
     518              : // names "chunked". The outputs: chunked_count (saturating at 2; chunked twice
     519              : // is refused in both modes), nonfinal_chunked (chunked before another coding,
     520              : // refused for a request), ends_with_chunked (the last non-empty token),
     521              : // names_a_coding (a line with only empty elements leaves the framing alone)
     522              : // and names_other_coding. The caller merges these across lines.
     523         1401 : static void transfer_encoding_scan(
     524              :     const char *v, size_t len, unsigned *chunked_count, bool *nonfinal_chunked,
     525              :     bool *ends_with_chunked, bool *names_a_coding, bool *names_other_coding) {
     526         1401 :   unsigned count = 0;
     527         1401 :   bool nonfinal = false;
     528         1401 :   bool any_token = false;
     529         1401 :   bool other = false;
     530         1401 :   bool last_token_was_chunked = false;
     531         1401 :   size_t i = 0;
     532         2812 :   while (i < len) {
     533              :     size_t start = i;
     534        11019 :     while (i < len && v[i] != ',') i++;
     535              :     size_t tok_end = i;
     536         1421 :     while (tok_end > start && is_ows((unsigned char)v[tok_end - 1])) tok_end--;
     537         1411 :     size_t ts = start;
     538         1429 :     while (ts < tok_end && is_ows((unsigned char)v[ts])) ts++;
     539         1411 :     size_t tok_len = tok_end - ts;
     540         1411 :     if (i < len) i++;
     541         1411 :     if (tok_len == 0) continue;
     542         2772 :     bool is_chunked =
     543         1386 :         (tok_len == 7 && ccol_ascii_ncasecmp(v + ts, "chunked", 7) == 0);
     544         1386 :     if (last_token_was_chunked) nonfinal = true;
     545         1386 :     if (is_chunked && count < 2) count++;
     546         1386 :     if (!is_chunked) other = true;
     547              :     last_token_was_chunked = is_chunked;
     548              :     any_token = true;
     549              :   }
     550         1401 :   *chunked_count = count;
     551         1401 :   *nonfinal_chunked = nonfinal;
     552         1401 :   *ends_with_chunked = last_token_was_chunked;
     553         1401 :   *names_a_coding = any_token;
     554         1401 :   *names_other_coding = other;
     555         1401 : }
     556              : 
     557              : // Reads the tokens of a Connection value and sets F_CONNECTION_CLOSE or
     558              : // F_CONNECTION_KEEP_ALIVE in parser->flags, which chttp1_should_keep_alive()
     559              : // reads. Upgrade isn't handled at all.
     560         1493 : static void parse_connection_tokens(chttp1_parser *parser, const char *v,
     561              :                                     size_t len) {
     562         1493 :   size_t i = 0;
     563         2995 :   while (i < len) {
     564         1526 :     while (i < len && (is_ows((unsigned char)v[i]) || v[i] == ',')) i++;
     565         1502 :     size_t start = i;
     566        10054 :     while (i < len && v[i] != ',') i++;
     567              :     size_t tok_end = i;
     568         1502 :     while (tok_end > start && is_ows((unsigned char)v[tok_end - 1])) tok_end--;
     569         1502 :     size_t tok_len = tok_end - start;
     570         1502 :     if (tok_len == 5 && ccol_ascii_ncasecmp(v + start, "close", 5) == 0) {
     571         1290 :       parser->flags |= F_CONNECTION_CLOSE;
     572          212 :     } else if (tok_len == 10 &&
     573          206 :                ccol_ascii_ncasecmp(v + start, "keep-alive", 10) == 0) {
     574          206 :       parser->flags |= F_CONNECTION_KEEP_ALIVE;
     575              :     }
     576              :   }
     577         1493 : }
     578              : 
     579              : // Gives the total header byte cap of parser: Its override, or the default.
     580              : // Header lines and the first line are both charged against it.
     581        31598 : static size_t effective_max_total_header_bytes(const chttp1_parser *parser) {
     582        31598 :   return parser->max_total_header_bytes_override
     583              :              ? parser->max_total_header_bytes_override
     584        31598 :              : CHTTP1_MAX_TOTAL_HEADER_BYTES;
     585              : }
     586              : 
     587              : // Gives the spill_budget accumulate_line() gets for a header or trailer line:
     588              : // 0 when spilling is off, else what's left of the header byte budget, so a
     589              : // spilled line can't pass the cap.
     590        27782 : static size_t header_spill_budget(const chttp1_parser *parser) {
     591        27782 :   if (!parser->line_spill_enabled) return 0;
     592         8905 :   size_t max = effective_max_total_header_bytes(parser);
     593         8905 :   return max > parser->total_header_bytes ? max - parser->total_header_bytes
     594         8905 :                                           : 0;
     595              : }
     596              : 
     597              : // Validates the current line as one "name: value" header or trailer, charges
     598              : // it to the header count and byte caps, and calls on_header or on_trailer.
     599              : // is_trailer picks the kind. A header line also updates the framing,
     600              : // Connection, Expect and Host state in parser->flags and host_count: A
     601              : // duplicate or bad Content-Length, chunked applied twice (on one line or
     602              : // across merged lines, F_CHUNKED_APPLIED), a request chunked that isn't last
     603              : // on its line, and Content-Length with chunked are refused. F_CHUNKED is
     604              : // derived again on every Transfer-Encoding line that names a coding, so
     605              : // chunked then identity fails and gzip then chunked passes; the final check
     606              : // waits for the end of the headers. A trailer touches none of that state, so
     607              : // it can't change a framing that's already acted on. It gives PH_OK, PH_ERROR
     608              : // (with parser->reason) or PH_USER.
     609        15990 : static ph_result process_header_line(chttp1_parser *parser, bool is_trailer) {
     610        15990 :   size_t contribution = parser->line_len + 2;
     611        31980 :   size_t max_count = parser->max_header_count_override
     612              :                          ? parser->max_header_count_override
     613        15990 :                          : CHTTP1_MAX_HEADER_COUNT;
     614        15990 :   size_t max_bytes = effective_max_total_header_bytes(parser);
     615        15990 :   if (parser->header_count + 1 > max_count) {
     616            3 :     parser->reason = "Too many headers";
     617            3 :     return PH_ERROR;
     618              :   }
     619        15987 :   if (parser->total_header_bytes + contribution > max_bytes) {
     620            5 :     parser->reason = "Header block too large";
     621            5 :     return PH_ERROR;
     622              :   }
     623              : 
     624        15982 :   char *line = line_ptr(parser);
     625        15982 :   size_t line_len = parser->line_len;
     626        15982 :   char *colon = memchr(line, ':', line_len);
     627        15982 :   if (!colon || colon == line) {
     628            4 :     parser->reason = "Invalid header field";
     629            4 :     return PH_ERROR;
     630              :   }
     631        15978 :   char *name = line;
     632        15978 :   size_t name_len = (size_t)(colon - line);
     633       159539 :   for (size_t i = 0; i < name_len; i++) {
     634       143563 :     if (!chttp1_is_tchar((unsigned char)name[i])) {
     635            2 :       parser->reason = "Invalid header field char";
     636            2 :       return PH_ERROR;
     637              :     }
     638              :   }
     639              : 
     640        15976 :   char *vstart = colon + 1;
     641        15976 :   char *vend = line + line_len;
     642        31162 :   while (vstart < vend && is_ows((unsigned char)*vstart)) vstart++;
     643        15983 :   while (vend > vstart && is_ows((unsigned char)vend[-1])) vend--;
     644        15976 :   size_t value_len = (size_t)(vend - vstart);
     645      8407973 :   for (size_t i = 0; i < value_len; i++) {
     646     16783996 :     if (is_invalid_value_byte((unsigned char)vstart[i])) {
     647            2 :       parser->reason = "Invalid header value char";
     648            2 :       return PH_ERROR;
     649              :     }
     650              :   }
     651              : 
     652        15974 :   if (is_trailer) {
     653         1184 :     if (parser->settings && parser->settings->on_trailer) {
     654         1176 :       int err = parser->settings->on_trailer(parser, name, name_len, vstart,
     655              :                                              value_len);
     656         1176 :       if (err != 0) return PH_USER;
     657              :     }
     658         1183 :     parser->header_count++;
     659         1183 :     parser->total_header_bytes += contribution;
     660         1183 :     return PH_OK;
     661              :   }
     662              : 
     663        14790 :   if (header_name_is(name, name_len, "content-length")) {
     664         3648 :     if (parser->flags & F_CONTENT_LENGTH) {
     665            2 :       parser->reason = "Duplicate Content-Length";
     666            2 :       return PH_ERROR;
     667              :     }
     668         3646 :     uint64_t v;
     669         7291 :     if (!parse_uint64_decimal(vstart, value_len, &v)) {
     670            3 :       parser->reason = "Invalid Content-Length";
     671            3 :       return PH_ERROR;
     672              :     }
     673         3643 :     parser->flags |= F_CONTENT_LENGTH;
     674         3643 :     parser->content_length = v;
     675        11142 :   } else if (header_name_is(name, name_len, "transfer-encoding")) {
     676         1401 :     parser->flags |= F_TRANSFER_ENCODING;
     677         1401 :     unsigned line_chunked_count;
     678         1401 :     bool line_has_nonfinal_chunked;
     679         1401 :     bool line_ends_with_chunked;
     680         1401 :     bool line_names_a_coding;
     681         1401 :     bool line_names_other_coding;
     682         1401 :     transfer_encoding_scan(vstart, value_len, &line_chunked_count,
     683              :                            &line_has_nonfinal_chunked, &line_ends_with_chunked,
     684              :                            &line_names_a_coding, &line_names_other_coding);
     685         1401 :     if (line_names_other_coding) parser->flags |= F_OTHER_CODING;
     686         1401 :     if (line_chunked_count > 1 ||
     687         1338 :         (line_chunked_count > 0 && (parser->flags & F_CHUNKED_APPLIED))) {
     688           13 :       parser->reason = "chunked can't be applied more than once";
     689           16 :       return PH_ERROR;
     690              :     }
     691         1388 :     if (line_chunked_count > 0) parser->flags |= F_CHUNKED_APPLIED;
     692         1388 :     if (parser->type == CHTTP1_PARSE_REQUEST && line_has_nonfinal_chunked) {
     693            3 :       parser->reason = "chunked must be the last Transfer-Encoding token";
     694            3 :       return PH_ERROR;
     695              :     }
     696         1385 :     if (line_ends_with_chunked)
     697         1322 :       parser->flags |= F_CHUNKED;
     698           63 :     else if (line_names_a_coding)
     699           29 :       parser->flags &= (uint16_t)~F_CHUNKED;
     700         9741 :   } else if (parser->type == CHTTP1_PARSE_REQUEST &&
     701         4551 :              header_name_is(name, name_len, "host")) {
     702         2164 :     if (parser->host_count < 2) parser->host_count++;
     703         2164 :     if (!host_value_is_valid(vstart, value_len)) {
     704           17 :       parser->reason = "Invalid Host header value";
     705           17 :       return PH_ERROR;
     706              :     }
     707         7577 :   } else if (header_name_is(name, name_len, "connection")) {
     708         1491 :     parse_connection_tokens(parser, vstart, value_len);
     709         6086 :   } else if (header_name_is(name, name_len, "expect")) {
     710           84 :     if (value_len == 12 && ccol_ascii_ncasecmp(vstart, "100-continue", 12) == 0)
     711           83 :       parser->flags |= F_EXPECT_100_CONTINUE;
     712              :   }
     713              : 
     714        14753 :   if ((parser->flags & F_CONTENT_LENGTH) && (parser->flags & F_CHUNKED)) {
     715           21 :     parser->reason =
     716              :         "Content-Length can't be present with chunked Transfer-Encoding";
     717           21 :     return PH_ERROR;
     718              :   }
     719              : 
     720        14732 :   if (parser->settings && parser->settings->on_header) {
     721        14463 :     int err =
     722        14463 :         parser->settings->on_header(parser, name, name_len, vstart, value_len);
     723        14462 :     if (err != 0) return PH_USER;
     724              :   }
     725              : 
     726        14689 :   parser->header_count++;
     727        14689 :   parser->total_header_bytes += contribution;
     728        14689 :   return PH_OK;
     729              : }
     730              : 
     731              : // Chunk size line
     732              : //
     733              : // Tells whether s[i..len) is a valid chunk-ext list (RFC 9112 section 7.1.1);
     734              : // an empty span is. The parser drops extensions but checks the grammar in
     735              : // full, because a recipient that skips everything after ';' accepts control
     736              : // bytes a stricter one refuses, and the two then frame the body
     737              : // differently.
     738         5696 : static bool chunk_ext_is_valid(const char *s, size_t i, size_t len) {
     739         8962 :   while (i < len) {
     740         3365 :     while (i < len && is_ows((unsigned char)s[i])) i++;
     741         3335 :     if (i >= len || s[i] != ';') return false;
     742         3301 :     i++;
     743         3305 :     while (i < len && is_ows((unsigned char)s[i])) i++;
     744         3301 :     size_t name_start = i;
     745       661692 :     while (i < len && chttp1_is_tchar((unsigned char)s[i])) i++;
     746         3301 :     if (i == name_start) return false;
     747              :     size_t after_name = i;
     748         3297 :     while (i < len && is_ows((unsigned char)s[i])) i++;
     749         3289 :     if (i >= len || s[i] != '=') {
     750          106 :       i = after_name;
     751          106 :       continue;
     752              :     }
     753         3183 :     i++;
     754         3187 :     while (i < len && is_ows((unsigned char)s[i])) i++;
     755         3183 :     if (i >= len) return false;
     756         3179 :     if (s[i] == '"') {
     757           20 :       i++;
     758           68 :       for (;;) {
     759           68 :         if (i >= len) return false;
     760           64 :         unsigned char c = (unsigned char)s[i];
     761           64 :         if (c == '"') {
     762            4 :           i++;
     763            4 :           break;
     764              :         }
     765           60 :         if (c == '\\') {
     766            8 :           i++;
     767            8 :           if (i >= len || is_invalid_value_byte((unsigned char)s[i]))
     768              :             return false;
     769            4 :           i++;
     770            4 :           continue;
     771              :         }
     772          113 :         if (is_invalid_value_byte(c)) return false;
     773           44 :         i++;
     774              :       }
     775              :     } else {
     776              :       size_t val_start = i;
     777        41279 :       while (i < len && chttp1_is_tchar((unsigned char)s[i])) i++;
     778         3159 :       if (i == val_start) return false;
     779              :     }
     780              :   }
     781              :   return true;
     782              : }
     783              : 
     784              : // Parses the current line as "1*HEXDIG chunk-ext" and stores the size in
     785              : // content_length, so the chunk data state knows how much to read. Response
     786              : // mode also accepts white space before the CRLF with no extension; request
     787              : // mode stays strict, since a looser server is half of a smuggling pair. A
     788              : // size above max_chunk_size_override sets F_CHUNK_TOO_LARGE. Each chunk adds
     789              : // its line and CRLFs to chunk_excess and earns back 16 bytes plus twice its
     790              : // data (Go's rule); passing CHTTP1_MAX_CHUNK_OVERHEAD_EXCESS fails the
     791              : // message, so extensions can't be sent for free. It gives false with
     792              : // parser->reason set on any refusal.
     793         5701 : static bool parse_chunk_size_line(chttp1_parser *parser) {
     794         5701 :   const char *s = line_ptr(parser);
     795         5701 :   size_t len = parser->line_len;
     796         5701 :   size_t hex_len = 0;
     797        11601 :   while (hex_len < len && s[hex_len] != ';' &&
     798              :          !is_ows((unsigned char)s[hex_len]))
     799         5900 :     hex_len++;
     800              : 
     801         5701 :   uint64_t v;
     802         5701 :   if (!parse_uint64_hex(s, hex_len, &v)) {
     803            5 :     parser->reason = "Invalid chunk size";
     804            5 :     return false;
     805              :   }
     806         5696 :   size_t ext_start = hex_len;
     807         5696 :   if (parser->type == CHTTP1_PARSE_RESPONSE) {
     808              :     size_t j = hex_len;
     809         3455 :     while (j < len && is_ows((unsigned char)s[j])) j++;
     810         3439 :     if (j == len) ext_start = len;
     811              :   }
     812         5696 :   if (!chunk_ext_is_valid(s, ext_start, len)) {
     813           69 :     parser->reason = "Invalid chunk extension";
     814           69 :     return false;
     815              :   }
     816         5627 :   if (parser->max_chunk_size_override && v > parser->max_chunk_size_override) {
     817            4 :     parser->flags |= F_CHUNK_TOO_LARGE;
     818            4 :     parser->reason = "Chunk size exceeds configured maximum";
     819            4 :     return false;
     820              :   }
     821         5623 :   uint64_t excess = parser->chunk_excess + (uint64_t)len + 4u;
     822         5623 :   uint64_t earned = v > (UINT64_MAX - 16u) / 2u ? UINT64_MAX : 16u + 2u * v;
     823         5623 :   excess = excess > earned ? excess - earned : 0;
     824          396 :   if (excess > CHTTP1_MAX_CHUNK_OVERHEAD_EXCESS) {
     825            2 :     parser->reason = "Chunk framing exceeds its data";
     826            2 :     return false;
     827              :   }
     828         5621 :   parser->chunk_excess = excess;
     829         5621 :   parser->content_length = v;
     830         5621 :   return true;
     831              : }
     832              : 
     833              : // Terminal outcomes
     834              : //
     835              : // Ends the parse on malformed input: Stores reason, moves the parser to DEAD
     836              : // and gives CHTTP1_ERROR.
     837           71 : static chttp1_errno fail(chttp1_parser *parser, const char *reason) {
     838           71 :   parser->reason = reason;
     839           71 :   parser->state = CHTTP1_ST_DEAD;
     840           71 :   return CHTTP1_ERROR;
     841              : }
     842              : 
     843              : // Ends the parse like fail() when a helper already set parser->reason.
     844          169 : static chttp1_errno fail_already_set(chttp1_parser *parser) {
     845          169 :   parser->state = CHTTP1_ST_DEAD;
     846          169 :   return CHTTP1_ERROR;
     847              : }
     848              : 
     849              : // Ends the parse after a callback reported an error: Moves the parser to DEAD,
     850              : // sets a reason if none is set and gives CHTTP1_USER.
     851          225 : static chttp1_errno user_error(chttp1_parser *parser) {
     852          225 :   parser->state = CHTTP1_ST_DEAD;
     853          225 :   if (!parser->reason) parser->reason = "Callback reported an error";
     854          225 :   return CHTTP1_USER;
     855              : }
     856              : 
     857              : // Finishes a message: Fires on_message_complete, records in parser->consumed
     858              : // how much of data was used (p is the current position), moves to
     859              : // MESSAGE_DONE and gives CHTTP1_PAUSED, or CHTTP1_USER when the callback
     860              : // fails.
     861         6150 : static chttp1_errno complete_message(chttp1_parser *parser, const char *p,
     862              :                                      const char *data) {
     863         6150 :   if (parser->settings && parser->settings->on_message_complete) {
     864         6068 :     int err = parser->settings->on_message_complete(parser);
     865         6068 :     if (err != 0) return user_error(parser);
     866              :   }
     867         6150 :   parser->consumed = (size_t)(p - data);
     868         6150 :   parser->state = CHTTP1_ST_MESSAGE_DONE;
     869         6150 :   return CHTTP1_PAUSED;
     870              : }
     871              : 
     872              : // Lifecycle
     873              : //
     874              : // Zeroes settings, so every callback is NULL until the caller sets one.
     875          195 : void chttp1_settings_init(chttp1_settings *settings) {
     876          195 :   memset(settings, 0, sizeof(*settings));
     877          195 : }
     878              : 
     879              : // The init clears only the members before line_buf (see the comment of
     880              : // line_buf in the header), so it must be the last member and the struct must
     881              : // end exactly where it ends.
     882              : _Static_assert(offsetof(chttp1_parser, line_buf) +
     883              :                        sizeof(((chttp1_parser *)0)->line_buf) ==
     884              :                    sizeof(chttp1_parser),
     885              :                "line_buf must be the last member of chttp1_parser");
     886              : _Static_assert(CHTTP1_MAX_LINE_LEN % _Alignof(max_align_t) == 0,
     887              :                "the size of line_buf must keep the end of chttp1_parser "
     888              :                "aligned");
     889              : 
     890              : // Prepares parser for a new message of the given type, the shared body of the
     891              : // two inits. It clears every member in front of line_buf, sets the first-line
     892              : // state and an unsafe finish state, and keeps settings.
     893         8778 : static void parser_init_common(chttp1_parser *parser,
     894              :                                const chttp1_settings *settings,
     895              :                                chttp1_parser_type type) {
     896         8778 :   memset(parser, 0, offsetof(chttp1_parser, line_buf));
     897         8778 :   parser->type = type;
     898         8778 :   parser->state = CHTTP1_ST_FIRST_LINE;
     899         8778 :   parser->finish_state = CHTTP1_FINISH_UNSAFE;
     900         8778 :   parser->settings = settings;
     901         8778 : }
     902              : 
     903              : // Prepares parser for a new response, for chttpclient.
     904         4602 : void chttp1_parser_init(chttp1_parser *parser,
     905              :                         const chttp1_settings *settings) {
     906         4602 :   parser_init_common(parser, settings, CHTTP1_PARSE_RESPONSE);
     907         4602 : }
     908              : 
     909              : // Prepares parser for a new request, for chttpserver.
     910         4176 : void chttp1_parser_init_request(chttp1_parser *parser,
     911              :                                 const chttp1_settings *settings) {
     912         4176 :   parser_init_common(parser, settings, CHTTP1_PARSE_REQUEST);
     913         4176 : }
     914              : 
     915              : // Lets a response parser move a long header or trailer line to a heap buffer
     916              : // from mp, because real responses can carry header lines longer than 8 KiB.
     917              : // It sets line_spill_enabled and line_spill_mp and gives false for NULL or a
     918              : // request parser.
     919         2643 : bool chttp1_parser_enable_line_spill(chttp1_parser *parser,
     920              :                                      ccol_memmgmt_procs *mp) {
     921         2643 :   if (!parser || parser->type != CHTTP1_PARSE_RESPONSE) return false;
     922         2642 :   parser->line_spill_enabled = true;
     923         2642 :   parser->line_spill_mp = mp;
     924         2642 :   return true;
     925              : }
     926              : 
     927              : // Frees the spill buffer of parser, if any, so a spilling response parser
     928              : // doesn't leak, and clears line_spill so a second call does nothing.
     929         4018 : void chttp1_parser_release(chttp1_parser *parser) {
     930         4018 :   if (!parser || !parser->line_spill) return;
     931          402 :   ccol__mem_free(parser->line_spill_mp, parser->line_spill);
     932          402 :   parser->line_spill = NULL;
     933              : }
     934              : 
     935              : // Main execute loop
     936              : //
     937              : // Runs the state machine over len bytes of data, firing the callbacks; it's
     938              : // the one entry point that turns wire bytes into a message for both modules.
     939              : // It gives the outcome code (a dead or finished parser gives CHTTP1_ERROR at
     940              : // once) and updates every state field of parser. A request skips up to
     941              : // CHTTP1_MAX_LEADING_BLANK_LINES blank lines first, and the first line counts
     942              : // against the total header bytes (max_header_bytes covers the request line).
     943              : // At the end of the headers, before on_headers_complete so the caller never
     944              : // routes such a message, a request is refused for two Host lines, no Host in
     945              : // HTTP/1.1, Transfer-Encoding in HTTP/1.0 (RFC 9112 section 6.1) and a
     946              : // Transfer-Encoding that doesn't end in chunked (section 6.3). A 1xx, 204 or
     947              : // 304 response has no body. A response with a non-chunked Transfer-Encoding
     948              : // and a Content-Length is refused, since framing it by the length would leave
     949              : // the sender's extra bytes on a keep-alive connection. Then it picks the
     950              : // framing: chunked, Content-Length, no body for a request without framing, or
     951              : // EOF for a response, the only mode where finish_state is SAFE_WITH_CB.
     952        24980 : chttp1_errno chttp1_parser_execute(chttp1_parser *parser, const char *data,
     953              :                                    size_t len) {
     954        24980 :   const char *p = data;
     955        24980 :   const char *end = data + len;
     956              : 
     957        24980 :   if (parser->state == CHTTP1_ST_DEAD ||
     958              :       parser->state == CHTTP1_ST_MESSAGE_DONE)
     959              :     return CHTTP1_ERROR;
     960              : 
     961        83478 :   while (p < end) {
     962        65283 :     switch (parser->state) {
     963         8704 :       case CHTTP1_ST_FIRST_LINE: {
     964         8704 :         line_result lr = accumulate_line(parser, &p, end, 0);
     965         8704 :         if (lr == LINE_NEED_MORE) break;
     966         6802 :         if (lr == LINE_TOO_LONG)
     967            0 :           return fail(parser, parser->type == CHTTP1_PARSE_REQUEST
     968              :                                   ? "Request line too long"
     969              :                                   : "Status line too long");
     970         6802 :         if (lr == LINE_BAD_EOL) return fail(parser, "Expected CRLF");
     971         6801 :         if (parser->type == CHTTP1_PARSE_REQUEST && parser->line_len == 0) {
     972           98 :           if (++parser->leading_blank_lines > CHTTP1_MAX_LEADING_BLANK_LINES)
     973            1 :             return fail(parser, "Too many leading blank lines");
     974           97 :           parser->line_len = 0;
     975           97 :           break;
     976              :         }
     977              :         {
     978         6703 :           size_t contribution = parser->line_len + 2;
     979         6703 :           if (parser->total_header_bytes + contribution >
     980         6703 :               effective_max_total_header_bytes(parser))
     981            1 :             return fail(parser, parser->type == CHTTP1_PARSE_REQUEST
     982              :                                     ? "Request line too large"
     983              :                                     : "Status line too large");
     984         6702 :           parser->total_header_bytes += contribution;
     985              :         }
     986         6702 :         if (parser->type == CHTTP1_PARSE_REQUEST) {
     987         2209 :           ph_result plr = parse_request_line(parser);
     988         2209 :           if (plr == PH_ERROR) return fail_already_set(parser);
     989         2225 :           if (plr == PH_USER) return user_error(parser);
     990              :         } else {
     991         4493 :           if (!parse_status_line(parser)) return fail_already_set(parser);
     992              :         }
     993         6664 :         parser->line_len = 0;
     994         6664 :         parser->finish_state = CHTTP1_FINISH_UNSAFE;
     995         6664 :         parser->state = CHTTP1_ST_HEADERS;
     996         6664 :         break;
     997              :       }
     998              : 
     999              :       case CHTTP1_ST_HEADERS: {
    1000        25296 :         line_result lr =
    1001        25296 :             accumulate_line(parser, &p, end, header_spill_budget(parser));
    1002        25297 :         if (lr == LINE_NEED_MORE) break;
    1003        21349 :         if (lr == LINE_TOO_LONG) return fail(parser, "Header line too long");
    1004        21341 :         if (lr == LINE_BAD_EOL) return fail(parser, "Expected CRLF");
    1005              : 
    1006        21341 :         if (parser->line_len == 0) {
    1007         6537 :           if (parser->type == CHTTP1_PARSE_REQUEST) {
    1008         4204 :             bool is_1_1_or_later =
    1009         2102 :                 parser->http_major > 1 ||
    1010         2102 :                 (parser->http_major == 1 && parser->http_minor >= 1);
    1011         2102 :             if (parser->host_count > 1)
    1012            4 :               return fail(parser, "Duplicate Host header");
    1013         2098 :             if (parser->host_count == 0 && is_1_1_or_later)
    1014            8 :               return fail(parser, "Missing Host header");
    1015         2090 :             if ((parser->flags & F_TRANSFER_ENCODING) && !is_1_1_or_later)
    1016            3 :               return fail(parser, "Transfer-Encoding in an HTTP/1.0 request");
    1017         2087 :             if ((parser->flags & F_TRANSFER_ENCODING) &&
    1018              :                 !(parser->flags & F_CHUNKED))
    1019            3 :               return fail(parser,
    1020              :                           "Transfer-Encoding present but final encoding is "
    1021              :                           "not chunked");
    1022              :           }
    1023              : 
    1024         6519 :           parser->flags |= F_HEADERS_DONE;
    1025         6519 :           int hint = CHTTP1_HEADERS_HAS_BODY;
    1026         6519 :           if (parser->settings && parser->settings->on_headers_complete)
    1027         6368 :             hint = parser->settings->on_headers_complete(parser);
    1028         6369 :           bool want_divert = (hint == CHTTP1_HEADERS_DIVERT_BODY &&
    1029         1071 :                               parser->type == CHTTP1_PARSE_REQUEST);
    1030         6520 :           if (hint != CHTTP1_HEADERS_HAS_BODY &&
    1031         6520 :               hint != CHTTP1_HEADERS_NO_BODY && !want_divert)
    1032          288 :             return user_error(parser);
    1033              : 
    1034         6376 :           bool no_body = (hint == CHTTP1_HEADERS_NO_BODY);
    1035         6376 :           if (!no_body && parser->type == CHTTP1_PARSE_RESPONSE &&
    1036         4415 :               ((parser->status_code >= 100 && parser->status_code < 200) ||
    1037         3824 :                parser->status_code == 204 || parser->status_code == 304)) {
    1038              :             no_body = true;
    1039              :           }
    1040              : 
    1041         5782 :           if (!no_body && (parser->flags & F_TRANSFER_ENCODING) &&
    1042         5778 :               !(parser->flags & F_CHUNKED) &&
    1043              :               (parser->flags & F_CONTENT_LENGTH)) {
    1044            3 :             return fail(parser,
    1045              :                         "Content-Length can't be present with a "
    1046              :                         "non-chunked Transfer-Encoding");
    1047              :           }
    1048              : 
    1049         5775 :           if (no_body) {
    1050          598 :             parser->finish_state = CHTTP1_FINISH_SAFE;
    1051         1196 :             return complete_message(parser, p, data);
    1052              :           }
    1053              : 
    1054         5775 :           if (parser->flags & F_CHUNKED) {
    1055         1275 :             parser->state = CHTTP1_ST_BODY_CHUNK_SIZE;
    1056         1275 :             parser->finish_state = CHTTP1_FINISH_UNSAFE;
    1057         1275 :             if (want_divert) {
    1058           31 :               parser->consumed = (size_t)(p - data);
    1059           31 :               return CHTTP1_HEADERS_ONLY;
    1060              :             }
    1061         4500 :           } else if (parser->flags & F_CONTENT_LENGTH) {
    1062         3575 :             if (parser->content_length == 0) {
    1063          356 :               parser->finish_state = CHTTP1_FINISH_SAFE;
    1064          712 :               return complete_message(parser, p, data);
    1065              :             }
    1066         3219 :             parser->state = CHTTP1_ST_BODY_CONTENT_LENGTH;
    1067         3219 :             parser->finish_state = CHTTP1_FINISH_UNSAFE;
    1068         3219 :             if (want_divert) {
    1069          172 :               parser->consumed = (size_t)(p - data);
    1070          172 :               return CHTTP1_HEADERS_ONLY;
    1071              :             }
    1072          925 :           } else if (parser->type == CHTTP1_PARSE_REQUEST) {
    1073          902 :             parser->finish_state = CHTTP1_FINISH_SAFE;
    1074         1804 :             return complete_message(parser, p, data);
    1075              :           } else {
    1076           23 :             parser->state = CHTTP1_ST_BODY_EOF;
    1077           23 :             parser->finish_state = CHTTP1_FINISH_SAFE_WITH_CB;
    1078              :           }
    1079              :         } else {
    1080        14804 :           ph_result ph = process_header_line(parser, false);
    1081        14804 :           if (ph == PH_ERROR) return fail_already_set(parser);
    1082        14775 :           if (ph == PH_USER) return user_error(parser);
    1083        14691 :           parser->line_len = 0;
    1084              :         }
    1085              :         break;
    1086              :       }
    1087              : 
    1088        13467 :       case CHTTP1_ST_BODY_CONTENT_LENGTH: {
    1089        13467 :         size_t avail = (size_t)(end - p);
    1090        13467 :         size_t take = (uint64_t)avail < parser->content_length
    1091              :                           ? avail
    1092              :                           : (size_t)parser->content_length;
    1093        13467 :         if (take > 0) {
    1094        13468 :           if (parser->settings && parser->settings->on_body) {
    1095        13466 :             int err = parser->settings->on_body(parser, p, take);
    1096        13469 :             if (err != 0) return user_error(parser);
    1097              :           }
    1098        13453 :           p += take;
    1099        13453 :           parser->content_length -= take;
    1100              :         }
    1101        13452 :         if (parser->content_length == 0) {
    1102         3117 :           parser->finish_state = CHTTP1_FINISH_SAFE;
    1103         6234 :           return complete_message(parser, p, data);
    1104              :         }
    1105              :         break;
    1106              :       }
    1107              : 
    1108         6170 :       case CHTTP1_ST_BODY_CHUNK_SIZE: {
    1109         6170 :         line_result lr = accumulate_line(parser, &p, end, 0);
    1110         6170 :         if (lr == LINE_NEED_MORE) break;
    1111         5701 :         if (lr == LINE_TOO_LONG)
    1112            0 :           return fail(parser, "Chunk size line too long");
    1113         5701 :         if (lr == LINE_BAD_EOL) return fail(parser, "Expected CRLF");
    1114         5701 :         if (!parse_chunk_size_line(parser)) return fail_already_set(parser);
    1115         5621 :         parser->line_len = 0;
    1116         5621 :         if (parser->content_length == 0) {
    1117         1183 :           parser->state = CHTTP1_ST_BODY_CHUNK_TRAILERS;
    1118              :         } else {
    1119         4438 :           parser->state = CHTTP1_ST_BODY_CHUNK_DATA;
    1120              :         }
    1121              :         break;
    1122              :       }
    1123              : 
    1124         4668 :       case CHTTP1_ST_BODY_CHUNK_DATA: {
    1125         4668 :         size_t avail = (size_t)(end - p);
    1126         4668 :         size_t take = (uint64_t)avail < parser->content_length
    1127              :                           ? avail
    1128              :                           : (size_t)parser->content_length;
    1129         4668 :         if (take > 0) {
    1130         4668 :           if (parser->settings && parser->settings->on_body) {
    1131         4525 :             int err = parser->settings->on_body(parser, p, take);
    1132         4529 :             if (err != 0) return user_error(parser);
    1133              :           }
    1134         4664 :           p += take;
    1135         4664 :           parser->content_length -= take;
    1136              :         }
    1137         4664 :         if (parser->content_length == 0)
    1138         4430 :           parser->state = CHTTP1_ST_BODY_CHUNK_CRLF;
    1139              :         break;
    1140              :       }
    1141              : 
    1142         4472 :       case CHTTP1_ST_BODY_CHUNK_CRLF: {
    1143         4472 :         line_result lr = accumulate_line(parser, &p, end, 0);
    1144         4472 :         if (lr == LINE_NEED_MORE) break;
    1145         4430 :         if (lr == LINE_TOO_LONG || lr == LINE_BAD_EOL || parser->line_len != 0)
    1146            2 :           return fail(parser, "Expected CRLF after chunk data");
    1147         4428 :         parser->state = CHTTP1_ST_BODY_CHUNK_SIZE;
    1148         4428 :         break;
    1149              :       }
    1150              : 
    1151              :       case CHTTP1_ST_BODY_CHUNK_TRAILERS: {
    1152         2486 :         line_result lr =
    1153         2486 :             accumulate_line(parser, &p, end, header_spill_budget(parser));
    1154         2486 :         if (lr == LINE_NEED_MORE) break;
    1155         2365 :         if (lr == LINE_TOO_LONG) return fail(parser, "Trailer line too long");
    1156         2365 :         if (lr == LINE_BAD_EOL) return fail(parser, "Expected CRLF");
    1157              : 
    1158         2365 :         if (parser->line_len == 0) {
    1159         1177 :           parser->finish_state = CHTTP1_FINISH_SAFE;
    1160         2354 :           return complete_message(parser, p, data);
    1161              :         }
    1162         1188 :         ph_result ph = process_header_line(parser, true);
    1163         1188 :         if (ph == PH_ERROR) return fail_already_set(parser);
    1164         1185 :         if (ph == PH_USER) return user_error(parser);
    1165         1183 :         parser->line_len = 0;
    1166         1183 :         break;
    1167              :       }
    1168              : 
    1169           20 :       case CHTTP1_ST_BODY_EOF: {
    1170           20 :         size_t avail = (size_t)(end - p);
    1171           20 :         if (avail > 0) {
    1172           20 :           if (parser->settings && parser->settings->on_body) {
    1173           20 :             int err = parser->settings->on_body(parser, p, avail);
    1174           21 :             if (err != 0) return user_error(parser);
    1175              :           }
    1176           19 :           p = end;
    1177              :         }
    1178              :         break;
    1179              :       }
    1180              : 
    1181              :       case CHTTP1_ST_MESSAGE_DONE:
    1182              :       case CHTTP1_ST_DEAD:
    1183              :       default:
    1184              :         return CHTTP1_ERROR;
    1185              :     }
    1186              :   }
    1187              :   return CHTTP1_OK;
    1188              : }
    1189              : 
    1190              : // Finish (EOF handling)
    1191              : //
    1192              : // Tells whether an EOF from the connection is a valid end of the message,
    1193              : // because a response without framing ends only at EOF. It gives CHTTP1_PAUSED
    1194              : // (after on_message_complete, moving to MESSAGE_DONE) for an EOF-delimited
    1195              : // body, CHTTP1_OK at a clean boundary, CHTTP1_ERROR for a cut message, and
    1196              : // CHTTP1_USER when the callback fails. A parser already at MESSAGE_DONE gives
    1197              : // CHTTP1_OK, so a second call never fires on_message_complete again
    1198              : // (finish_state stays SAFE_WITH_CB after an EOF-delimited message, since
    1199              : // chttp1_should_keep_alive() reads it).
    1200           56 : chttp1_errno chttp1_parser_finish(chttp1_parser *parser) {
    1201           56 :   if (parser->state == CHTTP1_ST_DEAD) return CHTTP1_ERROR;
    1202           56 :   if (parser->state == CHTTP1_ST_MESSAGE_DONE) return CHTTP1_OK;
    1203              : 
    1204           53 :   switch (parser->finish_state) {
    1205              :     case CHTTP1_FINISH_SAFE:
    1206              :       return CHTTP1_OK;
    1207           16 :     case CHTTP1_FINISH_SAFE_WITH_CB:
    1208           16 :       if (parser->settings && parser->settings->on_message_complete) {
    1209           16 :         int err = parser->settings->on_message_complete(parser);
    1210           16 :         if (err != 0) return user_error(parser);
    1211              :       }
    1212           16 :       parser->state = CHTTP1_ST_MESSAGE_DONE;
    1213           16 :       return CHTTP1_PAUSED;
    1214              :     case CHTTP1_FINISH_UNSAFE:
    1215              :     default:
    1216           37 :       return fail(parser, "Invalid EOF state");
    1217              :   }
    1218              : }
    1219              : 
    1220              : // Accessors
    1221              : //
    1222              : // Gives parser->consumed, the bytes of the last execute() buffer the message
    1223              : // used, so the caller knows where its leftover starts.
    1224         5547 : size_t chttp1_parser_consumed(const chttp1_parser *parser) {
    1225         5547 :   return parser->consumed;
    1226              : }
    1227              : 
    1228              : // Tells whether the parser reached MESSAGE_DONE, for a worker that continues a
    1229              : // request across a divert.
    1230         4476 : bool chttp1_parser_message_complete(const chttp1_parser *parser) {
    1231         4476 :   return parser->state == CHTTP1_ST_MESSAGE_DONE;
    1232              : }
    1233              : 
    1234              : // Sets F_CONNECTION_CLOSE, so chttp1_should_keep_alive() says no for a
    1235              : // connection that lost bytes of a pipelined message.
    1236            2 : void chttp1_parser_force_close(chttp1_parser *parser) {
    1237            2 :   if (parser) parser->flags |= F_CONNECTION_CLOSE;
    1238            2 : }
    1239              : 
    1240              : // Tells whether the connection may carry another message, so the caller can
    1241              : // pool or close it. It reads the version, the Connection flags,
    1242              : // Transfer-Encoding and finish_state. "1.1 or later" is major > 1 or 1.1+, so
    1243              : // HTTP/2.0 doesn't fall into the 1.0 class. A close token wins first. An
    1244              : // EOF-delimited body is the one case where finish_state stays SAFE_WITH_CB,
    1245              : // so that alone rules out keep-alive.
    1246         5233 : bool chttp1_should_keep_alive(const chttp1_parser *parser) {
    1247         5233 :   bool is_1_1_or_later = parser->http_major > 1 ||
    1248         5231 :                          (parser->http_major == 1 && parser->http_minor >= 1);
    1249         5233 :   if (parser->flags & F_CONNECTION_CLOSE) return false;
    1250         4158 :   if (!is_1_1_or_later && !(parser->flags & F_CONNECTION_KEEP_ALIVE))
    1251              :     return false;
    1252           15 :   if (!is_1_1_or_later && (parser->flags & F_TRANSFER_ENCODING)) return false;
    1253              : 
    1254         4142 :   bool needs_eof = (parser->finish_state == CHTTP1_FINISH_SAFE_WITH_CB);
    1255         4142 :   return !needs_eof;
    1256              : }
    1257              : 
    1258              : // Tells whether the headers held "Expect: 100-continue" in an HTTP/1.1 or
    1259              : // later message, so a server knows to answer before reading the body. RFC
    1260              : // 9110 section 10.1.1 has a server ignore it from HTTP/1.0.
    1261         1696 : bool chttp1_expects_continue(const chttp1_parser *parser) {
    1262         1696 :   bool is_1_1_or_later = parser->http_major > 1 ||
    1263         1695 :                          (parser->http_major == 1 && parser->http_minor >= 1);
    1264         1692 :   return is_1_1_or_later && (parser->flags & F_EXPECT_100_CONTINUE) != 0;
    1265              : }
    1266              : 
    1267              : // Tells whether F_OTHER_CODING is set, a coding this parser can't decode, so
    1268              : // the caller refuses the message. False for NULL.
    1269         3362 : bool chttp1_has_other_transfer_coding(const chttp1_parser *parser) {
    1270         3362 :   return parser && (parser->flags & F_OTHER_CODING) != 0;
    1271              : }
    1272              : 
    1273              : // Tells whether F_CONTENT_LENGTH is set, so the caller can look at the
    1274              : // declared length. False for NULL.
    1275         5874 : bool chttp1_has_content_length(const chttp1_parser *parser) {
    1276         5874 :   return parser && (parser->flags & F_CONTENT_LENGTH) != 0;
    1277              : }
    1278              : 
    1279              : // Gives content_length, which holds the declared length until the body parse
    1280              : // starts, so a server can refuse an oversized body at once. 0 for NULL.
    1281         2728 : uint64_t chttp1_declared_content_length(const chttp1_parser *parser) {
    1282         2728 :   return parser ? parser->content_length : 0;
    1283              : }
    1284              : 
    1285              : // Tells whether F_CHUNK_TOO_LARGE is set, so the caller answers a chunk over
    1286              : // its limit as a body that's too large. False for NULL.
    1287           17 : bool chttp1_chunk_size_limit_exceeded(const chttp1_parser *parser) {
    1288           17 :   return parser && (parser->flags & F_CHUNK_TOO_LARGE) != 0;
    1289              : }
    1290              : 
    1291              : // Tells whether the peer may still send bytes of this message, so a server
    1292              : // knows to linger before it closes. Without F_HEADERS_DONE the framing isn't
    1293              : // known, so the answer is true; after it, a chunked body or a Content-Length
    1294              : // body with bytes left gives true. False for NULL and a complete message.
    1295          587 : bool chttp1_request_bytes_may_remain(const chttp1_parser *parser) {
    1296          587 :   if (!parser || parser->state == CHTTP1_ST_MESSAGE_DONE) return false;
    1297          283 :   if (!(parser->flags & F_HEADERS_DONE)) return true;
    1298          196 :   if (parser->flags & F_CHUNKED) return true;
    1299          290 :   return (parser->flags & F_CONTENT_LENGTH) && parser->content_length > 0;
    1300              : }
    1301              : 
    1302              : // Gives the body bytes the framing still guarantees, which a server uses as
    1303              : // SO_RCVLOWAT: content_length inside a Content-Length body or a chunk's data,
    1304              : // 0 in every other state and for NULL.
    1305          129 : uint64_t chttp1_body_bytes_still_expected(const chttp1_parser *parser) {
    1306          129 :   if (!parser) return 0;
    1307          128 :   switch (parser->state) {
    1308          111 :     case CHTTP1_ST_BODY_CONTENT_LENGTH:
    1309              :     case CHTTP1_ST_BODY_CHUNK_DATA:
    1310          111 :       return parser->content_length;
    1311              :     case CHTTP1_ST_FIRST_LINE:
    1312              :     case CHTTP1_ST_HEADERS:
    1313              :     case CHTTP1_ST_BODY_CHUNK_SIZE:
    1314              :     case CHTTP1_ST_BODY_CHUNK_CRLF:
    1315              :     case CHTTP1_ST_BODY_CHUNK_TRAILERS:
    1316              :     case CHTTP1_ST_BODY_EOF:
    1317              :     case CHTTP1_ST_MESSAGE_DONE:
    1318              :     case CHTTP1_ST_DEAD:
    1319              :       return 0;
    1320              :   }
    1321              :   return 0;
    1322              : }
    1323              : 
    1324              : // Worker-pull body and response streaming
    1325              : //
    1326              : // Prepares stream, the shared body of the two prepare functions: It zeroes
    1327              : // the stream, records fd, tls_conn and mp, and copies leftover into a carry
    1328              : // buffer from mp. On a failed copy it gives false and rolls every field back
    1329              : // so the stream is all zeros, except fd, which goes to -1 so a caller that
    1330              : // ignores the result can't touch fd 0.
    1331         1747 : static bool stream_prepare_common(chttp1_stream *stream, int fd, void *tls_conn,
    1332              :                                   const char *leftover, size_t leftover_len,
    1333              :                                   ccol_memmgmt_procs *mp) {
    1334         1747 :   memset(stream, 0, sizeof(*stream));
    1335         1747 :   stream->fd = fd;
    1336         1747 :   stream->tls = tls_conn;
    1337         1747 :   stream->mp = mp;
    1338         1747 :   stream->prepared = true;
    1339         1747 :   if (leftover_len == 0) return true;
    1340              : 
    1341          174 :   char *copy = (char *)ccol__mem_alloc(mp, leftover_len);
    1342          174 :   if (!copy) {
    1343            0 :     stream->fd = -1;
    1344            0 :     stream->tls = NULL;
    1345            0 :     stream->mp = NULL;
    1346            0 :     stream->prepared = false;
    1347            0 :     return false;
    1348              :   }
    1349          174 :   memcpy(copy, leftover, leftover_len);
    1350          174 :   stream->carry = copy;
    1351          174 :   stream->carry_len = leftover_len;
    1352          174 :   stream->carry_pos = 0;
    1353          174 :   return true;
    1354              : }
    1355              : 
    1356              : // Prepares a plaintext stream on fd with a copy of leftover, for a worker that
    1357              : // takes over a diverted connection.
    1358         1641 : bool chttp1_stream_prepare(chttp1_stream *stream, int fd, const char *leftover,
    1359              :                            size_t leftover_len, ccol_memmgmt_procs *mp) {
    1360         1641 :   return stream_prepare_common(stream, fd, NULL, leftover, leftover_len, mp);
    1361              : }
    1362              : 
    1363              : // Prepares a TLS stream on fd and tls_conn with a copy of leftover, for a
    1364              : // worker that takes over a diverted TLS connection.
    1365          106 : bool chttp1_stream_prepare_tls(chttp1_stream *stream, int fd, void *tls_conn,
    1366              :                                const char *leftover, size_t leftover_len,
    1367              :                                ccol_memmgmt_procs *mp) {
    1368          106 :   return stream_prepare_common(stream, fd, tls_conn, leftover, leftover_len,
    1369              :                                mp);
    1370              : }
    1371              : 
    1372              : static void compute_deadline(struct timespec *deadline, int timeout_ms);
    1373              : static long remaining_ms(const struct timespec *deadline);
    1374              : 
    1375              : // Waits in poll(2) until stream->fd is ready for events, so the read and write
    1376              : // paths never block in the I/O call itself. It gives true when ready, false
    1377              : // when timeout_ms passed (stream->timed_out set) or poll failed
    1378              : // (stream->last_errno set). EINTR retries with what's left of the timeout,
    1379              : // and a passed deadline still gets one zero poll.
    1380           60 : static bool wait_for_ready(chttp1_stream *stream, short events,
    1381              :                            int timeout_ms) {
    1382           60 :   struct pollfd pfd = {.fd = stream->fd, .events = events, .revents = 0};
    1383           60 :   struct timespec deadline;
    1384           60 :   bool bounded = timeout_ms > 0;
    1385           60 :   if (bounded) compute_deadline(&deadline, timeout_ms);
    1386              :   int wait_ms = timeout_ms;
    1387           74 :   for (;;) {
    1388           74 :     int rv = poll(&pfd, 1, wait_ms);
    1389           74 :     if (rv > 0) return true;
    1390           21 :     if (rv == 0) {
    1391            7 :       stream->timed_out = true;
    1392            7 :       return false;
    1393              :     }
    1394           14 :     if (errno != EINTR) {
    1395            0 :       stream->last_errno = errno;
    1396            0 :       return false;
    1397              :     }
    1398           14 :     if (bounded) {
    1399           14 :       long rem = remaining_ms(&deadline);
    1400           74 :       wait_ms = rem > 0 ? (int)rem : 0;
    1401              :     }
    1402              :   }
    1403              : }
    1404              : 
    1405              : // Gives the milliseconds left until deadline, rounded up (a wait must not end
    1406              : // early), 0 when it passed, capped at INT_MAX. The retry loops use it so all
    1407              : // their rounds share one timeout budget.
    1408          504 : static long remaining_ms(const struct timespec *deadline) {
    1409          504 :   struct timespec now;
    1410          504 :   clock_gettime(CLOCK_MONOTONIC, &now);
    1411          504 :   long long ns = (long long)(deadline->tv_sec - now.tv_sec) * 1000000000LL +
    1412          504 :                  (deadline->tv_nsec - now.tv_nsec);
    1413          504 :   if (ns <= 0) return 0;
    1414           54 :   long long ms = (ns + 999999LL) / 1000000LL;
    1415           54 :   return ms > (long long)INT_MAX ? (long)INT_MAX : (long)ms;
    1416              : }
    1417              : 
    1418              : // Sets *deadline to CLOCK_MONOTONIC now plus timeout_ms, the start of every
    1419              : // bounded read or write.
    1420         4167 : static void compute_deadline(struct timespec *deadline, int timeout_ms) {
    1421         4167 :   clock_gettime(CLOCK_MONOTONIC, deadline);
    1422         4167 :   deadline->tv_sec += timeout_ms / 1000;
    1423         4167 :   deadline->tv_nsec += (long)(timeout_ms % 1000) * 1000000L;
    1424         4167 :   if (deadline->tv_nsec >= 1000000000L) {
    1425           26 :     deadline->tv_nsec -= 1000000000L;
    1426           26 :     deadline->tv_sec += 1;
    1427              :   }
    1428         4167 : }
    1429              : 
    1430              : // Reads up to buflen bytes into buf for a worker that pulls a body: From the
    1431              : // carry-over first (freeing it once drained), then from the connection within
    1432              : // timeout_ms. It gives the bytes read, 0 at EOF, or -1 with timed_out or
    1433              : // last_errno set. A TLS stream reads before polling: OpenSSL may hold
    1434              : // decrypted bytes poll can't see, and it's what makes a timeout of 0 still
    1435              : // try once. A TLS read that would block waits for the direction
    1436              : // ctls_conn_wants_write() names, since OpenSSL may need to write first. A
    1437              : // plaintext stream with fd_nonblocking also reads first; otherwise it makes
    1438              : // one poll with timeout_ms passed straight through (recomputing would turn a
    1439              : // 0 timeout into a timeout without any check) and then one read, because a
    1440              : // read on a blocking empty fd would ignore the timeout.
    1441         2583 : ssize_t chttp1_stream_read(chttp1_stream *stream, char *buf, size_t buflen,
    1442              :                            int timeout_ms) {
    1443         2583 :   stream->timed_out = false;
    1444         2583 :   stream->last_errno = 0;
    1445              : 
    1446         2583 :   if (stream->carry_pos < stream->carry_len) {
    1447           84 :     size_t avail = stream->carry_len - stream->carry_pos;
    1448           84 :     size_t take = avail < buflen ? avail : buflen;
    1449           84 :     if (take > 0) memcpy(buf, stream->carry + stream->carry_pos, take);
    1450           84 :     stream->carry_pos += take;
    1451           84 :     if (stream->carry_pos == stream->carry_len) {
    1452           83 :       ccol__mem_free(stream->mp, stream->carry);
    1453           83 :       stream->carry = NULL;
    1454           83 :       stream->carry_len = 0;
    1455           83 :       stream->carry_pos = 0;
    1456              :     }
    1457           84 :     return (ssize_t)take;
    1458              :   }
    1459              : 
    1460         2499 :   bool has_deadline = timeout_ms >= 0;
    1461         2499 :   struct timespec deadline;
    1462         2499 :   if (has_deadline) compute_deadline(&deadline, timeout_ms);
    1463              : 
    1464         2499 :   if (stream->tls) {
    1465           14 :     for (;;) {
    1466           14 :       ssize_t got = ctls_conn_read((ctls_conn *)stream->tls, buf, buflen);
    1467           14 :       if (got >= 0) return got;
    1468            6 :       if (!(errno == EWOULDBLOCK || errno == EAGAIN)) {
    1469            0 :         stream->last_errno = errno;
    1470            0 :         return -1;
    1471              :       }
    1472              : 
    1473            6 :       int this_timeout = timeout_ms;
    1474            6 :       if (has_deadline) {
    1475            6 :         long rem = remaining_ms(&deadline);
    1476            6 :         if (rem <= 0) {
    1477            6 :           stream->timed_out = true;
    1478            6 :           return -1;
    1479              :         }
    1480            0 :         this_timeout = (int)rem;
    1481              :       }
    1482            0 :       short want_events =
    1483            0 :           ctls_conn_wants_write((ctls_conn *)stream->tls) ? POLLOUT : POLLIN;
    1484            0 :       if (!wait_for_ready(stream, want_events, this_timeout)) return -1;
    1485              :     }
    1486              :   }
    1487              : 
    1488         2485 :   if (stream->fd_nonblocking) {
    1489         2515 :     for (;;) {
    1490         2515 :       ssize_t got = read(stream->fd, buf, buflen);
    1491         2515 :       if (got >= 0) return got;
    1492          358 :       if (errno == EINTR) continue;
    1493          358 :       if (!(errno == EWOULDBLOCK || errno == EAGAIN)) {
    1494            0 :         stream->last_errno = errno;
    1495            0 :         return -1;
    1496              :       }
    1497          358 :       int this_timeout = timeout_ms;
    1498          358 :       if (has_deadline) {
    1499          355 :         long rem = remaining_ms(&deadline);
    1500          355 :         if (rem <= 0) {
    1501          316 :           stream->timed_out = true;
    1502          316 :           return -1;
    1503              :         }
    1504           39 :         this_timeout = (int)rem;
    1505              :       }
    1506           42 :       if (!wait_for_ready(stream, POLLIN, this_timeout)) return -1;
    1507              :     }
    1508              :   }
    1509              : 
    1510            9 :   if (!wait_for_ready(stream, POLLIN, timeout_ms)) return -1;
    1511              : 
    1512            7 :   ssize_t got;
    1513            7 :   do {
    1514            7 :     got = read(stream->fd, buf, buflen);
    1515            7 :   } while (got < 0 && errno == EINTR);
    1516            6 :   if (got < 0) stream->last_errno = errno;
    1517              :   return got;
    1518              : }
    1519              : 
    1520              : // Writes up to len bytes of buf for a worker that sends a response, within
    1521              : // timeout_ms (0 with write_nonblocking). It gives the bytes written or -1 with
    1522              : // timed_out or last_errno set. The deadline isn't checked on the first round,
    1523              : // so a 0 timeout still tries once. A TLS write that would block waits for the
    1524              : // direction OpenSSL needs. A plaintext send uses MSG_NOSIGNAL and never
    1525              : // blocks (ccol_send_nb()), since POLLOUT means some room and not room for len
    1526              : // bytes; EINTR and EAGAIN wait again.
    1527          122 : ssize_t chttp1_stream_write(chttp1_stream *stream, const char *buf, size_t len,
    1528              :                             int timeout_ms) {
    1529          122 :   stream->timed_out = false;
    1530          122 :   stream->last_errno = 0;
    1531          122 :   if (stream->write_nonblocking) timeout_ms = 0;
    1532              : 
    1533          129 :   bool has_deadline = timeout_ms >= 0;
    1534            7 :   struct timespec deadline;
    1535          122 :   if (has_deadline) compute_deadline(&deadline, timeout_ms);
    1536              : 
    1537          122 :   short want_events = POLLOUT;
    1538          122 :   bool first_attempt = true;
    1539          123 :   for (;;) {
    1540          123 :     int this_timeout = timeout_ms;
    1541          123 :     if (has_deadline && !first_attempt) {
    1542            1 :       long rem = remaining_ms(&deadline);
    1543            1 :       if (rem <= 0) {
    1544            0 :         stream->timed_out = true;
    1545            0 :         return -1;
    1546              :       }
    1547            1 :       this_timeout = (int)rem;
    1548              :     }
    1549          131 :     if (!(first_attempt && stream->fd_nonblocking) &&
    1550            8 :         !wait_for_ready(stream, want_events, this_timeout))
    1551              :       return -1;
    1552          122 :     first_attempt = false;
    1553              : 
    1554          122 :     if (stream->tls) {
    1555           98 :       ssize_t written = ctls_conn_write((ctls_conn *)stream->tls, buf, len);
    1556           98 :       if (written >= 0) return written;
    1557            0 :       if (errno == EWOULDBLOCK || errno == EAGAIN) {
    1558            0 :         want_events =
    1559            0 :             ctls_conn_wants_write((ctls_conn *)stream->tls) ? POLLOUT : POLLIN;
    1560            0 :         continue;
    1561              :       }
    1562            0 :       stream->last_errno = errno;
    1563            0 :       return -1;
    1564              :     }
    1565              : 
    1566           24 :     ssize_t written = ccol_send_nb(stream->fd, buf, len, CCOL_MSG_NOSIGNAL);
    1567           24 :     if (written >= 0) return written;
    1568            2 :     if (errno == EINTR) continue;
    1569            1 :     if (errno == EWOULDBLOCK || errno == EAGAIN) continue;
    1570            1 :     stream->last_errno = errno;
    1571            1 :     return -1;
    1572              :   }
    1573              : }
    1574              : 
    1575              : // Writes a and then b as one write where it can, within timeout_ms, so the
    1576              : // server sends a response head and body together. It gives the bytes written
    1577              : // across both, or -1 like chttp1_stream_write(). TLS joins parts that fit one
    1578              : // record into a stack buffer (one encryption and one send), else writes a and
    1579              : // tries b with no wait. Plaintext loops over one sendmsg(2) with MSG_NOSIGNAL
    1580              : // and MSG_DONTWAIT; where send ignores MSG_DONTWAIT (the Darwin emulation)
    1581              : // ccol_send_room() caps each attempt.
    1582         1596 : ssize_t chttp1_stream_writev2(chttp1_stream *stream, const char *a, size_t alen,
    1583              :                               const char *b, size_t blen, int timeout_ms) {
    1584         1596 :   stream->timed_out = false;
    1585         1596 :   stream->last_errno = 0;
    1586         1596 :   if (stream->write_nonblocking) timeout_ms = 0;
    1587         1596 :   if (alen == 0 && blen == 0) return 0;
    1588              : 
    1589         1596 :   if (stream->tls) {
    1590           97 :     if (alen == 0) return chttp1_stream_write(stream, b, blen, timeout_ms);
    1591           96 :     if (blen == 0) return chttp1_stream_write(stream, a, alen, timeout_ms);
    1592           94 :     if (blen <= CHTTP1_TLS_COALESCE_LIMIT &&
    1593           94 :         alen <= CHTTP1_TLS_COALESCE_LIMIT - blen) {
    1594           94 :       char joined[CHTTP1_TLS_COALESCE_LIMIT];
    1595           94 :       memcpy(joined, a, alen);
    1596           94 :       memcpy(joined + alen, b, blen);
    1597           94 :       return chttp1_stream_write(stream, joined, alen + blen, timeout_ms);
    1598              :     }
    1599            0 :     ssize_t n = chttp1_stream_write(stream, a, alen, timeout_ms);
    1600            0 :     if (n < (ssize_t)alen) return n;
    1601            0 :     ssize_t m = chttp1_stream_write(stream, b, blen, 0);
    1602            0 :     stream->timed_out = false;
    1603            0 :     stream->last_errno = 0;
    1604            0 :     return m > 0 ? n + m : n;
    1605              :   }
    1606              : 
    1607         1499 :   struct iovec iov[2];
    1608         1499 :   int cnt = 0;
    1609         1499 :   if (alen) iov[cnt++] = (struct iovec){.iov_base = (void *)a, .iov_len = alen};
    1610         1499 :   if (blen) iov[cnt++] = (struct iovec){.iov_base = (void *)b, .iov_len = blen};
    1611         1499 :   struct msghdr msg = {.msg_iov = iov, .msg_iovlen = (size_t)cnt};
    1612         1499 :   bool has_deadline = timeout_ms >= 0;
    1613         1499 :   struct timespec deadline;
    1614         1499 :   if (has_deadline) compute_deadline(&deadline, timeout_ms);
    1615              :   bool first_attempt = true;
    1616         1755 :   for (;;) {
    1617         1627 :     int this_timeout = timeout_ms;
    1618         1627 :     if (has_deadline && !first_attempt) {
    1619          128 :       long rem = remaining_ms(&deadline);
    1620          128 :       if (rem <= 0) {
    1621          128 :         stream->timed_out = true;
    1622          128 :         return -1;
    1623              :       }
    1624            0 :       this_timeout = (int)rem;
    1625              :     }
    1626         1500 :     if (!(first_attempt && stream->fd_nonblocking) &&
    1627            1 :         !wait_for_ready(stream, POLLOUT, this_timeout))
    1628              :       return -1;
    1629         1499 :     first_attempt = false;
    1630              : #if defined(CCOL__EMULATE_DARWIN_SOCK)
    1631              :     struct iovec part[2];
    1632              :     struct msghdr pmsg = msg;
    1633              :     size_t room = ccol_send_room(stream->fd, alen + blen);
    1634              :     if (room == 0) continue;
    1635              :     if (room < alen + blen) {
    1636              :       int n = 0;
    1637              :       for (int i = 0; i < cnt && room > 0; i++) {
    1638              :         part[n] = iov[i];
    1639              :         if (part[n].iov_len > room) part[n].iov_len = room;
    1640              :         room -= part[n].iov_len;
    1641              :         n++;
    1642              :       }
    1643              :       pmsg.msg_iov = part;
    1644              :       pmsg.msg_iovlen = n;
    1645              :     }
    1646              :     ssize_t written = sendmsg(stream->fd, &pmsg, CCOL_MSG_NOSIGNAL);
    1647              : #else
    1648         1499 :     ssize_t written =
    1649         1499 :         sendmsg(stream->fd, &msg, CCOL_MSG_NOSIGNAL | MSG_DONTWAIT);
    1650              : #endif
    1651         1499 :     if (written >= 0) return written;
    1652          134 :     if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR) continue;
    1653            6 :     stream->last_errno = errno;
    1654            6 :     return -1;
    1655              :   }
    1656              : }
    1657              : 
    1658              : // Gives stream->timed_out, so a caller can tell a deadline from an error.
    1659          467 : bool chttp1_stream_timed_out(const chttp1_stream *stream) {
    1660          467 :   return stream->timed_out;
    1661              : }
    1662              : 
    1663              : // Gives stream->last_errno, the errno of the last failed call.
    1664            4 : int chttp1_stream_last_error(const chttp1_stream *stream) {
    1665            4 :   return stream->last_errno;
    1666              : }
    1667              : 
    1668              : // Puts a copy of buf in front of the unread carry-over, in one new buffer from
    1669              : // stream->mp, so bytes of the next pipelined request survive the end of this
    1670              : // one. It gives false, with the carry-over unchanged, when the sizes would
    1671              : // overflow or the allocation fails.
    1672           11 : bool chttp1_stream_push_back_leftover(chttp1_stream *stream, const char *buf,
    1673              :                                       size_t len) {
    1674           11 :   if (len == 0) return true;
    1675           10 :   size_t existing = stream->carry_len - stream->carry_pos;
    1676           10 :   if (len > SIZE_MAX - existing) return false;
    1677            9 :   size_t total = len + existing;
    1678            9 :   char *nc = (char *)ccol__mem_alloc(stream->mp, total);
    1679            9 :   if (!nc) return false;
    1680            7 :   memcpy(nc, buf, len);
    1681            7 :   if (existing) memcpy(nc + len, stream->carry + stream->carry_pos, existing);
    1682            7 :   ccol__mem_free(stream->mp, stream->carry);
    1683            7 :   stream->carry = nc;
    1684            7 :   stream->carry_len = total;
    1685            7 :   stream->carry_pos = 0;
    1686            7 :   return true;
    1687              : }
    1688              : 
    1689              : // Hands the unread carry-over to the caller in a new buffer from stream->mp
    1690              : // and empties it, so the server can parse the next pipelined request; *len_out
    1691              : // gets its length. With nothing left it gives NULL and 0. On a failed
    1692              : // allocation it gives NULL, keeps the carry-over for chttp1_stream_release()
    1693              : // and reports the lost bytes in *len_out.
    1694         1078 : char *chttp1_stream_take_leftover(chttp1_stream *stream, size_t *len_out) {
    1695         1078 :   if (len_out) *len_out = 0;
    1696         1078 :   if (stream->carry_pos >= stream->carry_len) return NULL;
    1697           96 :   size_t remaining = stream->carry_len - stream->carry_pos;
    1698           96 :   char *out = (char *)ccol__mem_alloc(stream->mp, remaining);
    1699           96 :   if (!out) {
    1700            2 :     if (len_out) *len_out = remaining;
    1701            2 :     return NULL;
    1702              :   }
    1703           94 :   memcpy(out, stream->carry + stream->carry_pos, remaining);
    1704           94 :   ccol__mem_free(stream->mp, stream->carry);
    1705           94 :   stream->carry = NULL;
    1706           94 :   stream->carry_len = 0;
    1707           94 :   stream->carry_pos = 0;
    1708           94 :   if (len_out) *len_out = remaining;
    1709              :   return out;
    1710              : }
    1711              : 
    1712              : // Frees the carry-over and marks the stream released, when the worker is done
    1713              : // with it. It never closes fd.
    1714         1748 : void chttp1_stream_release(chttp1_stream *stream) {
    1715         1748 :   if (stream->carry) {
    1716            3 :     ccol__mem_free(stream->mp, stream->carry);
    1717            3 :     stream->carry = NULL;
    1718              :   }
    1719         1748 :   stream->carry_len = 0;
    1720         1748 :   stream->carry_pos = 0;
    1721         1748 :   stream->released = true;
    1722         1748 : }
        

Generated by: LCOV version 2.0-1