Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #pragma once
26 :
27 : // Internal only. A small hand-written HTTP/1.1 parser: chttpclient.c uses it
28 : // in response mode and chttpserver.c in request mode. No public header
29 : // includes it.
30 : //
31 : // Both modes share everything after the first line (headers, chunks, trailers
32 : // and the size caps). Request mode adds chttp1_parser_init_request(),
33 : // on_request_line, CHTTP1_HEADERS_DIVERT_BODY and the request body rule of
34 : // RFC 7230 section 3.3. The parser does no I/O. A request parser, and a
35 : // response parser that never enabled line spilling, owns nothing, so it can
36 : // live on the stack and needs no release: The line buffer is a fixed array in
37 : // the struct, and its size is also the line length cap. Body bytes never pass
38 : // through that buffer.
39 : //
40 : // Three caps hold back a peer that sends endless headers: The line length,
41 : // the header count and the total header bytes. Trailers count against the
42 : // same count and byte budget as the headers.
43 : //
44 : // Repeated Transfer-Encoding lines form one merged list (RFC 7230 section
45 : // 3.2.2), and every framing rule applies to that list. Empty elements are
46 : // ignored, so "chunked" followed by an empty Transfer-Encoding line is the
47 : // list "chunked". Both modes refuse "chunked" more than once and a
48 : // Content-Length beside any Transfer-Encoding. A list whose final coding isn't
49 : // chunked fails a request (its length can't be known) and makes a response
50 : // EOF-delimited, never keep-alive. A request chunk-size line follows RFC 9112
51 : // section 7.1 (whitespace after the size only before ';'); response mode also
52 : // accepts "5 \r\n", as Go and curl do.
53 : //
54 : // Nothing here is thread-safe. One thread owns a parser at a time; in request
55 : // mode ownership may move once, at a CHTTP1_HEADERS_ONLY divert, from a reactor
56 : // thread to a worker, and the caller sequences that handoff. chttp1_stream
57 : // follows the same rule.
58 :
59 : #include <common.h>
60 : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
61 : #include <stdbool.h>
62 : #endif
63 : #include <stddef.h>
64 : #include <stdint.h>
65 : #include <sys/types.h>
66 :
67 : // Result codes
68 : //
69 : // The outcome of chttp1_parser_execute() and chttp1_parser_finish(). OK means
70 : // the message isn't complete, keep feeding. PAUSED means it completed (see the
71 : // contracts of chttp1_parser_execute()). USER means a callback reported an
72 : // error. ERROR is every parse failure; parser->reason names it for logs and
73 : // tests.
74 : typedef enum {
75 : CHTTP1_OK = 0,
76 : CHTTP1_PAUSED,
77 : CHTTP1_USER,
78 : CHTTP1_ERROR,
79 : // Request mode only: on_headers_complete gave CHTTP1_HEADERS_DIVERT_BODY, so
80 : // the parse stopped right after the header block, before any body byte.
81 : // chttp1_parser_consumed() is the size of the header block in this call's
82 : // buffer; the rest belongs to the caller (for example as the leftover of
83 : // chttp1_stream_prepare()). Unlike PAUSED this isn't terminal: State already
84 : // sits at the body framing, and more chttp1_parser_execute() calls, from the
85 : // thread that owns the connection, continue the body.
86 : CHTTP1_HEADERS_ONLY
87 : } chttp1_errno;
88 :
89 : // The grammar of the first line. The init function sets it and nothing
90 : // changes it later.
91 : typedef enum {
92 : CHTTP1_PARSE_RESPONSE = 0,
93 : CHTTP1_PARSE_REQUEST
94 : } chttp1_parser_type;
95 :
96 : // What on_headers_complete returns. HAS_BODY (0) and NO_BODY (1) work in both
97 : // modes, so a bare 0 or 1 means the same. DIVERT_BODY is for request mode only;
98 : // a response parser answers it with CHTTP1_USER.
99 : #define CHTTP1_HEADERS_HAS_BODY 0
100 : #define CHTTP1_HEADERS_NO_BODY 1
101 : #define CHTTP1_HEADERS_DIVERT_BODY 2
102 :
103 : // Internal state
104 : //
105 : // The parser's states. They're here only so chttp1_parser is a complete type;
106 : // callers use the accessors below instead. FIRST_LINE is the status line or
107 : // the request line, as parser->type says, and DEAD means a hard error after
108 : // which execute() does nothing.
109 : typedef enum {
110 : CHTTP1_ST_FIRST_LINE = 0,
111 : CHTTP1_ST_HEADERS,
112 : CHTTP1_ST_BODY_CONTENT_LENGTH,
113 : CHTTP1_ST_BODY_CHUNK_SIZE,
114 : CHTTP1_ST_BODY_CHUNK_DATA,
115 : CHTTP1_ST_BODY_CHUNK_CRLF,
116 : CHTTP1_ST_BODY_CHUNK_TRAILERS,
117 : CHTTP1_ST_BODY_EOF,
118 : CHTTP1_ST_MESSAGE_DONE,
119 : CHTTP1_ST_DEAD
120 : } chttp1__state;
121 :
122 : // What an EOF means at the current point: A clean boundary, the end of an
123 : // EOF-delimited body, or a cut message. chttp1_parser_finish() reads it, so
124 : // its caller needn't know the framing.
125 : typedef enum {
126 : CHTTP1_FINISH_SAFE = 0,
127 : CHTTP1_FINISH_SAFE_WITH_CB,
128 : CHTTP1_FINISH_UNSAFE
129 : } chttp1__finish_state;
130 :
131 : // The size of the line buffer in the struct, and with it the longest status,
132 : // header or chunk-size line (except a spilled response header line). It's here
133 : // because it decides the struct layout; the header count and total byte caps
134 : // are private to chttp1_parser.c.
135 : #define CHTTP1_MAX_LINE_LEN 8192
136 :
137 : // The capacity of the heap buffer a spilled response header or trailer line
138 : // moves to, so a client accepts the long header lines real servers send. The
139 : // total header byte cap bounds it too.
140 : #define CHTTP1_MAX_SPILL_LINE_LEN (64 * 1024)
141 :
142 : typedef struct chttp1_parser chttp1_parser;
143 :
144 : // The callbacks. Each is checked for NULL, so set only the ones you need, and
145 : // a callback that returns non-zero stops the parse with CHTTP1_USER (rules of
146 : // on_headers_complete below). Strings point into the parser's line buffer and
147 : // are valid only during the call.
148 : typedef struct {
149 : // Once per complete header line of the header block, with the name as sent
150 : // (not lower-cased) and the value trimmed of SP and HTAB. Trailer fields
151 : // never come here, so a trailer can't replace a header.
152 : int (*on_header)(chttp1_parser *p, const char *name, size_t name_len,
153 : const char *value, size_t value_len);
154 :
155 : // Once per trailer line after the last chunk (RFC 7230 section 4.1.2),
156 : // validated and charged like a header line. Trailers never change the framing
157 : // or what the accessors report. NULL (the default) drops each trailer after
158 : // validation.
159 : int (*on_trailer)(chttp1_parser *p, const char *name, size_t name_len,
160 : const char *value, size_t value_len);
161 :
162 : // Request mode only. Once, after the request line is validated and before the
163 : // first header; http_major and http_minor are set. method is a token and
164 : // target any run without CTL, DEL or white space; the form of the target and
165 : // whether the method is known are left to the caller.
166 : int (*on_request_line)(chttp1_parser *p, const char *method,
167 : size_t method_len, const char *target,
168 : size_t target_len);
169 :
170 : // Once, after the blank line that ends the headers (status_code is set in
171 : // response mode). Return HAS_BODY normally, NO_BODY when the caller knows no
172 : // body follows (a HEAD response, whatever Content-Length says), or, in
173 : // request mode, DIVERT_BODY to stop with CHTTP1_HEADERS_ONLY. Any other value
174 : // stops with CHTTP1_USER, so a callback can report a real error. DIVERT_BODY
175 : // acts as HAS_BODY when there's nothing to divert: No framing at all, or
176 : // "Content-Length: 0". A chunked body is always diverted, since its emptiness
177 : // shows only on the first chunk-size line.
178 : int (*on_headers_complete)(chttp1_parser *p);
179 :
180 : // Zero or more times with body bytes, after the framing is taken off. at
181 : // points into the caller's buffer and is valid only during the call.
182 : int (*on_body)(chttp1_parser *p, const char *at, size_t len);
183 :
184 : // Once, when the whole message is parsed. execute() and finish() report the
185 : // completion with CHTTP1_PAUSED themselves.
186 : int (*on_message_complete)(chttp1_parser *p);
187 : } chttp1_settings;
188 :
189 : // The parser. It owns a resource only after a response parser with spilling
190 : // enabled has spilled a line.
191 : struct chttp1_parser {
192 : // For the caller: Set it after the init and read it in the callbacks.
193 : void *data;
194 :
195 : // Response mode only, set before on_headers_complete; 0 in request mode.
196 : int status_code;
197 :
198 : chttp1_parser_type type;
199 :
200 : // A static description of the last rejection, or NULL. Only logs and tests
201 : // read it.
202 : const char *reason;
203 :
204 : // Internal state; callers neither read nor write it. content_length is the
205 : // bytes left of a Content-Length body or of the current chunk. chunk_excess
206 : // is the chunk framing overhead beyond what the data earned so far.
207 : chttp1__state state;
208 : chttp1__finish_state finish_state;
209 : uint8_t http_major;
210 : uint8_t http_minor;
211 : uint16_t flags;
212 : uint64_t content_length;
213 : uint64_t chunk_excess;
214 :
215 : size_t header_count;
216 : size_t total_header_bytes;
217 : // Request mode: Blank lines accepted before the request line (RFC 7230
218 : // section 3.5).
219 : size_t leading_blank_lines;
220 :
221 : // Request mode: Host lines seen, saturating. Judged at the end of the header
222 : // block: More than one, or none in HTTP/1.1, is a 400 (RFC 7230 section 5.4),
223 : // because two Host lines let a front end and a back end disagree about the
224 : // authority.
225 : uint8_t host_count;
226 :
227 : // Response mode: Set by chttp1_parser_enable_line_spill().
228 : bool line_spill_enabled;
229 :
230 : // Overrides of the built-in header count and total byte caps, 0 for the
231 : // default. Set them before the first byte; chttpserver does, for
232 : // max_header_bytes.
233 : size_t max_header_count_override;
234 : size_t max_total_header_bytes_override;
235 :
236 : // A cap on the declared size of one chunk, 0 for none. A larger chunk-size
237 : // line fails at once (chttp1_chunk_size_limit_exceeded()). Without it a peer
238 : // can declare a huge chunk, send nothing and hold a reader until a timeout,
239 : // so every request parser with a body limit should set it.
240 : uint64_t max_chunk_size_override;
241 :
242 : // The length of the current line, and the heap buffer (with its procs) a
243 : // response parser moves a long line to.
244 : size_t line_len;
245 : char *line_spill;
246 : ccol_memmgmt_procs *line_spill_mp;
247 :
248 : // What chttp1_parser_consumed() reports after a pause.
249 : size_t consumed;
250 :
251 : const chttp1_settings *settings;
252 :
253 : // Accumulates the status, request, header, trailer and chunk-size lines,
254 : // across execute() calls. It must stay the last member: An init clears only
255 : // the members in front of it, which is safe because nothing reads a byte of
256 : // line_buf or line_spill not written since the reset. Every reader stops at
257 : // line_len, and accumulate_line() looks back only at bytes it counted. A new
258 : // reader must keep that. The alignment makes the struct end exactly at the
259 : // buffer on every target (armhf would pad after it otherwise).
260 : _Alignas(max_align_t) char line_buf[CHTTP1_MAX_LINE_LEN];
261 : };
262 :
263 : // Grammar helpers
264 : //
265 : // Tells whether c is a tchar (RFC 7230 section 3.2.6), a byte a header name or
266 : // a method token may hold. The parser checks wire bytes with it, and
267 : // chttp_request_set_header() and chttpsvr_resp_set_header() check a caller's
268 : // header name, so all three agree on what a token is.
269 : bool chttp1_is_tchar(unsigned char c);
270 :
271 : // Lifecycle
272 : //
273 : // Zeroes settings, so every callback is NULL and a caller sets only the ones
274 : // it needs before passing it to an init.
275 : void chttp1_settings_init(chttp1_settings *settings);
276 :
277 : // Prepares parser for a new response; chttpclient calls it for every message
278 : // it reads. settings must outlive the parser. It can't fail. To reuse a
279 : // parser, init it again (release a spilling parser first). The init clears
280 : // the state and not the 8 KiB line buffer.
281 : void chttp1_parser_init(chttp1_parser *parser, const chttp1_settings *settings);
282 :
283 : // Prepares parser for a new request; chttpserver calls it for every request.
284 : // Unlike chttp1_parser_init(), the parser reads a request line, fires
285 : // on_request_line, gives a message without framing no body (never EOF
286 : // framing) and accepts CHTTP1_HEADERS_DIVERT_BODY.
287 : void chttp1_parser_init_request(chttp1_parser *parser,
288 : const chttp1_settings *settings);
289 :
290 : // Lets a response parser take header and trailer lines longer than
291 : // CHTTP1_MAX_LINE_LEN, up to CHTTP1_MAX_SPILL_LINE_LEN and within the total
292 : // header cap, because real servers send long Set-Cookie or CSP lines. Call it
293 : // after the init, before the first byte. A line that fills the fixed buffer
294 : // moves to a heap buffer from mp (NULL for the default) kept for the rest of
295 : // the message; the status and chunk-size lines stay at CHTTP1_MAX_LINE_LEN
296 : // until a header line spills. A failed allocation reports "line too long". It
297 : // gives false for a request parser and a NULL parser. After a true return,
298 : // call chttp1_parser_release() on every path that drops or reinitializes the
299 : // parser.
300 : bool chttp1_parser_enable_line_spill(chttp1_parser *parser,
301 : ccol_memmgmt_procs *mp);
302 :
303 : // Frees the spill buffer of a parser, if it has one, so a spilling response
304 : // parser doesn't leak. Safe on any initialized parser and more than once.
305 : // Reinitialize before feeding the parser again.
306 : void chttp1_parser_release(chttp1_parser *parser);
307 :
308 : // Parsing
309 : //
310 : // Feeds len bytes of data to the parser and fires the callbacks; both modules
311 : // call it once per read. CHTTP1_OK always means the whole buffer was consumed
312 : // (partial lines and counts carry over between calls). After CHTTP1_PAUSED
313 : // don't feed this parser again; the bytes from chttp1_parser_consumed() to
314 : // len weren't consumed (a client drops them, a server keeps them for the next
315 : // pipelined request through chttp1_stream_push_back_leftover()).
316 : // CHTTP1_HEADERS_ONLY isn't terminal, and feeding more continues the body. It
317 : // gives OK, PAUSED, HEADERS_ONLY, USER or ERROR (see parser->reason).
318 : chttp1_errno chttp1_parser_execute(chttp1_parser *parser, const char *data,
319 : size_t len);
320 :
321 : // Tells whether an EOF from the connection ends the message validly; call it
322 : // when a read gives 0, because a response without framing ends only at EOF.
323 : // For an EOF-delimited body it fires on_message_complete and gives
324 : // CHTTP1_PAUSED. It gives CHTTP1_OK at a clean boundary, CHTTP1_ERROR when the
325 : // EOF cut a message, and CHTTP1_USER (parser dead) when on_message_complete
326 : // failed.
327 : chttp1_errno chttp1_parser_finish(chttp1_parser *parser);
328 :
329 : // Gives how many bytes of the last execute() buffer the message used, so the
330 : // caller knows where the next message or the body starts. Valid only right
331 : // after CHTTP1_PAUSED or CHTTP1_HEADERS_ONLY.
332 : size_t chttp1_parser_consumed(const chttp1_parser *parser);
333 :
334 : // Tells whether the whole message is parsed. A worker that continues a
335 : // request across a divert asks this instead of reading parser->state.
336 : bool chttp1_parser_message_complete(const chttp1_parser *parser);
337 :
338 : // Tells whether the connection may carry another message (RFC 7230 section
339 : // 6.3), which decides whether the caller pools or closes it. HTTP/1.1
340 : // defaults to yes, HTTP/1.0 to no unless Connection: keep-alive. A close token
341 : // wins for every version, on any line. An HTTP/1.0 message with
342 : // Transfer-Encoding (RFC 9112 section 6.1), a body only the close delimits and
343 : // a chttp1_parser_force_close() all give false. Valid once the message
344 : // completed.
345 : bool chttp1_should_keep_alive(const chttp1_parser *parser);
346 :
347 : // Makes chttp1_should_keep_alive() false for this message, as a close token
348 : // would. A caller that lost bytes of a pipelined next message calls it, so
349 : // the connection closes instead of waiting for data already sent. The next
350 : // init clears it; NULL is ignored.
351 : void chttp1_parser_force_close(chttp1_parser *parser);
352 :
353 : // Tells whether the headers hold exactly "Expect: 100-continue", so a server
354 : // can send "100 Continue" (or a final status) before reading the body. Any
355 : // other Expect value is the caller's to refuse, with 417 for example. Always
356 : // false for HTTP/1.0 (RFC 9110 section 10.1.1). Valid once
357 : // on_headers_complete fired. The parser sends nothing itself. A response
358 : // parser sees a 100 as a complete bodiless message, and the client parses the
359 : // final response with a new parser.
360 : bool chttp1_expects_continue(const chttp1_parser *parser);
361 :
362 : // Tells whether the merged Transfer-Encoding list names a coding other than
363 : // chunked. Only chunked is decoded, so a request with "gzip, chunked" would
364 : // deliver gzip bytes; a server that doesn't decode them answers 501 (RFC 9112
365 : // section 6.1), and the client fails such a response. Valid once
366 : // on_headers_complete fired.
367 : bool chttp1_has_other_transfer_coding(const chttp1_parser *parser);
368 :
369 : // Tells whether the headers set up Content-Length framing, so the caller can
370 : // check the declared size before it diverts or reads the body. Valid once
371 : // on_headers_complete fired; such a message carries no Transfer-Encoding,
372 : // since every combination of the two is refused earlier.
373 : bool chttp1_has_content_length(const chttp1_parser *parser);
374 :
375 : // Gives the declared Content-Length. chttpserver refuses an oversized
376 : // declaration with it at headers-complete, so a peer that never sends the
377 : // body can't hold a reader until a timeout. Valid only while
378 : // chttp1_has_content_length() is true and before the body parse starts (the
379 : // field counts down, and counts the current chunk for a chunked body). 0 for
380 : // NULL.
381 : uint64_t chttp1_declared_content_length(const chttp1_parser *parser);
382 :
383 : // Tells whether the last CHTTP1_ERROR was a chunk-size line above
384 : // max_chunk_size_override, so the caller can answer it as a body that's too
385 : // large (413) instead of a generic failure. False in every other case.
386 : bool chttp1_chunk_size_limit_exceeded(const chttp1_parser *parser);
387 :
388 : // Gives the body bytes the framing still guarantees: The rest of a
389 : // Content-Length body, the rest of the current chunk's data, and 0 on a
390 : // chunk-size line, a chunk CRLF, in the trailers and in every other state. A
391 : // server uses it as SO_RCVLOWAT, since a peer that follows its framing sends
392 : // that much before it waits for an answer.
393 : uint64_t chttp1_body_bytes_still_expected(const chttp1_parser *parser);
394 :
395 : // Tells whether the peer may still send bytes of this message. chttpserver
396 : // lingers before a close when it's true, because closing on unread input
397 : // makes the kernel send a reset that can destroy the response. False once the
398 : // message is complete and for a header block without body framing (even when
399 : // refused at on_headers_complete); true for an unfinished body (paused,
400 : // diverted or failed inside it) and before or after an error in the head,
401 : // where the framing is unknown. False for NULL.
402 : bool chttp1_request_bytes_may_remain(const chttp1_parser *parser);
403 :
404 : // Worker-pull body and response streaming
405 : //
406 : // A reactor-free helper that lets a worker thread read and write a connection
407 : // with an absolute timeout per call. It first delivers the carry-over bytes a
408 : // reactor thread read along with the headers. The usual flow: Parse the head
409 : // until CHTTP1_HEADERS_ONLY, hand the fd and the unconsumed bytes to a worker,
410 : // which prepares a stream with them and feeds chttp1_stream_read() output to
411 : // the same parser until CHTTP1_PAUSED. chttp1_stream_write() serves the
412 : // response phase.
413 : typedef struct chttp1_stream {
414 : int fd;
415 :
416 : // An opaque ctls_conn, or NULL for plain text. With it, reads and writes go
417 : // through ctls and fd serves only the poll(2) waits.
418 : void *tls;
419 :
420 : // A heap copy of the leftover bytes, drained through carry_pos before fd is
421 : // read. For TLS they're already decrypted.
422 : char *carry;
423 : size_t carry_len;
424 : size_t carry_pos;
425 :
426 : // The allocator of every stream buffer, the carry-over and what
427 : // chttp1_stream_take_leftover() hands out included (NULL for malloc), so a
428 : // server's custom allocator also covers diverted bodies.
429 : ccol_memmgmt_procs *mp;
430 :
431 : // errno of the last failed call, and whether that call failed by its deadline
432 : // (then last_errno means nothing).
433 : int last_errno;
434 : bool timed_out;
435 : bool prepared;
436 : bool released;
437 : // When true, writes never wait: A full socket counts as a timeout. For a
438 : // caller that waits for writability on its own reactor. Cleared by prepare;
439 : // no effect on reads.
440 : bool write_nonblocking;
441 : // The caller promises fd is non-blocking, so I/O is tried before any poll.
442 : // Cleared by prepare, because a plaintext read on a blocking fd must poll
443 : // first or it ignores the timeout. Plaintext writes use MSG_DONTWAIT either
444 : // way.
445 : bool fd_nonblocking;
446 : } chttp1_stream;
447 :
448 : // Prepares stream for a worker that reads a request body and writes the
449 : // response on fd, a connected stream socket. leftover (NULL when leftover_len
450 : // is 0) holds bytes the reactor already read off fd; they're copied and
451 : // delivered first. Writes use MSG_NOSIGNAL, so a gone peer gives EPIPE or
452 : // ECONNRESET and never SIGPIPE; a non-socket fails with ENOTSOCK. Call it
453 : // before another thread can touch fd. mp is kept until
454 : // chttp1_stream_release() and also frees what chttp1_stream_take_leftover()
455 : // returns. It gives false only when the copy can't be allocated; the stream is
456 : // then all zeros.
457 : bool chttp1_stream_prepare(chttp1_stream *stream, int fd, const char *leftover,
458 : size_t leftover_len, ccol_memmgmt_procs *mp);
459 :
460 : // Prepares stream like chttp1_stream_prepare(), for a TLS connection whose
461 : // handshake is done. I/O goes through ctls_conn_read() and ctls_conn_write();
462 : // fd is only polled, since ctls has no poll of its own. leftover is already
463 : // decrypted. The caller keeps ownership of tls_conn and destroys it after
464 : // chttp1_stream_release().
465 : bool chttp1_stream_prepare_tls(chttp1_stream *stream, int fd, void *tls_conn,
466 : const char *leftover, size_t leftover_len,
467 : ccol_memmgmt_procs *mp);
468 :
469 : // Reads up to buflen bytes into buf for a worker that pulls a body, waiting at
470 : // most timeout_ms (< 0 forever, 0 not at all). Carry-over comes first, without
471 : // touching fd. Then a TLS stream, or a plaintext one with fd_nonblocking,
472 : // tries a read before polling (OpenSSL may already hold decrypted bytes); a
473 : // plaintext stream on a possibly blocking fd polls first. After EAGAIN it
474 : // polls and retries within the same total timeout, so TLS records that yield
475 : // no application bytes are retried quietly. It gives the bytes read, 0 on a
476 : // clean EOF or close_notify, or -1 on an error or a timeout
477 : // (chttp1_stream_timed_out() tells which).
478 : ssize_t chttp1_stream_read(chttp1_stream *stream, char *buf, size_t buflen,
479 : int timeout_ms);
480 :
481 : // Tells whether carry-over bytes remain, which the next read returns without
482 : // touching fd, so a caller knows it needn't wait for readiness.
483 2471 : static inline bool chttp1_stream_has_carry(const chttp1_stream *stream) {
484 2471 : return stream->carry_pos < stream->carry_len;
485 : }
486 :
487 : // Writes up to len bytes of buf (encrypted for TLS) for a worker that sends a
488 : // response, polling for at most timeout_ms while the socket is full, so a slow
489 : // reader can't hold a worker without bound. It gives the bytes written, which
490 : // may be fewer than len, or -1 on an error or a timeout.
491 : ssize_t chttp1_stream_write(chttp1_stream *stream, const char *buf, size_t len,
492 : int timeout_ms);
493 :
494 : // The largest head plus body chttp1_stream_writev2() copies into one TLS
495 : // record (the plaintext limit of a record), so a response head and a small
496 : // body cost one encryption and one send.
497 : #define CHTTP1_TLS_COALESCE_LIMIT 16384
498 :
499 : // Writes a and then b as one write where it can; either may be empty. The
500 : // server sends a response head and body with it in one system call or one TLS
501 : // record. With fd_nonblocking it writes first and polls only after a full
502 : // socket, otherwise it polls first. Plaintext uses one sendmsg(2) with
503 : // MSG_NOSIGNAL. TLS copies both into one record when they fit
504 : // CHTTP1_TLS_COALESCE_LIMIT, otherwise it writes a and then tries b at once. A
505 : // TLS write that would block is retried by the next call with the unsent
506 : // rest. It gives the bytes written across a and b, or -1 on an error or a
507 : // timeout.
508 : ssize_t chttp1_stream_writev2(chttp1_stream *stream, const char *a, size_t alen,
509 : const char *b, size_t blen, int timeout_ms);
510 :
511 : // Tells whether the last read or write gave -1 because its deadline passed,
512 : // so the caller can tell a slow peer from a broken connection.
513 : bool chttp1_stream_timed_out(const chttp1_stream *stream);
514 :
515 : // Gives the errno of the last failed read or write, for the caller's error
516 : // handling; 0 after a success, a timeout or a read from the carry-over.
517 : int chttp1_stream_last_error(const chttp1_stream *stream);
518 :
519 : // Puts a copy of buf in front of the carry-over. A message can end before the
520 : // bytes just read do; those trailing bytes are the next pipelined request, and
521 : // this keeps them for chttp1_stream_take_leftover(). It gives false only when
522 : // the copy can't be allocated, and the carry-over stays as it was.
523 : bool chttp1_stream_push_back_leftover(chttp1_stream *stream, const char *buf,
524 : size_t len);
525 :
526 : // Hands the unread carry-over to the caller, so the server can parse the next
527 : // pipelined request from it. Call it once, right before
528 : // chttp1_stream_release(), or that request is lost. The buffer comes from the
529 : // stream's mp; free it with ccol__mem_free() and that mp. NULL with *len_out
530 : // 0 means nothing was left; NULL with *len_out above 0 means the copy failed,
531 : // those bytes are gone and the caller must close the connection. The
532 : // carry-over is empty afterwards.
533 : char *chttp1_stream_take_leftover(chttp1_stream *stream, size_t *len_out);
534 :
535 : // Frees the stream's carry-over when the worker is done with it. It never
536 : // closes fd. Call it once; it's safe on a zeroed stream and a second call
537 : // does nothing.
538 : void chttp1_stream_release(chttp1_stream *stream);
|