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 <arpa/inet.h>
26 : #include <chashmap.h>
27 : #include <chttpclient.h>
28 : #include <cthreadcomm.h>
29 : #include <cthreadpool.h>
30 : #include <ctype.h>
31 : #include <cvector.h>
32 : #include <errno.h>
33 : #include <fcntl.h>
34 : #include <internal/cascii.h>
35 : #include <internal/catfork.h>
36 : #include <internal/cdeadline.h>
37 : #include <internal/chashinsert.h>
38 : #include <internal/chttp1_parser.h>
39 : #include <internal/clogderive.h>
40 : #include <internal/cpintable.h>
41 : #include <internal/csock.h>
42 : #include <internal/cstrutil.h>
43 : #include <internal/ctls.h>
44 : #include <internal/test_helpers/chttpclient.h>
45 : #include <internal/test_helpers/common.h>
46 : #include <limits.h>
47 : #include <netdb.h>
48 : #include <netinet/in.h>
49 : #include <netinet/tcp.h>
50 : #include <openssl/ssl.h>
51 : #include <poll.h>
52 : #include <stdatomic.h>
53 : #include <stdio.h>
54 : #include <stdlib.h>
55 : #include <string.h>
56 : #include <sys/ioctl.h>
57 : #include <sys/socket.h>
58 : #include <sys/un.h>
59 : #include <time.h>
60 : #include <unistd.h>
61 :
62 : // Constants
63 : //
64 : // The most redirects one request follows (as in Go), and the caps of the
65 : // keep-alive idle pool, idle connections per origin and in total, so idle
66 : // sockets can't pile up.
67 : #define CHTTP_MAX_REDIRECTS 50
68 : #define CHTTP_MAX_IDLE_PER_ORIGIN 4
69 : #define CHTTP_MAX_IDLE_TOTAL 32
70 : // The most distinct origin keys the idle pool's map holds. A client that talks
71 : // to many hosts once each would otherwise keep a map entry for every origin it
72 : // ever saw. When the cap is full, a connection to a new origin simply isn't
73 : // pooled.
74 : #define CHTTP_MAX_IDLE_ORIGINS 128
75 : #ifdef RUNNING_UNIT_TESTS
76 : // A test sets a small value here, so it can hit the origin cap without 128 real
77 : // origins. 0 means the real constant.
78 : static _Atomic size_t g_max_idle_origins_override_for_tests = 0;
79 : #endif
80 : // Gives the origin cap in effect, so the pool code reads one value whether or
81 : // not a test set an override in g_max_idle_origins_override_for_tests.
82 573 : static size_t effective_max_idle_origins(void) {
83 : #ifdef RUNNING_UNIT_TESTS
84 573 : size_t override = atomic_load(&g_max_idle_origins_override_for_tests);
85 573 : if (override > 0) return override;
86 : #endif
87 : return CHTTP_MAX_IDLE_ORIGINS;
88 : }
89 : // How long an idle connection may sit in the pool before we drop it, since
90 : // servers close idle connections after a while and a stale one would fail the
91 : // next request.
92 : #define CHTTP_IDLE_MAX_AGE_MS 60000L
93 : // How long we wait for a "100 Continue" before sending the body anyway. It's
94 : // the default of curl's CURLOPT_EXPECT_100_TIMEOUT_MS.
95 : #define CHTTP_100_CONTINUE_WAIT_US UINT64_C(1000000)
96 : // Happy Eyeballs' Connection Attempt Delay (RFC 8305 section 5): With several
97 : // addresses, we start on the next one when the attempts in flight give no
98 : // result for this long. Go's net.Dialer uses the same value.
99 : #define CHTTP_CONNECT_ATTEMPT_DELAY_MS 250L
100 : #ifdef RUNNING_UNIT_TESTS
101 : // Hooks for the Happy Eyeballs tests. The first replaces the attempt delay.
102 : // While the second is above 0, each attempt delay that starts takes one from it
103 : // and lasts 1 ms. While the third is above 0, each Tier 1 attempt that
104 : // completes takes one from it and counts as ECONNREFUSED; a loopback connect
105 : // that completes inside connect(2) counts as in progress then, so the hook sees
106 : // it.
107 : static _Atomic long g_connect_attempt_delay_ms_for_tests = 0;
108 : static _Atomic int g_connect_short_delays_for_tests = 0;
109 : static _Atomic int g_connect_async_failures_for_tests = 0;
110 :
111 : // Set the three Happy Eyeballs hooks above, so a test can shape the attempt
112 : // timing and failures.
113 4 : void chttp__set_connect_attempt_delay_ms_for_tests(long ms) {
114 4 : atomic_store(&g_connect_attempt_delay_ms_for_tests, ms);
115 4 : }
116 :
117 2 : void chttp__set_connect_short_delays_for_tests(int n) {
118 2 : atomic_store(&g_connect_short_delays_for_tests, n);
119 2 : }
120 :
121 2 : void chttp__set_connect_async_failures_for_tests(int n) {
122 2 : atomic_store(&g_connect_async_failures_for_tests, n);
123 2 : }
124 :
125 : // Takes one from *counter if it's above 0 and tells whether it did. The
126 : // counting test hooks use it to fire a given number of times.
127 1128 : static bool take_one_for_tests(_Atomic int *counter) {
128 1128 : int v = atomic_load(counter);
129 1128 : while (v > 0)
130 2 : if (atomic_compare_exchange_weak(counter, &v, v - 1)) return true;
131 : return false;
132 : }
133 : #endif
134 :
135 : // Gives the attempt delay in effect, so every tier reads one value whether or
136 : // not a test replaced it through the hooks above.
137 598 : static inline long connect_attempt_delay_ms(void) {
138 : #ifdef RUNNING_UNIT_TESTS
139 1196 : if (take_one_for_tests(&g_connect_short_delays_for_tests)) return 1;
140 597 : long ms = atomic_load(&g_connect_attempt_delay_ms_for_tests);
141 597 : if (ms > 0) return ms;
142 : #endif
143 : return CHTTP_CONNECT_ATTEMPT_DELAY_MS;
144 : }
145 : // The most interim (1xx) responses chttp_read_message_loop throws away in one
146 : // message. Without a cap, a server that sends "103 Early Hints" forever would
147 : // hold the caller's thread and its limiter slot for good, since requests have
148 : // no timeout by default.
149 : #define CHTTP_MAX_INTERIM_RESPONSES 64
150 :
151 : // Internal types
152 : //
153 : // A parsed URL. Every string is an owned copy from the client's allocator. A
154 : // "http+unix://" URL fills is_unix and unix_socket_path and leaves host NULL
155 : // and port 0. origin_key ("scheme://host:port" or "unix://<path>") is the idle
156 : // pool's key and, for TCP, gives the SNI name.
157 : typedef struct {
158 : bool is_https;
159 : // host is an IPv6 literal without brackets, which is what connect() and TLS
160 : // want; the Host header, origin_key and a rebuilt URL add them back.
161 : bool is_ipv6;
162 : bool is_unix;
163 : char *unix_socket_path;
164 : char *host;
165 : uint16_t port;
166 : char *path_and_query;
167 : char *origin_key;
168 : // "Basic <b64>" from the "user:pass@" part of this URL, or NULL.
169 : char *userinfo_authorization;
170 : } chttp_url;
171 :
172 : // An absolute deadline; active == false means no limit.
173 : typedef struct {
174 : bool active;
175 : struct timespec deadline;
176 : } chttp_deadline;
177 :
178 : // One connection, the thing the idle pool holds. It's always kept by value (on
179 : // the stack, in the pool's cvector, or inside another object), so it never
180 : // costs a heap block of its own.
181 : typedef struct {
182 : int fd;
183 : ctls_conn *tls;
184 : char *origin_key;
185 : struct timespec last_used;
186 : // The client's tls_generation when this connection did its handshake. The
187 : // pool reuses a TLS connection only while it matches (see idle_pool_take).
188 : uint64_t tls_generation;
189 : // The inactivity timeout of the request this connection serves (0 for none),
190 : // and how long that request has waited since a byte last moved.
191 : uint64_t inactivity_us;
192 : uint64_t inactivity_waited_ns;
193 : } chttp_conn;
194 :
195 : // A growable buffer for a response body. max_size is the cap of
196 : // chttpcli_set_max_response_body_size (0 for none); the first append past it
197 : // sets too_large instead of growing, so an oversized body is cut off early.
198 : typedef struct {
199 : char *buf;
200 : size_t len;
201 : size_t cap;
202 : ccol_memmgmt_procs *mp;
203 : bool oom;
204 : size_t max_size;
205 : bool too_large;
206 : } chttp_bodybuf;
207 :
208 : // Every occurrence, in wire order, of each field name that appears more than
209 : // once in one response. data holds one record per occurrence: A
210 : // chttp_field_rec, then "name\0value\0" with the name lower-cased, padded to 4
211 : // bytes. The records of one name are chained through next, and index is an
212 : // open-addressing table with one slot per repeated name (first and last
213 : // record), so adding an occurrence and reading them all are linear. A response
214 : // with no repeated name allocates none of this.
215 : typedef struct {
216 : uint32_t name_len;
217 : uint32_t value_len;
218 : uint32_t next;
219 : } chttp_field_rec;
220 :
221 : // One index slot: The first and last record of a name's chain.
222 : typedef struct {
223 : uint32_t head;
224 : uint32_t tail;
225 : } chttp_field_slot;
226 :
227 : // The field-lines block of one response (see chttp_field_rec).
228 : typedef struct {
229 : size_t len;
230 : size_t cap;
231 : chttp_field_slot *index;
232 : size_t index_cap;
233 : size_t names;
234 : char data[];
235 : } chttp_field_lines;
236 :
237 : // The parse state of one response (one hop). Every hop of a redirect chain gets
238 : // a fresh one, so nothing from a redirect's headers leaks into the final
239 : // response.
240 : typedef struct {
241 : ccol_memmgmt_procs *mp;
242 : chmap headers;
243 : chttp_field_lines *field_lines;
244 :
245 : bool is_head_request;
246 : bool will_redirect;
247 : char *location;
248 :
249 : bool message_complete;
250 : bool trailing_garbage;
251 : bool error;
252 : bool aborted;
253 : bool too_large;
254 : int status_code;
255 :
256 : chttpcli_write_fn requested_sink_fn;
257 : void *requested_sink_ctx;
258 : chttpcli_write_fn sink_fn;
259 : void *sink_ctx;
260 : } chttp_parse_ctx;
261 :
262 : // Client handle slot table
263 : //
264 : // A chttpcli handle holds the slot index in its top 32 bits and the generation
265 : // in the bottom 32. Every call resolves the handle through this table before it
266 : // touches the client, so a double destroy or a destroy racing a call is a
267 : // ccol__fatal_err instead of a use-after-free.
268 : typedef struct {
269 : struct chttpclient *ptr;
270 : uint32_t generation;
271 : bool in_use;
272 : } chttpcli_slot;
273 :
274 : // The slots, guarded by lock. slots only grows, so an index never goes away;
275 : // free_indices is a LIFO list for reuse. When the exit destructor finds a live
276 : // client it leaves the table alone, and the destroy that releases the last slot
277 : // frees it later. lost_indices counts released indices that a failed push kept
278 : // off the free list.
279 : static struct {
280 : ccol__rw_lock rwlock;
281 : ccol__once_flag once;
282 : cvec slots;
283 : cvec free_indices;
284 : bool release_deferred;
285 : size_t lost_indices;
286 : } chttpcli_slot_table = {0};
287 :
288 : #ifdef RUNNING_UNIT_TESTS
289 : // When true, the next push onto free_indices acts as if its allocation failed.
290 : static _Atomic bool g_chttpcli_fail_next_free_index_push = false;
291 :
292 : // Arms g_chttpcli_fail_next_free_index_push, so a test can reach the lost-index
293 : // path without a real allocation failure.
294 9 : void chttpcli__force_next_free_index_push_failure_for_tests(void) {
295 9 : atomic_store(&g_chttpcli_fail_next_free_index_push, true);
296 9 : }
297 : #endif
298 :
299 : // Gives a released slot's index back for reuse, so the table doesn't grow on
300 : // every create. A failed push counts the index in lost_indices instead of
301 : // dropping it, for chttpcli_reclaim_lost_index_locked to find. The caller holds
302 : // the table's write lock.
303 2819 : static void chttpcli_free_index_release_locked(uint32_t idx) {
304 : #ifdef RUNNING_UNIT_TESTS
305 2819 : if (atomic_exchange(&g_chttpcli_fail_next_free_index_push, false)) {
306 9 : chttpcli_slot_table.lost_indices++;
307 9 : return;
308 : }
309 : #endif
310 2810 : if (cvector_push_back(chttpcli_slot_table.free_indices, &idx) != ccol_success)
311 0 : chttpcli_slot_table.lost_indices++;
312 : }
313 :
314 : // Finds one slot whose index a failed push stranded. The caller holds the write
315 : // lock and saw free_indices empty, which is what makes "ptr NULL and not in
316 : // use" mean lost. A scan that finds nothing zeroes the counter, so later
317 : // acquires don't scan again.
318 9 : static __attribute__((noinline)) bool chttpcli_reclaim_lost_index_locked(
319 : uint32_t *out_idx) {
320 9 : size_t slot_count = cvector_size(chttpcli_slot_table.slots);
321 18 : for (size_t i = 0; i < slot_count; i++) {
322 18 : chttpcli_slot *slot =
323 18 : (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, i);
324 18 : if (slot->ptr == NULL && !slot->in_use) {
325 9 : *out_idx = (uint32_t)i;
326 9 : chttpcli_slot_table.lost_indices--;
327 9 : return true;
328 : }
329 : }
330 0 : chttpcli_slot_table.lost_indices = 0;
331 0 : return false;
332 : }
333 :
334 : static bool chttpcli_any_slot_live_locked(void);
335 : static void chttpcli_release_slot_table_locked(void);
336 : static void chttpcli_release_slot_table_if_deferred_locked(void);
337 :
338 : // The hot half of the slot table: It maps a handle to a client pointer and
339 : // holds the pin that keeps the client alive during a call. A resolve runs on
340 : // every request and writes nothing other threads read.
341 : static ccol_pintable chttpcli_pintable;
342 :
343 : // Initializes the slot table's lock and pin table, once, from the first create
344 : // or resolve that needs them.
345 42 : static void chttpcli_slot_table_init_globals(void) {
346 42 : if (ccol__rw_lock_init(chttpcli_slot_table.rwlock) != 0)
347 0 : ccol__fatal_err("chttpcli slot table: failed to initialize rwlock");
348 42 : chttpcli_slot_table.slots = cvector_create(sizeof(chttpcli_slot), NULL);
349 42 : if (!chttpcli_slot_table.slots)
350 0 : ccol__fatal_err("chttpcli slot table: failed to allocate slots vector");
351 42 : chttpcli_slot_table.free_indices = cvector_create(sizeof(uint32_t), NULL);
352 42 : if (!chttpcli_slot_table.free_indices)
353 0 : ccol__fatal_err(
354 : "chttpcli slot table: failed to allocate free-index vector");
355 42 : }
356 :
357 : // The client behind a chttpcli handle. lock guards everything here except the
358 : // async counter, which has its own lock.
359 : struct chttpclient {
360 : ccol__mutex lock;
361 : // The concurrency limiter: At most pool_cap requests in flight.
362 : ccol__cond_var available;
363 :
364 : size_t pool_cap;
365 : size_t configured_pool_size;
366 : size_t in_flight_count;
367 : bool pool_initialized;
368 : bool destroying;
369 :
370 : // The Tier 1 idle pool, chmap(origin_key -> cvec of chttp_conn).
371 : chmap idle_pools;
372 : size_t idle_total_count;
373 :
374 : // The Tier 2 idle pool, chmap(origin_key -> cvec of chttp_async_ctx *), and
375 : // the condition destroy waits on until it's empty.
376 : chmap idle_pools_async;
377 : size_t idle_total_count_async;
378 : ccol__cond_var idle_async_drained;
379 :
380 : // Active Tier 2 and Tier 3 chains; destroy waits for the count to reach 0.
381 : ccol__mutex async_count_lock;
382 : ccol__cond_var async_count_drained;
383 : size_t async_in_flight_count;
384 :
385 : // Settings that requests copy when they start.
386 : uint64_t connect_timeout_us;
387 : uint64_t request_timeout_us;
388 : uint64_t inactivity_timeout_us;
389 : size_t max_response_body_size;
390 : chttp_tls_config tls;
391 : char *owned_cert_path;
392 : char *owned_key_path;
393 : char *owned_ca_bundle_path;
394 : // The TLS context, rebuilt by every chttpcli_set_tls. tls_ctx_usable is false
395 : // when a configured file couldn't be read or the last rebuild ran out of
396 : // memory; tls_ctx_oom makes the next request try that rebuild again.
397 : ctls_ctx *tls_ctx;
398 : bool tls_ctx_usable;
399 : bool tls_ctx_oom;
400 :
401 : ccol_memmgmt_procs *m_procs;
402 :
403 : chttpcli self_handle;
404 :
405 : // Bumped by every TLS change, so the pool never reuses a connection made
406 : // under an older policy.
407 : uint64_t tls_generation;
408 : };
409 :
410 : // One frame of the per-thread stack of clients with a request running on this
411 : // thread: A Tier 1 call for its whole length, or the write_fn of a streaming
412 : // Tier 2 or Tier 3 request on an engine thread. Frames live on the pusher's C
413 : // stack. chttpcli__destroy walks the stack, because destroying a client that
414 : // has a frame here would wait for this very call to end; it makes that a fatal
415 : // error instead. on_engine marks a frame pushed on an engine thread.
416 : typedef struct chttpcli_call_frame {
417 : const struct chttpclient *cli;
418 : struct chttpcli_call_frame *prev;
419 : bool on_engine;
420 : } chttpcli_call_frame;
421 :
422 : // The top of this thread's frame stack.
423 : static __thread chttpcli_call_frame *g_chttpcli_call_top = NULL;
424 :
425 : // Push and pop a call frame on this thread's stack, around a Tier 1 call or a
426 : // streaming write_fn, so chttpcli__destroy can spot a destroy from inside a
427 : // request of the same client.
428 659 : static inline void chttpcli_call_push(chttpcli_call_frame *f,
429 : const struct chttpclient *cli,
430 : bool on_engine) {
431 659 : f->cli = cli;
432 659 : f->prev = g_chttpcli_call_top;
433 659 : f->on_engine = on_engine;
434 659 : g_chttpcli_call_top = f;
435 : }
436 :
437 653 : static inline void chttpcli_call_pop(chttpcli_call_frame *f) {
438 653 : g_chttpcli_call_top = f->prev;
439 : }
440 :
441 : // Tells whether cli has a frame on this thread's stack. chttpcli__destroy uses
442 : // it to make a destroy from inside one of cli's own requests fatal instead of a
443 : // wait for itself.
444 2815 : static bool chttpcli_call_runs_on_this_thread(const struct chttpclient *cli) {
445 2818 : for (const chttpcli_call_frame *f = g_chttpcli_call_top; f; f = f->prev)
446 6 : if (f->cli == cli) return true;
447 : return false;
448 : }
449 :
450 : // Tells whether the calling thread is an engine thread running an application's
451 : // write_fn, the only application code that runs there. Destroy and
452 : // chttpcli_engine_wait use it, because waiting there would wait for the engine
453 : // itself.
454 5 : static bool chttpcli_runs_on_engine_thread(void) {
455 2818 : for (const chttpcli_call_frame *f = g_chttpcli_call_top; f; f = f->prev)
456 3 : if (f->on_engine) return true;
457 : return false;
458 : }
459 :
460 : // Client handle resolve and unpin
461 : //
462 : // Resolves h and pins the client so a concurrent destroy can't free it. It
463 : // gives NULL for 0, a garbage handle, a free slot or a reused one (the
464 : // generation doesn't match). On success the caller calls chttpcli_resolve_unpin
465 : // exactly once, as soon as its tier's own count protects the client. It takes
466 : // no lock and writes nothing shared, since every public call comes through
467 : // here.
468 2034 : static struct chttpclient *chttpcli_resolve(chttpcli h) {
469 2034 : return (struct chttpclient *)ccol_pintable_pin(&chttpcli_pintable, h);
470 : }
471 :
472 : // Drops the pin and nothing else, without the client's lock.
473 2018 : static void chttpcli_resolve_unpin(struct chttpclient *raw) {
474 2018 : ccol_pintable_unpin(&chttpcli_pintable, raw->self_handle);
475 : }
476 :
477 : // Gives cli a new or freed slot and returns its handle, or 0 when an allocation
478 : // fails. chttpcli_create_mp calls it once, after the client is fully built. It
479 : // refuses an index the pin table can't hold, skips the generation that would
480 : // make the handle equal CHTTPCLI_NULL, and sets self_handle before the publish.
481 2832 : static chttpcli chttpcli_handle_slot_acquire(struct chttpclient *cli) {
482 2832 : ccol__call_once(chttpcli_slot_table.once, chttpcli_slot_table_init_globals);
483 2832 : ccol__rw_lock_wrlock(chttpcli_slot_table.rwlock);
484 2832 : uint32_t idx;
485 2832 : chttpcli_slot *slot;
486 2832 : if (cvector_size(chttpcli_slot_table.free_indices) > 0) {
487 2779 : cvector_pop_back(chttpcli_slot_table.free_indices, &idx);
488 2779 : slot = (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, idx);
489 62 : } else if (chttpcli_slot_table.lost_indices > 0 &&
490 9 : chttpcli_reclaim_lost_index_locked(&idx)) {
491 9 : slot = (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, idx);
492 : } else {
493 44 : if (cvector_size(chttpcli_slot_table.slots) >= CCOL_PIN_MAX_SLOTS) {
494 0 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
495 0 : return 0;
496 : }
497 44 : chttpcli_slot fresh = {0};
498 44 : if (cvector_push_back(chttpcli_slot_table.slots, &fresh) != ccol_success) {
499 0 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
500 0 : return 0;
501 : }
502 44 : idx = (uint32_t)cvector_size(chttpcli_slot_table.slots) - 1;
503 44 : slot = (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, idx);
504 : }
505 2832 : slot->generation++;
506 2832 : if (slot->generation == 0) slot->generation++;
507 2832 : chttpcli h = ((chttpcli)idx << 32) | (chttpcli)slot->generation;
508 :
509 2832 : cli->self_handle = h;
510 :
511 2832 : if (!ccol_pintable_publish(&chttpcli_pintable, idx, slot->generation, cli)) {
512 9 : cli->self_handle = 0;
513 9 : chttpcli_free_index_release_locked(idx);
514 9 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
515 9 : return 0;
516 : }
517 :
518 2823 : slot->ptr = cli;
519 2823 : slot->in_use = true;
520 2823 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
521 2823 : return h;
522 : }
523 :
524 : // Default client
525 : //
526 : // The singleton behind chttp_default_client, created once and never
527 : // re-initialized. client is atomic so chttpcli__destroy can clear it with a
528 : // compare-and-swap when it's given this handle.
529 : static struct {
530 : _Atomic(chttpcli) client;
531 : ccol__once_flag once;
532 : } default_client_bundler = {0};
533 :
534 : // URL parsing
535 : //
536 : // Frees the strings of u, for every path that drops a parsed URL. mp is the
537 : // allocator they came from.
538 2736 : static void url_free(ccol_memmgmt_procs *mp, chttp_url *u) {
539 2736 : if (!u) return;
540 2736 : ccol__mem_free(mp, u->unix_socket_path);
541 351 : ccol__mem_free(mp, u->host);
542 351 : ccol__mem_free(mp, u->path_and_query);
543 351 : ccol__mem_free(mp, u->origin_key);
544 2736 : ccol__mem_free(mp, u->userinfo_authorization);
545 2736 : memset(u, 0, sizeof(*u));
546 : }
547 :
548 : // Percent-encodes len bytes of a unix socket path into a new string, for
549 : // rebuilding a "http+unix://<path>" URL (origin_key, a resolved redirect).
550 : // Every byte outside RFC 3986's unreserved set is escaped, '/' included,
551 : // because the whole path has to fit into one authority component. The length
552 : // comes in as a parameter so a test can reach the overflow guard.
553 4 : static char *percent_encode_unix_path_len(ccol_memmgmt_procs *mp,
554 : const char *path, size_t len) {
555 4 : static const char *unreserved =
556 : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
557 4 : if (len > (SIZE_MAX - 1) / 3) return NULL;
558 3 : char *out = (char *)ccol__mem_alloc(mp, len * 3 + 1);
559 3 : if (!out) return NULL;
560 : size_t w = 0;
561 59 : for (size_t i = 0; i < len; i++) {
562 56 : unsigned char c = (unsigned char)path[i];
563 56 : if (strchr(unreserved, (char)c)) {
564 49 : out[w++] = (char)c;
565 : } else {
566 7 : static const char *hex = "0123456789ABCDEF";
567 7 : out[w++] = '%';
568 7 : out[w++] = hex[(c >> 4) & 0xF];
569 7 : out[w++] = hex[c & 0xF];
570 : }
571 : }
572 3 : out[w] = '\0';
573 3 : return out;
574 : }
575 :
576 : // Percent-encodes a NUL-terminated unix socket path into a new string, for
577 : // building origin_key and redirect URLs of "http+unix://" targets. Gives NULL
578 : // when the allocation fails.
579 2 : static char *percent_encode_unix_path(ccol_memmgmt_procs *mp,
580 : const char *path) {
581 2 : return percent_encode_unix_path_len(mp, path, strlen(path));
582 : }
583 :
584 : #ifdef RUNNING_UNIT_TESTS
585 : // Lets a test drive the overflow guard of percent_encode_unix_path_len with a
586 : // made-up length. Call it only with fake_len above (SIZE_MAX - 1) / 3, so the
587 : // guard refuses the call before anything reads path.
588 2 : bool chttp__percent_encode_unix_path_overflow_guard_for_tests(
589 : ccol_memmgmt_procs *mp, const char *path, size_t fake_len) {
590 2 : char *r = percent_encode_unix_path_len(mp, path, fake_len);
591 2 : bool rejected = (r == NULL);
592 2 : ccol__mem_free(mp, r);
593 2 : return rejected;
594 : }
595 : #endif
596 :
597 : // Percent-decodes [start, start+len) into a new string. Only userinfo is
598 : // decoded; a malformed escape and an escaped NUL are refused, since a password
599 : // cut at a NUL would give a wrong Authorization header.
600 118 : static ccol_retval percent_decode_component(ccol_memmgmt_procs *mp,
601 : const char *start, size_t len,
602 : char **out) {
603 118 : char *buf = (char *)ccol__mem_alloc(mp, len + 1);
604 118 : if (!buf) return ccol_not_enough_memory;
605 : size_t w = 0;
606 2089 : for (size_t i = 0; i < len; i++) {
607 1974 : char c = start[i];
608 1974 : if (c == '%') {
609 158 : if (i + 2 >= len || !isxdigit((unsigned char)start[i + 1]) ||
610 157 : !isxdigit((unsigned char)start[i + 2])) {
611 1 : ccol__mem_free(mp, buf);
612 1 : return ccol_http_invalid_url;
613 : }
614 157 : char hex[3] = {start[i + 1], start[i + 2], '\0'};
615 157 : int v = (int)strtol(hex, NULL, 16);
616 157 : if (v == 0) {
617 0 : ccol__mem_free(mp, buf);
618 0 : return ccol_http_invalid_url;
619 : }
620 157 : buf[w++] = (char)v;
621 157 : i += 2;
622 : } else {
623 1816 : buf[w++] = c;
624 : }
625 : }
626 115 : buf[w] = '\0';
627 115 : *out = buf;
628 115 : return ccol_success;
629 : }
630 :
631 : // True for the bytes RFC 3986 allows as they are in a path or query
632 : // (unreserved, sub-delims, ':', '@', '/', '?'). The caller handles '%'.
633 68733 : static bool is_target_literal_byte(unsigned char c) {
634 68733 : if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
635 13734 : (c >= '0' && c <= '9'))
636 : return true;
637 12119 : return c != 0 && strchr("-._~!$&'()*+,;=:@/?", (int)c) != NULL;
638 : }
639 :
640 : // Builds the request-target "/path[?query]" from pq[0..pq_len), so the request
641 : // line is always valid RFC 3986 whatever bytes the caller's URL or a Location
642 : // holds. Every byte not allowed there becomes "%XX" (upper-case hex) and a
643 : // valid escape is kept. *out gets the new string from mp; a stray '%' is
644 : // ccol_http_invalid_url (as in Go's net/url), a failed allocation
645 : // ccol_not_enough_memory.
646 2819 : static ccol_retval build_request_target(ccol_memmgmt_procs *mp, const char *pq,
647 : size_t pq_len, char **out) {
648 2819 : *out = NULL;
649 2819 : bool add_slash = !(pq_len > 0 && pq[0] == '/');
650 2819 : size_t need = add_slash ? 1 : 0;
651 37241 : for (size_t i = 0; i < pq_len; i++) {
652 34426 : unsigned char c = (unsigned char)pq[i];
653 34426 : if (need > SIZE_MAX - 4) return ccol_not_enough_memory;
654 34426 : if (c == '%') {
655 23 : if (i + 2 >= pq_len || !isxdigit((unsigned char)pq[i + 1]) ||
656 19 : !isxdigit((unsigned char)pq[i + 2]))
657 : return ccol_http_invalid_url;
658 19 : need += 3;
659 19 : i += 2;
660 34403 : } else if (is_target_literal_byte(c)) {
661 34351 : need += 1;
662 : } else {
663 52 : need += 3;
664 : }
665 : }
666 2815 : char *t = (char *)ccol__mem_alloc(mp, need + 1);
667 2815 : if (!t) return ccol_not_enough_memory;
668 2804 : static const char hex[] = "0123456789ABCDEF";
669 2804 : size_t w = 0;
670 2804 : if (add_slash) t[w++] = '/';
671 37153 : for (size_t i = 0; i < pq_len; i++) {
672 34349 : unsigned char c = (unsigned char)pq[i];
673 34349 : if (c == '%') {
674 19 : t[w++] = '%';
675 19 : t[w++] = pq[i + 1];
676 19 : t[w++] = pq[i + 2];
677 19 : i += 2;
678 34330 : } else if (is_target_literal_byte(c)) {
679 34278 : t[w++] = (char)c;
680 : } else {
681 52 : t[w++] = '%';
682 52 : t[w++] = hex[c >> 4];
683 52 : t[w++] = hex[c & 0xF];
684 : }
685 : }
686 2804 : t[w] = '\0';
687 2804 : *out = t;
688 2804 : return ccol_success;
689 : }
690 :
691 : // Parses the authority of a "http+unix://" URL for parse_chttp_url. p points at
692 : // a percent-encoded path such as "%2Fvar%2Frun%2Fapp.sock" (the
693 : // requests-unixsocket convention); the decoded path goes into out. There's no
694 : // "https+unix://" and no userinfo, and a raw CR or LF is refused.
695 80 : static ccol_retval parse_chttp_unix_url(ccol_memmgmt_procs *mp, const char *p,
696 : chttp_url *out) {
697 80 : const char *authority_end = p;
698 2179 : while (*authority_end && *authority_end != '/' && *authority_end != '?' &&
699 : *authority_end != '#')
700 2099 : authority_end++;
701 80 : size_t enc_len = (size_t)(authority_end - p);
702 80 : if (enc_len == 0) return ccol_http_invalid_url;
703 :
704 79 : char *unix_path = NULL;
705 79 : ccol_retval drv = percent_decode_component(mp, p, enc_len, &unix_path);
706 79 : if (drv != ccol_success) return drv;
707 77 : if (unix_path[0] == '\0') {
708 0 : ccol__mem_free(mp, unix_path);
709 0 : return ccol_http_invalid_url;
710 : }
711 :
712 77 : const char *q = authority_end;
713 77 : const char *pq = (*q && *q != '#') ? q : "/";
714 77 : size_t pq_raw_len = strlen(pq);
715 77 : const char *frag = memchr(pq, '#', pq_raw_len);
716 77 : size_t pq_len = frag ? (size_t)(frag - pq) : pq_raw_len;
717 :
718 77 : if (memchr(pq, '\r', pq_len) || memchr(pq, '\n', pq_len)) {
719 1 : ccol__mem_free(mp, unix_path);
720 1 : return ccol_http_invalid_url;
721 : }
722 :
723 76 : char *path_and_query = NULL;
724 76 : ccol_retval trv = build_request_target(mp, pq, pq_len, &path_and_query);
725 76 : if (trv != ccol_success) {
726 2 : ccol__mem_free(mp, unix_path);
727 2 : return trv;
728 : }
729 :
730 74 : int needed = snprintf(NULL, 0, "unix://%s", unix_path);
731 74 : if (needed < 0) {
732 0 : ccol__mem_free(mp, unix_path);
733 0 : ccol__mem_free(mp, path_and_query);
734 0 : return ccol_unexpected_failure;
735 : }
736 74 : char *origin_key = (char *)ccol__mem_alloc(mp, (size_t)needed + 1);
737 74 : if (!origin_key) {
738 2 : ccol__mem_free(mp, unix_path);
739 2 : ccol__mem_free(mp, path_and_query);
740 2 : return ccol_not_enough_memory;
741 : }
742 72 : snprintf(origin_key, (size_t)needed + 1, "unix://%s", unix_path);
743 :
744 72 : out->is_https = false;
745 72 : out->is_ipv6 = false;
746 72 : out->is_unix = true;
747 72 : out->unix_socket_path = unix_path;
748 72 : out->host = NULL;
749 72 : out->port = 0;
750 72 : out->path_and_query = path_and_query;
751 72 : out->origin_key = origin_key;
752 72 : out->userinfo_authorization = NULL;
753 72 : return ccol_success;
754 : }
755 :
756 : // Gives an owned "[host]" for an IPv6 literal and a plain copy for any other
757 : // host, for the places where a host goes back into a URL string.
758 2806 : static char *format_bracketed_host(ccol_memmgmt_procs *mp, const char *host,
759 : bool is_ipv6) {
760 5590 : if (!is_ipv6) return ccol_strdup(mp, host);
761 22 : size_t hlen = strlen(host);
762 22 : if (hlen > SIZE_MAX - 3) return NULL;
763 22 : char *out = (char *)ccol__mem_alloc(mp, hlen + 3);
764 22 : if (!out) return NULL;
765 22 : out[0] = '[';
766 22 : memcpy(out + 1, host, hlen);
767 22 : out[hlen + 1] = ']';
768 22 : out[hlen + 2] = '\0';
769 22 : return out;
770 : }
771 :
772 : // Tells whether c is RFC 3986 unreserved or a sub-delim, in ASCII whatever the
773 : // locale, for the host and userinfo grammar checks.
774 25138 : static bool uri_unreserved_or_sub_delim(unsigned char c) {
775 25138 : if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
776 22971 : (c >= '0' && c <= '9'))
777 : return true;
778 7808 : switch (c) {
779 : case '-':
780 : case '.':
781 : case '_':
782 : case '~':
783 : case '!':
784 : case '$':
785 : case '&':
786 : case '\'':
787 : case '(':
788 : case ')':
789 : case '*':
790 : case '+':
791 : case ',':
792 : case ';':
793 : case '=':
794 : return true;
795 : default:
796 : return false;
797 : }
798 : }
799 :
800 : // Tells whether c is an ASCII hex digit, for the pct-encoded checks.
801 166 : static bool uri_hexdig(unsigned char c) {
802 166 : return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
803 : (c >= 'A' && c <= 'F');
804 : }
805 :
806 : // Checks that s[0..len) is a non-empty RFC 3986 reg-name (unreserved,
807 : // sub-delims, pct-encoded). parse_chttp_url refuses anything else, because such
808 : // a host would reach the Host header, the pool key, SNI and the resolver in a
809 : // form that recipients read differently. A non-ASCII name must come in its
810 : // punycode form.
811 2758 : static bool uri_reg_name_is_valid(const char *s, size_t len) {
812 2758 : if (len == 0) return false;
813 27590 : for (size_t i = 0; i < len; i++) {
814 24849 : unsigned char c = (unsigned char)s[i];
815 24849 : if (c == '%') {
816 5 : if (len - i < 3 || !uri_hexdig((unsigned char)s[i + 1]) ||
817 2 : !uri_hexdig((unsigned char)s[i + 2]))
818 : return false;
819 1 : i += 2;
820 1 : continue;
821 : }
822 24845 : if (!uri_unreserved_or_sub_delim(c)) return false;
823 : }
824 : return true;
825 : }
826 :
827 : // Whether s[0..len), the inside of an IP-literal's brackets, is an IPv6address
828 : // or IPvFuture. Zone IDs are refused. Only hex digits, ':' and '.' reach
829 : // inet_pton(), because macOS's inet_pton() accepts a zone suffix.
830 35 : static bool uri_ip_literal_is_valid(const char *s, size_t len) {
831 35 : if (len == 0) return false;
832 35 : if (s[0] == 'v' || s[0] == 'V') {
833 : size_t j = 1;
834 10 : while (j < len && uri_hexdig((unsigned char)s[j])) j++;
835 6 : if (j == 1 || j >= len || s[j] != '.') return false;
836 3 : j++;
837 3 : if (j >= len) return false;
838 17 : for (; j < len; j++) {
839 15 : unsigned char c = (unsigned char)s[j];
840 15 : if (!uri_unreserved_or_sub_delim(c) && c != ':') return false;
841 : }
842 : return true;
843 : }
844 29 : char text[INET6_ADDRSTRLEN];
845 29 : if (len >= sizeof(text)) return false;
846 179 : for (size_t j = 0; j < len; j++) {
847 155 : unsigned char c = (unsigned char)s[j];
848 231 : if (!uri_hexdig(c) && c != ':' && c != '.') return false;
849 : }
850 24 : memcpy(text, s, len);
851 24 : text[len] = '\0';
852 24 : struct in6_addr addr;
853 24 : return inet_pton(AF_INET6, text, &addr) == 1;
854 : }
855 :
856 : // Whether s[0..len) is RFC 3986 userinfo. A raw '@' is accepted too (we split
857 : // at the last '@', as Go does); a backslash is refused, since WHATWG readers
858 : // treat it as '/' and would find a different host.
859 27 : static bool uri_userinfo_is_valid(const char *s, size_t len) {
860 298 : for (size_t i = 0; i < len; i++) {
861 278 : unsigned char c = (unsigned char)s[i];
862 278 : if (!uri_unreserved_or_sub_delim(c) && c != ':' && c != '@' && c != '%')
863 : return false;
864 : }
865 : return true;
866 : }
867 :
868 : // Parses an "http://", "https://" or "http+unix://" URL into *out. Userinfo
869 : // becomes a ready "Basic <base64>" value, the host is checked against the RFC
870 : // 3986 grammar, an empty port means the scheme's default, and a fragment is
871 : // dropped (a client never sends one). The '@' and ':' delimiters are found in
872 : // the raw string before each part is decoded, and raw CR or LF anywhere is
873 : // refused, since it could inject header lines. Any failure is
874 : // ccol_http_invalid_url or ccol_not_enough_memory, and leaves *out empty.
875 2902 : static ccol_retval parse_chttp_url(ccol_memmgmt_procs *mp, const char *url,
876 : chttp_url *out) {
877 2902 : memset(out, 0, sizeof(*out));
878 2902 : if (!url) return ccol_http_invalid_url;
879 :
880 2902 : if (ccol_ascii_ncasecmp(url, "http+unix://", 12) == 0)
881 80 : return parse_chttp_unix_url(mp, url + 12, out);
882 :
883 2822 : bool https;
884 2822 : const char *p;
885 2822 : if (ccol_ascii_ncasecmp(url, "http://", 7) == 0) {
886 2400 : https = false;
887 2400 : p = url + 7;
888 422 : } else if (ccol_ascii_ncasecmp(url, "https://", 8) == 0) {
889 411 : https = true;
890 411 : p = url + 8;
891 : } else {
892 : return ccol_http_invalid_url;
893 : }
894 :
895 2811 : const char *authority_end = p;
896 43725 : while (*authority_end && *authority_end != '/' && *authority_end != '?' &&
897 : *authority_end != '#')
898 40914 : authority_end++;
899 :
900 : const char *last_at = NULL;
901 43725 : for (const char *s = p; s < authority_end; s++)
902 40914 : if (*s == '@') last_at = s;
903 :
904 2811 : char *userinfo_authorization = NULL;
905 2811 : const char *host_scan_start = p;
906 2811 : if (last_at) {
907 27 : if (!uri_userinfo_is_valid(p, (size_t)(last_at - p)))
908 8 : return ccol_http_invalid_url;
909 134 : const char *colon = NULL;
910 134 : for (const char *s = p; s < last_at; s++)
911 132 : if (*s == ':') {
912 : colon = s;
913 : break;
914 : }
915 20 : const char *user_start = p;
916 20 : size_t user_len = colon ? (size_t)(colon - p) : (size_t)(last_at - p);
917 20 : const char *pass_start = colon ? colon + 1 : last_at;
918 18 : size_t pass_len = colon ? (size_t)(last_at - colon - 1) : 0;
919 :
920 20 : char *user_dec = NULL, *pass_dec = NULL;
921 20 : ccol_retval drv =
922 20 : percent_decode_component(mp, user_start, user_len, &user_dec);
923 20 : if (drv == ccol_success)
924 19 : drv = percent_decode_component(mp, pass_start, pass_len, &pass_dec);
925 19 : if (drv != ccol_success) {
926 1 : ccol__mem_free(mp, user_dec);
927 1 : ccol__mem_free(mp, pass_dec);
928 1 : return drv;
929 : }
930 :
931 19 : if (strchr(user_dec, ':')) {
932 0 : ccol__mem_free(mp, user_dec);
933 0 : ccol__mem_free(mp, pass_dec);
934 0 : return ccol_http_invalid_url;
935 : }
936 :
937 19 : userinfo_authorization = chttp_basic_auth_mp(mp, user_dec, pass_dec);
938 19 : ccol__mem_free(mp, user_dec);
939 19 : ccol__mem_free(mp, pass_dec);
940 19 : if (!userinfo_authorization) return ccol_not_enough_memory;
941 :
942 19 : host_scan_start = last_at + 1;
943 : }
944 :
945 2803 : bool is_ipv6 = false;
946 2803 : const char *host_start;
947 2803 : const char *q;
948 2803 : if (*host_scan_start == '[') {
949 42 : const char *close = host_scan_start + 1;
950 269 : while (close < authority_end && *close != ']') close++;
951 42 : if (close >= authority_end) {
952 5 : ccol__mem_free(mp, userinfo_authorization);
953 5 : return ccol_http_invalid_url;
954 : }
955 37 : char after = close[1];
956 37 : if (after != '\0' && after != ':' && after != '/' && after != '?' &&
957 : after != '#') {
958 1 : ccol__mem_free(mp, userinfo_authorization);
959 1 : return ccol_http_invalid_url;
960 : }
961 : host_start = host_scan_start + 1;
962 : q = close;
963 : is_ipv6 = true;
964 : } else {
965 27648 : host_start = host_scan_start;
966 : q = host_scan_start;
967 27648 : while (*q && *q != ':' && *q != '/' && *q != '?' && *q != '#') q++;
968 : }
969 2797 : size_t host_len = (size_t)(q - host_start);
970 2797 : if (host_len == 0) {
971 4 : ccol__mem_free(mp, userinfo_authorization);
972 4 : return ccol_http_invalid_url;
973 : }
974 5551 : if (is_ipv6 ? !uri_ip_literal_is_valid(host_start, host_len)
975 2758 : : !uri_reg_name_is_valid(host_start, host_len)) {
976 31 : ccol__mem_free(mp, userinfo_authorization);
977 31 : return ccol_http_invalid_url;
978 : }
979 2762 : if (is_ipv6) q++;
980 :
981 2762 : uint16_t port = https ? 443 : 80;
982 2762 : if (*q == ':') {
983 2588 : q++;
984 2588 : unsigned long pv = 0;
985 2588 : size_t pd = 0;
986 15352 : while (*q && isdigit((unsigned char)*q)) {
987 12765 : pv = pv * 10 + (unsigned long)(*q - '0');
988 12765 : if (pv > 65535) {
989 1 : ccol__mem_free(mp, userinfo_authorization);
990 1 : return ccol_http_invalid_url;
991 : }
992 12764 : q++;
993 12764 : pd++;
994 : }
995 2587 : if (pd > 0 && pv == 0) {
996 2 : ccol__mem_free(mp, userinfo_authorization);
997 2 : return ccol_http_invalid_url;
998 : }
999 2585 : if (*q != '\0' && *q != '/' && *q != '?' && *q != '#') {
1000 3 : ccol__mem_free(mp, userinfo_authorization);
1001 3 : return ccol_http_invalid_url;
1002 : }
1003 2582 : if (pd > 0) port = (uint16_t)pv;
1004 : }
1005 :
1006 2756 : const char *pq = (*q && *q != '#') ? q : "/";
1007 2756 : size_t pq_raw_len = strlen(pq);
1008 2756 : const char *frag = memchr(pq, '#', pq_raw_len);
1009 2756 : size_t pq_len = frag ? (size_t)(frag - pq) : pq_raw_len;
1010 :
1011 2756 : if (memchr(pq, '\r', pq_len) || memchr(pq, '\n', pq_len)) {
1012 4 : ccol__mem_free(mp, userinfo_authorization);
1013 4 : return ccol_http_invalid_url;
1014 : }
1015 :
1016 2752 : char *host = (char *)ccol__mem_alloc(mp, host_len + 1);
1017 2752 : if (!host) {
1018 9 : ccol__mem_free(mp, userinfo_authorization);
1019 9 : return ccol_not_enough_memory;
1020 : }
1021 2743 : memcpy(host, host_start, host_len);
1022 2743 : host[host_len] = '\0';
1023 :
1024 2743 : char *path_and_query = NULL;
1025 2743 : ccol_retval trv = build_request_target(mp, pq, pq_len, &path_and_query);
1026 2743 : if (trv != ccol_success) {
1027 13 : ccol__mem_free(mp, host);
1028 13 : ccol__mem_free(mp, userinfo_authorization);
1029 13 : return trv;
1030 : }
1031 :
1032 2730 : char *bracketed_host = format_bracketed_host(mp, host, is_ipv6);
1033 2730 : if (!bracketed_host) {
1034 9 : ccol__mem_free(mp, host);
1035 9 : ccol__mem_free(mp, path_and_query);
1036 9 : ccol__mem_free(mp, userinfo_authorization);
1037 9 : return ccol_not_enough_memory;
1038 : }
1039 :
1040 2721 : int needed = snprintf(NULL, 0, "%s://%s:%u", https ? "https" : "http",
1041 : bracketed_host, (unsigned)port);
1042 2721 : if (needed < 0) {
1043 0 : ccol__mem_free(mp, host);
1044 0 : ccol__mem_free(mp, path_and_query);
1045 0 : ccol__mem_free(mp, bracketed_host);
1046 0 : ccol__mem_free(mp, userinfo_authorization);
1047 0 : return ccol_unexpected_failure;
1048 : }
1049 2721 : char *origin_key = (char *)ccol__mem_alloc(mp, (size_t)needed + 1);
1050 2721 : if (!origin_key) {
1051 9 : ccol__mem_free(mp, host);
1052 9 : ccol__mem_free(mp, path_and_query);
1053 9 : ccol__mem_free(mp, bracketed_host);
1054 9 : ccol__mem_free(mp, userinfo_authorization);
1055 9 : return ccol_not_enough_memory;
1056 : }
1057 2712 : snprintf(origin_key, (size_t)needed + 1, "%s://%s:%u",
1058 : https ? "https" : "http", bracketed_host, (unsigned)port);
1059 2712 : ccol__mem_free(mp, bracketed_host);
1060 62300 : for (char *c = origin_key; *c; c++)
1061 59655 : *c = (char)ccol_ascii_tolower((unsigned char)*c);
1062 :
1063 2712 : out->is_https = https;
1064 2712 : out->is_ipv6 = is_ipv6;
1065 2712 : out->host = host;
1066 2712 : out->port = port;
1067 2712 : out->path_and_query = path_and_query;
1068 2712 : out->origin_key = origin_key;
1069 2712 : out->userinfo_authorization = userinfo_authorization;
1070 2712 : return ccol_success;
1071 : }
1072 :
1073 : // RFC 3986 section 5.2.4 "Remove Dot Segments" on a path. It must never see the
1074 : // query, so the caller cuts that off first and adds it back.
1075 273 : static char *remove_dot_segments(ccol_memmgmt_procs *mp, const char *path) {
1076 273 : size_t len = strlen(path);
1077 273 : char *in = (char *)ccol__mem_alloc(mp, len + 1);
1078 273 : if (!in) return NULL;
1079 270 : memcpy(in, path, len + 1);
1080 270 : char *out = (char *)ccol__mem_alloc(mp, len + 1);
1081 270 : if (!out) {
1082 3 : ccol__mem_free(mp, in);
1083 3 : return NULL;
1084 : }
1085 : size_t out_len = 0;
1086 : char *p = in;
1087 653 : while (*p) {
1088 386 : if (strncmp(p, "../", 3) == 0) {
1089 0 : p += 3;
1090 386 : } else if (strncmp(p, "./", 2) == 0) {
1091 0 : p += 2;
1092 386 : } else if (strncmp(p, "/./", 3) == 0) {
1093 9 : p += 2;
1094 377 : } else if (strcmp(p, "/.") == 0) {
1095 2 : p[1] = '\0';
1096 375 : } else if (strncmp(p, "/../", 4) == 0) {
1097 27 : p += 3;
1098 58 : while (out_len > 0 && out[out_len - 1] != '/') out_len--;
1099 27 : if (out_len > 0) out_len--;
1100 348 : } else if (strcmp(p, "/..") == 0) {
1101 2 : p[1] = '\0';
1102 4 : while (out_len > 0 && out[out_len - 1] != '/') out_len--;
1103 2 : if (out_len > 0) out_len--;
1104 346 : } else if (strcmp(p, ".") == 0 || strcmp(p, "..") == 0) {
1105 0 : p += strlen(p);
1106 : } else {
1107 346 : const char *seg_start = p;
1108 346 : if (*p == '/') p++;
1109 3013 : while (*p && *p != '/') p++;
1110 346 : size_t seg_len = (size_t)(p - seg_start);
1111 346 : memcpy(out + out_len, seg_start, seg_len);
1112 346 : out_len += seg_len;
1113 : }
1114 : }
1115 267 : out[out_len] = '\0';
1116 267 : ccol__mem_free(mp, in);
1117 : return out;
1118 : }
1119 :
1120 : // Merges a reference path with the base path (RFC 3986 section 5.3) for
1121 : // resolve_redirect_url, on the path only; the caller adds the query back after
1122 : // the dot segments are removed. ref_path_len is a parameter so a test can reach
1123 : // the overflow guard. Gives a new string, or NULL on failure.
1124 37 : static char *merge_ref_path(ccol_memmgmt_procs *mp,
1125 : const char *base_path_and_query,
1126 : const char *ref_path, size_t ref_path_len) {
1127 37 : const char *base_query = strchr(base_path_and_query, '?');
1128 104 : size_t base_path_len = base_query ? (size_t)(base_query - base_path_and_query)
1129 37 : : strlen(base_path_and_query);
1130 :
1131 37 : size_t dir_len;
1132 37 : if (ref_path_len == 0) {
1133 : dir_len = base_path_len;
1134 : } else {
1135 : const char *last_slash = NULL;
1136 356 : for (size_t i = 0; i < base_path_len; i++)
1137 321 : if (base_path_and_query[i] == '/') last_slash = &base_path_and_query[i];
1138 35 : dir_len = last_slash ? (size_t)(last_slash - base_path_and_query) + 1 : 0;
1139 : }
1140 :
1141 37 : if (ref_path_len > SIZE_MAX - dir_len ||
1142 36 : dir_len + ref_path_len > SIZE_MAX - 1)
1143 : return NULL;
1144 36 : char *out = (char *)ccol__mem_alloc(mp, dir_len + ref_path_len + 1);
1145 36 : if (!out) return NULL;
1146 36 : memcpy(out, base_path_and_query, dir_len);
1147 36 : memcpy(out + dir_len, ref_path, ref_path_len);
1148 36 : out[dir_len + ref_path_len] = '\0';
1149 36 : return out;
1150 : }
1151 :
1152 : #ifdef RUNNING_UNIT_TESTS
1153 : // Lets a test drive the overflow guard of merge_ref_path with a made-up length.
1154 : // Call it only with a length above the guard's threshold.
1155 2 : bool chttp__merge_ref_path_overflow_guard_for_tests(
1156 : ccol_memmgmt_procs *mp, const char *base_path_and_query,
1157 : const char *ref_path, size_t fake_ref_path_len) {
1158 2 : char *r =
1159 2 : merge_ref_path(mp, base_path_and_query, ref_path, fake_ref_path_len);
1160 2 : bool rejected = (r == NULL);
1161 2 : ccol__mem_free(mp, r);
1162 2 : return rejected;
1163 : }
1164 : #endif
1165 :
1166 : // Joins a[0..a_len) and b[0..b_len) into a new string. The lengths are
1167 : // parameters so a test can reach the overflow guard.
1168 12 : static char *concat_len(ccol_memmgmt_procs *mp, const char *a, size_t a_len,
1169 : const char *b, size_t b_len) {
1170 12 : if (b_len > SIZE_MAX - a_len || a_len + b_len > SIZE_MAX - 1) return NULL;
1171 11 : char *out = (char *)ccol__mem_alloc(mp, a_len + b_len + 1);
1172 11 : if (!out) return NULL;
1173 11 : memcpy(out, a, a_len);
1174 11 : memcpy(out + a_len, b, b_len);
1175 11 : out[a_len + b_len] = '\0';
1176 11 : return out;
1177 : }
1178 :
1179 : #ifdef RUNNING_UNIT_TESTS
1180 : // Lets a test drive the overflow guard of concat_len. Call it only with lengths
1181 : // above the guard's threshold.
1182 2 : bool chttp__concat_len_overflow_guard_for_tests(ccol_memmgmt_procs *mp,
1183 : const char *a,
1184 : size_t fake_a_len,
1185 : const char *b,
1186 : size_t fake_b_len) {
1187 2 : char *r = concat_len(mp, a, fake_a_len, b, fake_b_len);
1188 2 : bool rejected = (r == NULL);
1189 2 : ccol__mem_free(mp, r);
1190 2 : return rejected;
1191 : }
1192 : #endif
1193 :
1194 : // True if s starts with an RFC 3986 "scheme ':'". A ':' after the first '/',
1195 : // '?' or '#' never ends a scheme. The character classes are written out by
1196 : // hand, so the locale doesn't matter.
1197 91 : static bool location_has_scheme(const char *s) {
1198 91 : int c0 = ccol_ascii_tolower((unsigned char)s[0]);
1199 91 : if (!(c0 >= 'a' && c0 <= 'z')) return false;
1200 48 : for (const char *p = s + 1;; p++) {
1201 48 : if (*p == ':') return true;
1202 42 : int c = ccol_ascii_tolower((unsigned char)*p);
1203 58 : if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' ||
1204 17 : c == '-' || c == '.'))
1205 : return false;
1206 : }
1207 : }
1208 :
1209 : // Removes the dot segments of the path of url, a reference with an authority
1210 : // (RFC 3986 section 5.2.2), for resolve_redirect_url. The authority, query and
1211 : // fragment are copied as they are. Gives a new string, or NULL when an
1212 : // allocation fails.
1213 208 : static char *normalize_authority_ref(ccol_memmgmt_procs *mp, const char *url) {
1214 208 : const char *auth = strstr(url, "//");
1215 208 : if (!auth) return ccol_strdup(mp, url);
1216 208 : const char *path = auth + 2;
1217 3238 : while (*path && *path != '/' && *path != '?' && *path != '#') path++;
1218 208 : size_t path_len = strcspn(path, "?#");
1219 211 : if (path_len == 0) return ccol_strdup(mp, url);
1220 205 : char *path_only = (char *)ccol__mem_alloc(mp, path_len + 1);
1221 205 : if (!path_only) return NULL;
1222 205 : memcpy(path_only, path, path_len);
1223 205 : path_only[path_len] = '\0';
1224 205 : char *clean = remove_dot_segments(mp, path_only);
1225 205 : ccol__mem_free(mp, path_only);
1226 205 : if (!clean) return NULL;
1227 205 : size_t prefix_len = (size_t)(path - url);
1228 205 : size_t clean_len = strlen(clean);
1229 205 : const char *rest = path + path_len;
1230 205 : size_t rest_len = strlen(rest);
1231 205 : char *out =
1232 205 : (char *)ccol__mem_alloc(mp, prefix_len + clean_len + rest_len + 1);
1233 205 : if (out) {
1234 205 : memcpy(out, url, prefix_len);
1235 205 : memcpy(out + prefix_len, clean, clean_len);
1236 205 : memcpy(out + prefix_len + clean_len, rest, rest_len + 1);
1237 : }
1238 205 : ccol__mem_free(mp, clean);
1239 : return out;
1240 : }
1241 :
1242 : // Resolves a Location value against the hop's URL (RFC 3986 sections 5.2 and
1243 : // 5.3), so any non-empty Location gives some absolute URL, as in a browser or
1244 : // curl. A reference with an unknown scheme is absolute and is refused later by
1245 : // the transport check. On NULL, *rv_out is ccol_http_transfer_aborted for a
1246 : // NULL or empty location and ccol_not_enough_memory for a failed allocation (an
1247 : // overflowing size counts as one).
1248 295 : static char *resolve_redirect_url_impl(ccol_memmgmt_procs *mp,
1249 : const chttp_url *base,
1250 : const char *location,
1251 : ccol_retval *rv_out) {
1252 295 : if (!location || !*location) {
1253 0 : *rv_out = ccol_http_transfer_aborted;
1254 0 : return NULL;
1255 : }
1256 295 : *rv_out = ccol_not_enough_memory;
1257 295 : if (ccol_ascii_ncasecmp(location, "http://", 7) == 0 ||
1258 116 : ccol_ascii_ncasecmp(location, "https://", 8) == 0 ||
1259 109 : ccol_ascii_ncasecmp(location, "http+unix://", 12) == 0) {
1260 204 : return normalize_authority_ref(mp, location);
1261 : }
1262 97 : if (location_has_scheme(location)) return ccol_strdup(mp, location);
1263 :
1264 85 : const char *scheme = base->is_https ? "https" : "http";
1265 :
1266 85 : if (location[0] == '/' && location[1] == '/') {
1267 4 : int needed = snprintf(NULL, 0, "%s:%s", scheme, location);
1268 4 : if (needed < 0) return NULL;
1269 4 : char *out = (char *)ccol__mem_alloc(mp, (size_t)needed + 1);
1270 4 : if (!out) return NULL;
1271 4 : snprintf(out, (size_t)needed + 1, "%s:%s", scheme, location);
1272 4 : char *clean = normalize_authority_ref(mp, out);
1273 4 : ccol__mem_free(mp, out);
1274 4 : return clean;
1275 : }
1276 :
1277 81 : const char *frag = strchr(location, '#');
1278 81 : size_t loc_len_nf = frag ? (size_t)(frag - location) : strlen(location);
1279 81 : char *location_nf = (char *)ccol__mem_alloc(mp, loc_len_nf + 1);
1280 81 : if (!location_nf) return NULL;
1281 78 : memcpy(location_nf, location, loc_len_nf);
1282 78 : location_nf[loc_len_nf] = '\0';
1283 78 : location = location_nf;
1284 :
1285 156 : char *authority = base->is_unix
1286 2 : ? percent_encode_unix_path(mp, base->unix_socket_path)
1287 78 : : format_bracketed_host(mp, base->host, base->is_ipv6);
1288 78 : if (!authority) {
1289 3 : ccol__mem_free(mp, location_nf);
1290 3 : return NULL;
1291 : }
1292 :
1293 150 : bool default_port =
1294 75 : !base->is_unix && ((base->is_https && base->port == 443) ||
1295 71 : (!base->is_https && base->port == 80));
1296 :
1297 75 : if (loc_len_nf == 0) {
1298 2 : ccol__mem_free(mp, location_nf);
1299 2 : const char *out_scheme0 = base->is_unix ? "http+unix" : scheme;
1300 2 : int needed0;
1301 2 : if (base->is_unix || default_port) {
1302 2 : needed0 = snprintf(NULL, 0, "%s://%s%s", out_scheme0, authority,
1303 2 : base->path_and_query);
1304 : } else {
1305 0 : needed0 = snprintf(NULL, 0, "%s://%s:%u%s", out_scheme0, authority,
1306 0 : (unsigned)base->port, base->path_and_query);
1307 : }
1308 2 : if (needed0 < 0) {
1309 0 : ccol__mem_free(mp, authority);
1310 0 : return NULL;
1311 : }
1312 2 : char *out0 = (char *)ccol__mem_alloc(mp, (size_t)needed0 + 1);
1313 2 : if (!out0) {
1314 0 : ccol__mem_free(mp, authority);
1315 0 : return NULL;
1316 : }
1317 2 : if (base->is_unix || default_port) {
1318 2 : snprintf(out0, (size_t)needed0 + 1, "%s://%s%s", out_scheme0, authority,
1319 2 : base->path_and_query);
1320 : } else {
1321 0 : snprintf(out0, (size_t)needed0 + 1, "%s://%s:%u%s", out_scheme0,
1322 0 : authority, (unsigned)base->port, base->path_and_query);
1323 : }
1324 2 : ccol__mem_free(mp, authority);
1325 2 : return out0;
1326 : }
1327 :
1328 73 : const char *ref_query = strchr(location, '?');
1329 146 : size_t ref_path_len =
1330 73 : ref_query ? (size_t)(ref_query - location) : strlen(location);
1331 :
1332 73 : char *new_path = NULL;
1333 73 : if (location[0] == '/') {
1334 38 : char *path_only = (char *)ccol__mem_alloc(mp, ref_path_len + 1);
1335 38 : if (path_only) {
1336 35 : memcpy(path_only, location, ref_path_len);
1337 35 : path_only[ref_path_len] = '\0';
1338 35 : new_path = remove_dot_segments(mp, path_only);
1339 35 : ccol__mem_free(mp, path_only);
1340 : }
1341 35 : } else if (ref_path_len == 0) {
1342 2 : new_path = merge_ref_path(mp, base->path_and_query, location, 0);
1343 : } else {
1344 33 : char *merged =
1345 33 : merge_ref_path(mp, base->path_and_query, location, ref_path_len);
1346 33 : if (merged) {
1347 33 : new_path = remove_dot_segments(mp, merged);
1348 33 : ccol__mem_free(mp, merged);
1349 : }
1350 : }
1351 73 : if (new_path && ref_query) {
1352 10 : char *with_query = concat_len(mp, new_path, strlen(new_path), ref_query,
1353 : strlen(ref_query));
1354 10 : if (!with_query) {
1355 0 : ccol__mem_free(mp, new_path);
1356 : new_path = NULL;
1357 : } else {
1358 10 : ccol__mem_free(mp, new_path);
1359 : new_path = with_query;
1360 : }
1361 : }
1362 73 : if (!new_path) {
1363 9 : ccol__mem_free(mp, authority);
1364 9 : ccol__mem_free(mp, location_nf);
1365 9 : return NULL;
1366 : }
1367 :
1368 64 : const char *out_scheme = base->is_unix ? "http+unix" : scheme;
1369 64 : int needed;
1370 64 : if (base->is_unix) {
1371 2 : needed = snprintf(NULL, 0, "%s://%s%s", out_scheme, authority, new_path);
1372 62 : } else if (default_port) {
1373 38 : needed = snprintf(NULL, 0, "%s://%s%s", out_scheme, authority, new_path);
1374 : } else {
1375 24 : needed = snprintf(NULL, 0, "%s://%s:%u%s", out_scheme, authority,
1376 24 : (unsigned)base->port, new_path);
1377 : }
1378 64 : if (needed < 0) {
1379 0 : ccol__mem_free(mp, authority);
1380 0 : ccol__mem_free(mp, new_path);
1381 0 : ccol__mem_free(mp, location_nf);
1382 0 : return NULL;
1383 : }
1384 64 : char *out = (char *)ccol__mem_alloc(mp, (size_t)needed + 1);
1385 64 : if (!out) {
1386 3 : ccol__mem_free(mp, authority);
1387 3 : ccol__mem_free(mp, new_path);
1388 3 : ccol__mem_free(mp, location_nf);
1389 3 : return NULL;
1390 : }
1391 61 : if (base->is_unix || default_port) {
1392 40 : snprintf(out, (size_t)needed + 1, "%s://%s%s", out_scheme, authority,
1393 : new_path);
1394 : } else {
1395 21 : snprintf(out, (size_t)needed + 1, "%s://%s:%u%s", out_scheme, authority,
1396 21 : (unsigned)base->port, new_path);
1397 : }
1398 61 : ccol__mem_free(mp, authority);
1399 3 : ccol__mem_free(mp, new_path);
1400 61 : ccol__mem_free(mp, location_nf);
1401 : return out;
1402 : }
1403 :
1404 : #ifdef RUNNING_UNIT_TESTS
1405 : // Set while this thread runs resolve_redirect_url, so a test allocator can fail
1406 : // exactly the allocations of the redirect resolution, on any tier and thread.
1407 : static __thread bool g_chttp_in_redirect_resolve;
1408 : // Tells a test allocator whether the calling thread is resolving a redirect, so
1409 : // it can fail exactly those allocations.
1410 574 : bool chttp__in_redirect_resolve_for_tests(void) {
1411 574 : return g_chttp_in_redirect_resolve;
1412 : }
1413 : #endif
1414 :
1415 : // Resolves location against base for every tier's redirect handling, through
1416 : // resolve_redirect_url_impl, and sets g_chttp_in_redirect_resolve around the
1417 : // call for the tests. Read *rv_out only when the result is NULL.
1418 295 : static char *resolve_redirect_url(ccol_memmgmt_procs *mp, const chttp_url *base,
1419 : const char *location, ccol_retval *rv_out) {
1420 : #ifdef RUNNING_UNIT_TESTS
1421 295 : g_chttp_in_redirect_resolve = true;
1422 590 : char *r = resolve_redirect_url_impl(mp, base, location, rv_out);
1423 295 : g_chttp_in_redirect_resolve = false;
1424 295 : return r;
1425 : #else
1426 : return resolve_redirect_url_impl(mp, base, location, rv_out);
1427 : #endif
1428 : }
1429 :
1430 : // Decides whether we may fetch a resolved redirect target over the transport it
1431 : // names. A redirect never adds the AF_UNIX transport and never points it at
1432 : // another socket, since that would let any server reach every local socket of
1433 : // the process. An https to http downgrade is refused only when the request set
1434 : // prevent_tls_downgrade_on_redirect, because curl and Go follow it by default.
1435 : // A target that can't be parsed for lack of memory gives
1436 : // ccol_not_enough_memory, never an approval.
1437 245 : static ccol_retval redirect_transport_allowed(ccol_memmgmt_procs *mp,
1438 : const chttp_url *base,
1439 : const char *next_url,
1440 : bool prevent_downgrade) {
1441 245 : if (ccol_ascii_ncasecmp(next_url, "http+unix://", 12) != 0) {
1442 217 : if (!prevent_downgrade || !base->is_https) return ccol_success;
1443 18 : chttp_url next;
1444 18 : ccol_retval prv = parse_chttp_url(mp, next_url, &next);
1445 18 : if (prv == ccol_not_enough_memory) return prv;
1446 10 : if (prv != ccol_success) return ccol_success;
1447 10 : bool allowed = next.is_https;
1448 10 : url_free(mp, &next);
1449 10 : return allowed ? ccol_success : ccol_http_invalid_url;
1450 : }
1451 28 : if (!base->is_unix || !base->unix_socket_path) return ccol_http_invalid_url;
1452 17 : chttp_url next;
1453 17 : ccol_retval prv = parse_chttp_url(mp, next_url, &next);
1454 17 : if (prv == ccol_not_enough_memory) return prv;
1455 11 : if (prv != ccol_success) return ccol_success;
1456 11 : bool allowed = next.is_unix && next.unix_socket_path &&
1457 11 : strcmp(next.unix_socket_path, base->unix_socket_path) == 0;
1458 11 : url_free(mp, &next);
1459 11 : return allowed ? ccol_success : ccol_http_invalid_url;
1460 : }
1461 :
1462 : #ifdef RUNNING_UNIT_TESTS
1463 : // Runs redirect_transport_allowed with the caller's allocator, so a test can
1464 : // fail each of its allocations; the base URL is parsed with plain malloc.
1465 18 : ccol_retval chttp__redirect_transport_check_for_tests(ccol_memmgmt_procs *mp,
1466 : const char *base_url,
1467 : const char *next_url,
1468 : bool prevent_downgrade) {
1469 18 : chttp_url base;
1470 18 : ccol_retval rv = parse_chttp_url(NULL, base_url, &base);
1471 18 : if (rv != ccol_success) return rv;
1472 18 : rv = redirect_transport_allowed(mp, &base, next_url, prevent_downgrade);
1473 18 : url_free(NULL, &base);
1474 18 : return rv;
1475 : }
1476 : #endif
1477 :
1478 : #ifdef RUNNING_UNIT_TESTS
1479 : // Let a test call parse_chttp_url, resolve_redirect_url and the transport
1480 : // check. chttp_url is private to this file, so they flatten the result into out
1481 : // parameters or a string, which the test frees with plain free().
1482 102 : ccol_retval chttp__parse_url_for_tests(
1483 : const char *url, bool *is_https_out, bool *is_ipv6_out, char **host_out,
1484 : uint16_t *port_out, char **path_and_query_out, char **origin_key_out,
1485 : char **userinfo_authorization_out, bool *is_unix_out,
1486 : char **unix_socket_path_out) {
1487 102 : ccol_memmgmt_procs *mp = NULL;
1488 102 : chttp_url parsed;
1489 102 : ccol_retval rv = parse_chttp_url(mp, url, &parsed);
1490 102 : if (rv != ccol_success) return rv;
1491 47 : if (is_https_out) *is_https_out = parsed.is_https;
1492 47 : if (is_ipv6_out) *is_ipv6_out = parsed.is_ipv6;
1493 47 : if (port_out) *port_out = parsed.port;
1494 47 : if (is_unix_out) *is_unix_out = parsed.is_unix;
1495 47 : if (unix_socket_path_out)
1496 16 : *unix_socket_path_out = parsed.unix_socket_path;
1497 : else
1498 31 : ccol__mem_free(mp, parsed.unix_socket_path);
1499 47 : if (host_out)
1500 30 : *host_out = parsed.host;
1501 : else
1502 17 : ccol__mem_free(mp, parsed.host);
1503 47 : if (path_and_query_out)
1504 38 : *path_and_query_out = parsed.path_and_query;
1505 : else
1506 9 : ccol__mem_free(mp, parsed.path_and_query);
1507 47 : if (origin_key_out)
1508 35 : *origin_key_out = parsed.origin_key;
1509 : else
1510 12 : ccol__mem_free(mp, parsed.origin_key);
1511 47 : if (userinfo_authorization_out)
1512 24 : *userinfo_authorization_out = parsed.userinfo_authorization;
1513 : else
1514 23 : ccol__mem_free(mp, parsed.userinfo_authorization);
1515 : return ccol_success;
1516 : }
1517 :
1518 50 : char *chttp__resolve_redirect_url_for_tests(const char *base_url,
1519 : const char *location) {
1520 50 : ccol_memmgmt_procs *mp = NULL;
1521 50 : chttp_url base;
1522 50 : ccol_retval rv = parse_chttp_url(mp, base_url, &base);
1523 50 : if (rv != ccol_success) return NULL;
1524 50 : ccol_retval rrv;
1525 50 : char *result = resolve_redirect_url(mp, &base, location, &rrv);
1526 50 : url_free(mp, &base);
1527 50 : return result;
1528 : }
1529 :
1530 29 : bool chttp__redirect_transport_allowed_for_tests(const char *base_url,
1531 : const char *location,
1532 : bool prevent_downgrade,
1533 : char **resolved_out) {
1534 29 : ccol_memmgmt_procs *mp = NULL;
1535 29 : chttp_url base;
1536 29 : if (resolved_out) *resolved_out = NULL;
1537 29 : ccol_retval rv = parse_chttp_url(mp, base_url, &base);
1538 29 : if (rv != ccol_success) return false;
1539 29 : ccol_retval rrv;
1540 29 : char *resolved = resolve_redirect_url(mp, &base, location, &rrv);
1541 58 : bool allowed =
1542 29 : resolved && redirect_transport_allowed(mp, &base, resolved,
1543 : prevent_downgrade) == ccol_success;
1544 29 : url_free(mp, &base);
1545 29 : if (resolved_out) {
1546 29 : *resolved_out = resolved;
1547 : } else {
1548 0 : ccol__mem_free(mp, resolved);
1549 : }
1550 : return allowed;
1551 : }
1552 : #endif
1553 :
1554 : // Request lifecycle
1555 : //
1556 : // Copies url, the body and its content type into a new request. CHTTP_ANY, a
1557 : // value outside the enum, and a NULL body->data with a non-zero length are
1558 : // refused, because none of them describes a request a server can read.
1559 1470 : chttp_request *chttp_request_create_mp(chttp_method method, const char *url,
1560 : const chttp_request_body *body,
1561 : ccol_memmgmt_procs *mprocs,
1562 : char **err_str) {
1563 1470 : if (!url) {
1564 1 : if (err_str) *err_str = CCOL__ERR_STR("url must not be NULL");
1565 1 : return NULL;
1566 : }
1567 1469 : if ((unsigned)method >= (unsigned)CHTTP_ANY) {
1568 2 : if (err_str)
1569 1 : *err_str = CCOL__ERR_STR("method must name a real HTTP method");
1570 2 : return NULL;
1571 : }
1572 1467 : if (body && !body->data && body->len > 0) {
1573 1 : if (err_str)
1574 1 : *err_str =
1575 : CCOL__ERR_STR("body->data must not be NULL when body->len > 0");
1576 1 : return NULL;
1577 : }
1578 1466 : if (mprocs && !ccol__verify_memmgmt_procs(mprocs, err_str)) return NULL;
1579 :
1580 1466 : ccol_memmgmt_procs *mp = NULL;
1581 1466 : if (mprocs) {
1582 81 : mp = (ccol_memmgmt_procs *)mprocs->malloc(sizeof(ccol_memmgmt_procs));
1583 81 : if (!mp) {
1584 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to allocate mprocs");
1585 1 : return NULL;
1586 : }
1587 80 : memcpy(mp, mprocs, sizeof(ccol_memmgmt_procs));
1588 : }
1589 :
1590 2930 : chttp_request *req =
1591 1465 : (chttp_request *)ccol__mem_alloc(mp, sizeof(chttp_request));
1592 1465 : if (!req) {
1593 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to allocate request");
1594 1 : if (mp) mp->free(mp);
1595 1 : return NULL;
1596 : }
1597 1464 : memset(req, 0, sizeof(*req));
1598 1464 : req->method = method;
1599 1464 : req->ccol__m_procs = mp;
1600 :
1601 1464 : req->url = ccol_strdup(mp, url);
1602 1464 : if (!req->url) {
1603 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to copy url");
1604 1 : ccol__mem_free(mp, req);
1605 1 : if (mp) mp->free(mp);
1606 1 : return NULL;
1607 : }
1608 :
1609 1463 : if (body && body->data && body->len > 0) {
1610 194 : void *body_copy = ccol__mem_alloc(mp, body->len);
1611 194 : if (!body_copy) {
1612 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to copy body");
1613 1 : ccol__mem_free(mp, req->url);
1614 1 : ccol__mem_free(mp, req);
1615 1 : if (mp) mp->free(mp);
1616 1 : return NULL;
1617 : }
1618 193 : memcpy(body_copy, body->data, body->len);
1619 193 : req->body.data = body_copy;
1620 193 : req->body.len = body->len;
1621 : }
1622 :
1623 201 : if (body && body->content_type) {
1624 193 : req->body.content_type = ccol_strdup(mp, body->content_type);
1625 193 : if (!req->body.content_type) {
1626 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to copy content_type");
1627 1 : ccol__mem_free(mp, (void *)req->body.data);
1628 1 : ccol__mem_free(mp, req->url);
1629 1 : ccol__mem_free(mp, req);
1630 1 : if (mp) mp->free(mp);
1631 1 : return NULL;
1632 : }
1633 : }
1634 :
1635 : return req;
1636 : }
1637 :
1638 : // The size of the stack buffer for a lower-cased header name. Real field names
1639 : // fit, so a header lookup allocates nothing.
1640 : enum { CHTTP_NAME_STACK_BUF = 128 };
1641 : // Lower-cases name (NUL included) into stack_buf when it fits, else into a
1642 : // buffer from mp, for the header setter and lookups, which store and find names
1643 : // in lower case. Sets *len_out to its length. Gives the buffer, or NULL when
1644 : // the allocation fails; a result other than stack_buf is freed through mp by
1645 : // the caller.
1646 482 : static char *lower_name_copy(ccol_memmgmt_procs *mp, const char *name,
1647 : char *stack_buf, size_t *len_out) {
1648 482 : size_t nlen = strlen(name);
1649 482 : char *lower = stack_buf;
1650 482 : if (nlen >= CHTTP_NAME_STACK_BUF) {
1651 4 : lower = (char *)ccol__mem_alloc(mp, nlen + 1);
1652 4 : if (!lower) return NULL;
1653 : }
1654 5820 : for (size_t i = 0; i <= nlen; i++)
1655 6099 : lower[i] = (char)ccol_ascii_tolower((unsigned char)name[i]);
1656 482 : *len_out = nlen;
1657 482 : return lower;
1658 : }
1659 :
1660 : // Tells whether every byte of a field value is a field-vchar, a space or a tab
1661 : // (RFC 9110 section 5.5). The header setter, the serializer and the content
1662 : // type check use it, because CR and LF would split the request and other
1663 : // control bytes make recipients read it differently.
1664 : static bool header_value_is_valid(const char *v) {
1665 8525 : for (const unsigned char *p = (const unsigned char *)v; *p; p++)
1666 7850 : if ((*p < 0x20 && *p != '\t') || *p == 0x7F) return false;
1667 : return true;
1668 : }
1669 :
1670 : // Stores a header, replacing an earlier value of the same name. The name must
1671 : // be a token and the value must pass header_value_is_valid, since the
1672 : // serializer writes both as they are. Transfer-Encoding is refused, because we
1673 : // have no transfer coding for a request body.
1674 136 : ccol_retval chttp_request_set_header(chttp_request *req, const char *name,
1675 : const char *value) {
1676 136 : if (!req || !name || !value) return ccol_invalid_args;
1677 133 : if (!*name) return ccol_invalid_args;
1678 1689 : for (const char *p = name; *p; p++) {
1679 1560 : if (!chttp1_is_tchar((unsigned char)*p)) return ccol_invalid_args;
1680 : }
1681 129 : if (!header_value_is_valid(value)) return ccol_invalid_args;
1682 123 : if (ccol_ascii_casecmp(name, "transfer-encoding") == 0)
1683 : return ccol_invalid_args;
1684 :
1685 120 : if (!req->headers) {
1686 72 : char *err = NULL;
1687 72 : chmap hm = chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE,
1688 : ccol_string, ccol_string,
1689 : req->ccol__m_procs, NULL, NULL, &err);
1690 72 : if (!hm) return ccol_not_enough_memory;
1691 72 : req->headers = hm;
1692 : }
1693 :
1694 120 : char name_buf[CHTTP_NAME_STACK_BUF];
1695 120 : size_t nlen = 0;
1696 120 : char *lower = lower_name_copy(req->ccol__m_procs, name, name_buf, &nlen);
1697 120 : if (!lower) return ccol_not_enough_memory;
1698 :
1699 120 : cmap_pair kp = {.ptr = lower, .size = nlen + 1};
1700 120 : cmap_pair vp = {.ptr = (void *)value, .size = strlen(value) + 1};
1701 :
1702 120 : ccol_retval rv = chashmap_insert_elem((chmap)req->headers, &kp, &vp);
1703 120 : if (lower != name_buf) ccol__mem_free(req->ccol__m_procs, lower);
1704 120 : if (rv == ccol_key_already_present) rv = ccol_success;
1705 : return rv;
1706 : }
1707 :
1708 : // Gives the value stored for name in req, or NULL. The lookup lower-cases name,
1709 : // as the setter stores it.
1710 25 : const char *chttp_request_get_header(const chttp_request *req,
1711 : const char *name) {
1712 25 : if (!req || !name || !req->headers) return NULL;
1713 :
1714 22 : char name_buf[CHTTP_NAME_STACK_BUF];
1715 22 : size_t nlen = 0;
1716 22 : char *lower = lower_name_copy(req->ccol__m_procs, name, name_buf, &nlen);
1717 22 : if (!lower) return NULL;
1718 :
1719 22 : cmap_pair kp = {.ptr = lower, .size = nlen + 1};
1720 22 : cmap_pair vp;
1721 22 : ccol_retval rv = chashmap_get_elem_ref((chmap)req->headers, &kp, &vp);
1722 22 : if (lower != name_buf) ccol__mem_free(req->ccol__m_procs, lower);
1723 :
1724 22 : if (rv != ccol_success) return NULL;
1725 16 : return (const char *)vp.ptr;
1726 : }
1727 :
1728 : // Frees req with its URL, body, content type and header map. NULL is allowed.
1729 1453 : void chttp_request_free(chttp_request *req) {
1730 1453 : if (!req) return;
1731 1452 : ccol_memmgmt_procs *mp = req->ccol__m_procs;
1732 1452 : ccol__mem_free(mp, req->url);
1733 76 : ccol__mem_free(mp, (void *)req->body.data);
1734 1452 : ccol__mem_free(mp, (void *)req->body.content_type);
1735 1452 : if (req->headers) chashmap__destroy((chmap)req->headers);
1736 1452 : ccol__mem_free(mp, req);
1737 1452 : if (mp) mp->free(mp);
1738 : }
1739 :
1740 : // Deadline helpers
1741 : //
1742 : // Makes a deadline timeout_us from now on CLOCK_MONOTONIC. 0 gives no limit,
1743 : // and a value too large for the clock saturates instead of wrapping into the
1744 : // past.
1745 3096 : static chttp_deadline deadline_make(uint64_t timeout_us) {
1746 3096 : chttp_deadline d = {0};
1747 3058 : if (timeout_us == 0) return d;
1748 1793 : d.active = true;
1749 1755 : ccol_deadline_after_us(timeout_us, &d.deadline);
1750 1755 : return d;
1751 : }
1752 :
1753 : // Gives the milliseconds from from to to, rounded down, for the idle pool's age
1754 : // check. It works from the full nanosecond difference, because a per-field
1755 : // computation rounds a short span across a second boundary up.
1756 675 : static inline int64_t ms_elapsed_floor(const struct timespec *from,
1757 : const struct timespec *to) {
1758 675 : int64_t ns = ((int64_t)to->tv_sec - (int64_t)from->tv_sec) * 1000000000 +
1759 675 : ((int64_t)to->tv_nsec - (int64_t)from->tv_nsec);
1760 675 : int64_t ms = ns / 1000000;
1761 0 : if (ns < 0 && ms * 1000000 != ns) ms--;
1762 675 : return ms;
1763 : }
1764 :
1765 : // Gives false once d has passed at now. Otherwise *out_ms is the time left
1766 : // rounded up, so a poll(2) for that long can't end before the deadline; it's -1
1767 : // with no active deadline. The math is int64_t and saturates, whatever the
1768 : // widths of long and time_t.
1769 14151 : static bool deadline_remaining_ms_at(const chttp_deadline *d,
1770 : const struct timespec *now, int *out_ms) {
1771 14151 : if (!d->active) {
1772 488 : *out_ms = -1;
1773 488 : return true;
1774 : }
1775 13663 : int64_t secs = (int64_t)d->deadline.tv_sec - (int64_t)now->tv_sec;
1776 13663 : if (secs < 0) return false;
1777 13659 : if (secs > INT_MAX / 1000) {
1778 26 : *out_ms = INT_MAX;
1779 26 : return true;
1780 : }
1781 13633 : int64_t ns = secs * 1000000000 +
1782 13633 : ((int64_t)d->deadline.tv_nsec - (int64_t)now->tv_nsec);
1783 13633 : if (ns <= 0) return false;
1784 13567 : int64_t ms = (ns + 999999) / 1000000;
1785 13567 : *out_ms = (ms > INT_MAX) ? INT_MAX : (int)ms;
1786 13567 : return true;
1787 : }
1788 :
1789 : // Gives the time left on d at the current time, for every Tier 1 wait. See
1790 : // deadline_remaining_ms_at for the result.
1791 17145 : static bool deadline_remaining_ms(const chttp_deadline *d, int *out_ms) {
1792 17145 : if (!d->active) {
1793 4146 : *out_ms = -1;
1794 4146 : return true;
1795 : }
1796 12999 : struct timespec now;
1797 12999 : clock_gettime(CLOCK_MONOTONIC, &now);
1798 12996 : return deadline_remaining_ms_at(d, &now, out_ms);
1799 : }
1800 :
1801 : #ifdef RUNNING_UNIT_TESTS
1802 : // Let a test run deadline_remaining_ms for a deadline add_sec seconds away,
1803 : // ms_elapsed_floor on two given instants, and deadline_remaining_ms_at at a
1804 : // fixed instant, so the rounding can be checked without racing the clock.
1805 3 : bool chttp__deadline_remaining_ms_for_tests(long long add_sec, int *out_ms) {
1806 3 : chttp_deadline d = {0};
1807 3 : d.active = true;
1808 3 : clock_gettime(CLOCK_MONOTONIC, &d.deadline);
1809 3 : d.deadline.tv_sec = (time_t)((long long)d.deadline.tv_sec + add_sec);
1810 3 : return deadline_remaining_ms(&d, out_ms);
1811 : }
1812 :
1813 4 : long long chttp__ms_elapsed_floor_for_tests(long long from_sec, long from_nsec,
1814 : long long to_sec, long to_nsec) {
1815 4 : struct timespec a = {.tv_sec = (time_t)from_sec, .tv_nsec = from_nsec};
1816 4 : struct timespec b = {.tv_sec = (time_t)to_sec, .tv_nsec = to_nsec};
1817 4 : return (long long)ms_elapsed_floor(&a, &b);
1818 : }
1819 :
1820 7 : bool chttp__deadline_remaining_ms_at_for_tests(long long ahead_ns,
1821 : int *out_ms) {
1822 7 : struct timespec now = {.tv_sec = 1000, .tv_nsec = 0};
1823 7 : chttp_deadline d = {0};
1824 7 : d.active = true;
1825 7 : d.deadline.tv_sec = (time_t)(1000 + ahead_ns / 1000000000LL);
1826 7 : d.deadline.tv_nsec = (long)(ahead_ns % 1000000000LL);
1827 7 : if (d.deadline.tv_nsec < 0) {
1828 1 : d.deadline.tv_nsec += 1000000000L;
1829 1 : d.deadline.tv_sec -= 1;
1830 : }
1831 7 : return deadline_remaining_ms_at(&d, &now, out_ms);
1832 : }
1833 :
1834 : // While set, every read point of every tier waits for its fd to be readable and
1835 : // then sees its overall deadline as passed, so a test hits that case at the
1836 : // same point on each tier.
1837 : static _Atomic bool g_expire_at_read_for_tests = false;
1838 :
1839 : // Turns g_expire_at_read_for_tests on or off, for the tests of a deadline that
1840 : // passes with the whole response buffered.
1841 2 : void chttp__set_expire_at_read_for_tests(bool on) {
1842 2 : atomic_store(&g_expire_at_read_for_tests, on);
1843 2 : }
1844 : #endif
1845 :
1846 : // Whether the request's overall deadline has passed before a read of response
1847 : // bytes. Every tier checks it there, so a response not fully read by the
1848 : // deadline ends in ccol_timed_out even when the rest is already buffered.
1849 7209 : static bool read_deadline_passed(const chttp_deadline *overall, int fd) {
1850 : #ifdef RUNNING_UNIT_TESTS
1851 7209 : if (atomic_load(&g_expire_at_read_for_tests)) {
1852 3 : struct pollfd p = {.fd = fd, .events = POLLIN, .revents = 0};
1853 3 : (void)poll(&p, 1, 5000);
1854 3 : return true;
1855 : }
1856 : #else
1857 : (void)fd;
1858 : #endif
1859 7206 : int ms;
1860 7206 : return !deadline_remaining_ms(overall, &ms);
1861 : }
1862 :
1863 : // Gives the tighter of two poll timeouts (-1 means no limit), so a wait can
1864 : // honour two budgets at once.
1865 6819 : static int combine_ms(int a, int b) {
1866 6819 : if (a < 0) return b;
1867 606 : if (b < 0) return a;
1868 4662 : return (a < b) ? a : b;
1869 : }
1870 :
1871 : // Gives whichever of a and b passes first; an inactive deadline never wins. The
1872 : // 100-continue wait uses it to honour both its own window and the overall
1873 : // deadline.
1874 38 : static chttp_deadline deadline_earlier(chttp_deadline a, chttp_deadline b) {
1875 38 : if (!a.active) return b;
1876 38 : if (!b.active) return a;
1877 16 : if (a.deadline.tv_sec != b.deadline.tv_sec)
1878 16 : return (a.deadline.tv_sec < b.deadline.tv_sec) ? a : b;
1879 0 : return (a.deadline.tv_nsec <= b.deadline.tv_nsec) ? a : b;
1880 : }
1881 :
1882 : // Initializes *cv on CLOCK_MONOTONIC, or on the default clock when the platform
1883 : // has no condattr clock. Every deadline here is monotonic, and a timed wait on
1884 : // a wall-clock condition variable would misread it.
1885 2873 : static int ccol_cond_var_init_monotonic(ccol__cond_var *cv) {
1886 2873 : ccol__cond_var_attr cv_attr;
1887 2873 : if (ccol__cond_var_attr_init(cv_attr) == 0) {
1888 2873 : ccol__cond_var_attr_setclock(cv_attr, CLOCK_MONOTONIC);
1889 2873 : int rv = ccol__cond_var_init_ca(*cv, cv_attr);
1890 2873 : ccol__cond_var_attr_destroy(cv_attr);
1891 2873 : return rv;
1892 : }
1893 0 : return ccol__cond_var_init(*cv);
1894 : }
1895 :
1896 : #ifdef RUNNING_UNIT_TESTS
1897 : // Low-level socket and TLS I/O
1898 : //
1899 : // A test hook that fakes the TLS case a cooperating peer can't produce: An
1900 : // SSL_write that must read first, or an SSL_read that must write first (a
1901 : // renegotiation or a badly timed KeyUpdate). The mode picks the direction, and
1902 : // the flags record whether a call was blocked and whether the waiting code
1903 : // asked for the other direction, which releases it.
1904 : #define CHTTP_TLS_DIR_INJECT_OFF 0
1905 : #define CHTTP_TLS_DIR_INJECT_WRITE_WANTS_READ 1
1906 : #define CHTTP_TLS_DIR_INJECT_READ_WANTS_WRITE 2
1907 :
1908 : static _Atomic int g_tls_dir_inject_mode = CHTTP_TLS_DIR_INJECT_OFF;
1909 : static _Atomic bool g_tls_dir_blocked = false;
1910 : static _Atomic bool g_tls_dir_released = false;
1911 : // A guard against a hang only: After this many refused attempts the injection
1912 : // stops refusing without marking itself released, so a broken test fails
1913 : // instead of hanging.
1914 : #define CHTTP_TLS_DIR_INJECT_MAX_BLOCKS 256
1915 : static _Atomic unsigned g_tls_dir_block_attempts = 0;
1916 : static _Atomic unsigned g_tls_dir_read_interest_while_writing = 0;
1917 : static _Atomic unsigned g_tls_dir_write_interest_while_reading = 0;
1918 :
1919 : // True when a TLS attempt with home direction home_is_write must be reported as
1920 : // blocked and asking for the other direction.
1921 809 : static bool tls_dir_inject_blocks(bool home_is_write) {
1922 809 : int mode = atomic_load(&g_tls_dir_inject_mode);
1923 809 : if (mode == CHTTP_TLS_DIR_INJECT_OFF || atomic_load(&g_tls_dir_released))
1924 803 : return false;
1925 12 : bool match = home_is_write ? (mode == CHTTP_TLS_DIR_INJECT_WRITE_WANTS_READ)
1926 6 : : (mode == CHTTP_TLS_DIR_INJECT_READ_WANTS_WRITE);
1927 6 : if (!match) return false;
1928 4 : if (atomic_fetch_add(&g_tls_dir_block_attempts, 1u) >=
1929 : CHTTP_TLS_DIR_INJECT_MAX_BLOCKS)
1930 : return false;
1931 4 : atomic_store(&g_tls_dir_blocked, true);
1932 4 : return true;
1933 : }
1934 :
1935 : // Records a wait in the waiting_for_write direction while an injected block is
1936 : // pending, so the TLS direction tests can see which direction the code waits
1937 : // in. Gives true, and releases the block, when that's the direction the
1938 : // injection asked for; for Tier 1's poll waits that also plays the peer's bytes
1939 : // arriving.
1940 5390 : static bool tls_dir_note_wait(bool waiting_for_write) {
1941 5390 : int mode = atomic_load(&g_tls_dir_inject_mode);
1942 5390 : if (mode == CHTTP_TLS_DIR_INJECT_OFF || !atomic_load(&g_tls_dir_blocked) ||
1943 7 : atomic_load(&g_tls_dir_released))
1944 5386 : return false;
1945 8 : bool opposite = (mode == CHTTP_TLS_DIR_INJECT_WRITE_WANTS_READ)
1946 : ? !waiting_for_write
1947 4 : : waiting_for_write;
1948 4 : if (!opposite) return false;
1949 4 : atomic_store(&g_tls_dir_released, true);
1950 4 : return true;
1951 : }
1952 : #endif
1953 :
1954 : #ifdef RUNNING_UNIT_TESTS
1955 : // When non-zero, the first ctls_conn_read of each Tier 2 read dispatch asks for
1956 : // at most this many bytes, so a test can leave part of a record in the TLS
1957 : // layer.
1958 : static _Atomic size_t g_async_tls_first_read_cap_for_tests = 0;
1959 :
1960 : // Sets g_async_tls_first_read_cap_for_tests, so a test can leave part of a
1961 : // record inside the TLS layer.
1962 2 : void chttp__set_async_tls_first_read_cap_for_tests(size_t cap) {
1963 2 : atomic_store(&g_async_tls_first_read_cap_for_tests, cap);
1964 2 : }
1965 : #endif
1966 :
1967 : // Tells whether a blocked TLS call on tls needs the write direction, for every
1968 : // loop that waits after a TLS call. It's ctls_conn_wants_write, plus the
1969 : // direction injection in a test build.
1970 119 : static bool conn_tls_wants_write(ctls_conn *tls) {
1971 : #ifdef RUNNING_UNIT_TESTS
1972 119 : int mode = atomic_load(&g_tls_dir_inject_mode);
1973 119 : if (mode != CHTTP_TLS_DIR_INJECT_OFF && atomic_load(&g_tls_dir_blocked) &&
1974 6 : !atomic_load(&g_tls_dir_released))
1975 4 : return (mode == CHTTP_TLS_DIR_INJECT_READ_WANTS_WRITE);
1976 : #endif
1977 115 : return ctls_conn_wants_write(tls);
1978 : }
1979 :
1980 : #ifdef RUNNING_UNIT_TESTS
1981 : // While above 0, each capped wait of conn_wait returns at once as if it had run
1982 : // out, so a test can check that callers wait again until their real deadline.
1983 : static atomic_int g_chttp_short_capped_waits;
1984 : // Makes the next n capped waits of conn_wait return at once, so a test can
1985 : // check that callers wait again until their real deadline.
1986 2 : void chttp__short_next_capped_waits_for_tests(int n) {
1987 2 : atomic_store(&g_chttp_short_capped_waits, n);
1988 2 : }
1989 : #endif
1990 : // Polls fd for events for at most timeout_ms (-1 waits forever) and retries
1991 : // after EINTR against the original budget. ccol_timed_out only means this wait
1992 : // ran out; callers check their own deadline again, since waits are capped at
1993 : // INT_MAX ms. POLLERR or POLLNVAL gives error_rv.
1994 994 : static ccol_retval conn_wait(int fd, short events, int timeout_ms,
1995 : ccol_retval error_rv) {
1996 : #ifdef RUNNING_UNIT_TESTS
1997 994 : if (tls_dir_note_wait((events & POLLOUT) != 0)) return ccol_success;
1998 : #endif
1999 993 : bool has_timeout = (timeout_ms >= 0);
2000 993 : struct timespec start;
2001 993 : if (has_timeout) clock_gettime(CLOCK_MONOTONIC, &start);
2002 : int remaining = timeout_ms;
2003 :
2004 993 : for (;;) {
2005 993 : struct pollfd pfd = {.fd = fd, .events = events, .revents = 0};
2006 993 : int wait = remaining;
2007 : #ifdef RUNNING_UNIT_TESTS
2008 993 : if (wait == INT_MAX && atomic_load(&g_chttp_short_capped_waits) > 0 &&
2009 0 : atomic_fetch_sub(&g_chttp_short_capped_waits, 1) > 0)
2010 993 : wait = 0;
2011 : #endif
2012 993 : int rc = poll(&pfd, 1, wait);
2013 993 : if (rc < 0) {
2014 0 : if (errno == EINTR) {
2015 0 : if (has_timeout) {
2016 0 : struct timespec now;
2017 0 : clock_gettime(CLOCK_MONOTONIC, &now);
2018 0 : int64_t elapsed_ms = ms_elapsed_floor(&start, &now);
2019 0 : remaining = (int)(timeout_ms - elapsed_ms);
2020 0 : if (remaining <= 0) return ccol_timed_out;
2021 : }
2022 0 : continue;
2023 : }
2024 : return ccol_http_transfer_aborted;
2025 : }
2026 993 : if (rc == 0) return ccol_timed_out;
2027 988 : if (pfd.revents & (POLLERR | POLLNVAL)) return error_rv;
2028 : return ccol_success;
2029 : }
2030 : }
2031 :
2032 : // Narrows *wait_ms to what's left of c's inactivity budget, rounded up, so a
2033 : // silent peer ends the request. Gives false once the budget is used up. Only
2034 : // the waits of conn_wait_io and the duplex send count, and every byte moved
2035 : // resets it (c->inactivity_waited_ns).
2036 6215 : static bool conn_inactivity_left_ms(const chttp_conn *c, int *wait_ms) {
2037 6215 : if (c->inactivity_us == 0) return true;
2038 12426 : uint64_t budget_ns = c->inactivity_us > UINT64_MAX / 1000
2039 : ? UINT64_MAX
2040 6213 : : c->inactivity_us * 1000;
2041 6213 : if (c->inactivity_waited_ns >= budget_ns) return false;
2042 6211 : uint64_t left_ns = budget_ns - c->inactivity_waited_ns;
2043 6211 : uint64_t left_ms = left_ns / 1000000 + (left_ns % 1000000 != 0);
2044 6211 : *wait_ms = combine_ms(*wait_ms, left_ms > INT_MAX ? INT_MAX : (int)left_ms);
2045 6211 : return true;
2046 : }
2047 :
2048 : // Adds the time since *start to what c's request has waited with no byte
2049 : // moving.
2050 5339 : static void conn_inactivity_charge(chttp_conn *c,
2051 : const struct timespec *start) {
2052 5339 : if (c->inactivity_us == 0) return;
2053 5337 : struct timespec now;
2054 5337 : clock_gettime(CLOCK_MONOTONIC, &now);
2055 5337 : int64_t ns = (int64_t)(now.tv_sec - start->tv_sec) * 1000000000 +
2056 5337 : (now.tv_nsec - start->tv_nsec);
2057 5337 : if (ns > 0) c->inactivity_waited_ns += (uint64_t)ns;
2058 : }
2059 :
2060 : // Waits on c's socket like conn_wait and charges the time to c's inactivity
2061 : // budget, so the inactivity timeout counts only time spent waiting on the peer.
2062 946 : static ccol_retval conn_wait_io(chttp_conn *c, short events, int timeout_ms,
2063 : ccol_retval error_rv) {
2064 946 : struct timespec start;
2065 946 : clock_gettime(CLOCK_MONOTONIC, &start);
2066 946 : ccol_retval rv = conn_wait(c->fd, events, timeout_ms, error_rv);
2067 946 : conn_inactivity_charge(c, &start);
2068 946 : return rv;
2069 : }
2070 :
2071 : // Starts the inactivity count of a request that has just taken c, fresh or from
2072 : // the pool, since the budget belongs to the request.
2073 655 : static void conn_inactivity_start(chttp_conn *c, uint64_t timeout_us) {
2074 655 : c->inactivity_us = timeout_us;
2075 655 : c->inactivity_waited_ns = 0;
2076 : }
2077 :
2078 : // Reads from c through TLS or recv, for every Tier 1 read. Gives what the call
2079 : // gave, and resets c's inactivity count when bytes moved.
2080 5363 : static ssize_t conn_read(chttp_conn *c, void *buf, size_t len) {
2081 5363 : if (c->tls) {
2082 : #ifdef RUNNING_UNIT_TESTS
2083 94 : if (tls_dir_inject_blocks(false)) {
2084 1 : errno = EWOULDBLOCK;
2085 1 : return -1;
2086 : }
2087 : #endif
2088 93 : ssize_t n = ctls_conn_read(c->tls, buf, len);
2089 93 : if (n < 0 && (errno == EAGAIN)) errno = EWOULDBLOCK;
2090 93 : if (n > 0) c->inactivity_waited_ns = 0;
2091 93 : return n;
2092 : }
2093 5269 : ssize_t n;
2094 5269 : do {
2095 5269 : n = recv(c->fd, buf, len, 0);
2096 5269 : } while (n < 0 && errno == EINTR);
2097 5269 : if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) errno = EWOULDBLOCK;
2098 5269 : if (n > 0) c->inactivity_waited_ns = 0;
2099 : return n;
2100 : }
2101 :
2102 : // Writes to c through TLS or send, for every Tier 1 write; send uses
2103 : // MSG_NOSIGNAL so it never raises SIGPIPE. Gives what the call gave, and resets
2104 : // c's inactivity count when bytes moved.
2105 850 : static ssize_t conn_write(chttp_conn *c, const void *buf, size_t len) {
2106 850 : if (c->tls) {
2107 : #ifdef RUNNING_UNIT_TESTS
2108 179 : if (tls_dir_inject_blocks(true)) {
2109 1 : errno = EWOULDBLOCK;
2110 1 : return -1;
2111 : }
2112 : #endif
2113 178 : ssize_t n = ctls_conn_write(c->tls, buf, len);
2114 178 : if (n < 0 && (errno == EAGAIN)) errno = EWOULDBLOCK;
2115 178 : if (n > 0) c->inactivity_waited_ns = 0;
2116 178 : return n;
2117 : }
2118 671 : ssize_t n;
2119 671 : do {
2120 671 : n = send(c->fd, buf, len, CCOL_MSG_NOSIGNAL);
2121 671 : } while (n < 0 && errno == EINTR);
2122 671 : if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) errno = EWOULDBLOCK;
2123 671 : if (n > 0) c->inactivity_waited_ns = 0;
2124 : return n;
2125 : }
2126 :
2127 : // Sends all of data within the deadline. On TLS the direction of the next wait
2128 : // is worked out again after each blocked attempt, since a TLS write may need to
2129 : // read first. A closed peer is ccol_http_transfer_aborted.
2130 14 : static ccol_retval chttp_send_all(chttp_conn *conn, const char *data,
2131 : size_t len, chttp_deadline *overall) {
2132 14 : size_t sent = 0;
2133 14 : short want_events = POLLOUT;
2134 28 : while (sent < len) {
2135 14 : int wait_ms;
2136 14 : if (!deadline_remaining_ms(overall, &wait_ms) ||
2137 14 : !conn_inactivity_left_ms(conn, &wait_ms))
2138 0 : return ccol_timed_out;
2139 14 : ccol_retval prv =
2140 14 : conn_wait_io(conn, want_events, wait_ms, ccol_http_transfer_aborted);
2141 14 : if (prv == ccol_timed_out) continue;
2142 14 : if (prv != ccol_success) return prv;
2143 14 : ssize_t n = conn_write(conn, data + sent, len - sent);
2144 14 : if (n < 0) {
2145 0 : if (errno == EWOULDBLOCK) {
2146 0 : if (conn->tls)
2147 0 : want_events = conn_tls_wants_write(conn->tls) ? POLLOUT : POLLIN;
2148 0 : continue;
2149 : }
2150 : return ccol_http_transfer_aborted;
2151 : }
2152 14 : if (n == 0) return ccol_http_transfer_aborted;
2153 14 : sent += (size_t)n;
2154 14 : want_events = POLLOUT;
2155 : }
2156 : return ccol_success;
2157 : }
2158 :
2159 : // Sets TCP_NODELAY on a TCP socket, best effort, because a request goes out in
2160 : // small writes that must not wait for an ACK. Every connect path goes through
2161 : // here.
2162 1339 : static void apply_tcp_nodelay(int fd) {
2163 1339 : int one = 1;
2164 1339 : (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
2165 806 : }
2166 :
2167 : // One resolved address of a TCP target, copied out of the getaddrinfo() result.
2168 : typedef struct {
2169 : struct sockaddr_storage addr;
2170 : socklen_t addr_len;
2171 : int protocol;
2172 : } chttp_resolved_addr;
2173 :
2174 : // The candidate addresses of one TCP target. They keep the resolver's RFC 6724
2175 : // order and addr_list_interleave then alternates the families (RFC 8305 section
2176 : // 4). Every tier connects with Happy Eyeballs: The first candidate starts at
2177 : // once, the next one when the attempts in flight have had no result for the
2178 : // attempt delay or one fails, the first to connect wins and the connect timeout
2179 : // bounds the whole race.
2180 : typedef struct {
2181 : size_t count;
2182 : chttp_resolved_addr addrs[];
2183 : } chttp_addr_list;
2184 :
2185 : // True when host is an IPv4 or IPv6 literal, so no name lookup is needed.
2186 3528 : static bool host_is_ip_literal(const char *host) {
2187 3528 : unsigned char buf[sizeof(struct in6_addr)];
2188 3663 : return inet_pton(AF_INET, host, buf) == 1 ||
2189 135 : inet_pton(AF_INET6, host, buf) == 1;
2190 : }
2191 :
2192 : // Resolves host:port into a new list from mp; an address literal is converted
2193 : // without a lookup. A name that resolves to nothing is
2194 : // ccol_http_host_resolution_failed.
2195 1333 : static ccol_retval addr_list_resolve(ccol_memmgmt_procs *mp, const char *host,
2196 : uint16_t port, chttp_addr_list **out) {
2197 1333 : *out = NULL;
2198 1333 : char port_str[8];
2199 1333 : snprintf(port_str, sizeof(port_str), "%u", (unsigned)port);
2200 :
2201 1333 : struct addrinfo hints;
2202 1333 : memset(&hints, 0, sizeof(hints));
2203 1333 : hints.ai_family = AF_UNSPEC;
2204 1333 : hints.ai_socktype = SOCK_STREAM;
2205 1333 : if (host_is_ip_literal(host)) hints.ai_flags = AI_NUMERICHOST;
2206 :
2207 1335 : struct addrinfo *res = NULL;
2208 1335 : if (getaddrinfo(host, port_str, &hints, &res) != 0 || !res)
2209 : return ccol_http_host_resolution_failed;
2210 :
2211 : size_t count = 0;
2212 2675 : for (struct addrinfo *ai = res; ai; ai = ai->ai_next)
2213 1346 : if (ai->ai_addrlen <= sizeof(struct sockaddr_storage)) count++;
2214 1329 : if (count == 0) {
2215 0 : freeaddrinfo(res);
2216 0 : return ccol_http_host_resolution_failed;
2217 : }
2218 :
2219 1329 : chttp_addr_list *l = (chttp_addr_list *)ccol__mem_alloc(
2220 : mp, sizeof(*l) + count * sizeof(l->addrs[0]));
2221 1329 : if (!l) {
2222 2 : freeaddrinfo(res);
2223 2 : return ccol_not_enough_memory;
2224 : }
2225 1327 : size_t i = 0;
2226 2671 : for (struct addrinfo *ai = res; ai; ai = ai->ai_next) {
2227 1344 : if (ai->ai_addrlen > sizeof(struct sockaddr_storage)) continue;
2228 1344 : memset(&l->addrs[i].addr, 0, sizeof(l->addrs[i].addr));
2229 1344 : memcpy(&l->addrs[i].addr, ai->ai_addr, ai->ai_addrlen);
2230 1344 : l->addrs[i].addr_len = (socklen_t)ai->ai_addrlen;
2231 1344 : l->addrs[i].protocol = ai->ai_protocol;
2232 1344 : i++;
2233 : }
2234 1327 : l->count = count;
2235 1327 : freeaddrinfo(res);
2236 1327 : *out = l;
2237 1327 : return ccol_success;
2238 : }
2239 :
2240 : // Alternates the address families of l, starting with the first address's
2241 : // family and keeping each family's order. It rotates in place without
2242 : // allocating, since lists are short.
2243 1353 : static void addr_list_interleave(chttp_addr_list *l) {
2244 1353 : if (l->count < 3) return;
2245 4 : sa_family_t first = l->addrs[0].addr.ss_family;
2246 10 : for (size_t i = 1; i < l->count; i++) {
2247 8 : bool want_first = (i % 2) == 0;
2248 8 : size_t j = i;
2249 16 : while (j < l->count &&
2250 14 : ((l->addrs[j].addr.ss_family == first) != want_first))
2251 8 : j++;
2252 8 : if (j == l->count) break;
2253 6 : if (j != i) {
2254 3 : chttp_resolved_addr moved = l->addrs[j];
2255 3 : memmove(&l->addrs[i + 1], &l->addrs[i], (j - i) * sizeof(l->addrs[0]));
2256 3 : l->addrs[i] = moved;
2257 : }
2258 : }
2259 : }
2260 :
2261 : #ifdef RUNNING_UNIT_TESTS
2262 : static bool addr_is_silent_for_tests(const chttp_resolved_addr *a);
2263 : static int silent_attempt_fd_for_tests(void);
2264 : #endif
2265 :
2266 : // Starts a non-blocking, close-on-exec connect to a, for one Happy Eyeballs
2267 : // attempt; a child the process spawns must not inherit the connection. Gives
2268 : // the fd, with *in_progress true while the connect is pending, or -1 when
2269 : // socket() or connect() fails at once.
2270 1390 : static int addr_connect_start(const chttp_resolved_addr *a, bool *in_progress) {
2271 1390 : int fd = ccol_socket_nb(a->addr.ss_family, SOCK_STREAM, a->protocol);
2272 1389 : if (fd < 0) return -1;
2273 : #ifdef RUNNING_UNIT_TESTS
2274 1389 : if (addr_is_silent_for_tests(a)) {
2275 1 : close(fd);
2276 1 : *in_progress = true;
2277 1 : return silent_attempt_fd_for_tests();
2278 : }
2279 : #endif
2280 1389 : if (connect(fd, (const struct sockaddr *)&a->addr, a->addr_len) == 0) {
2281 0 : *in_progress = false;
2282 : #ifdef RUNNING_UNIT_TESTS
2283 0 : if (atomic_load(&g_connect_async_failures_for_tests) > 0)
2284 0 : *in_progress = true;
2285 : #endif
2286 0 : return fd;
2287 : }
2288 1389 : if (errno == EINPROGRESS) {
2289 1389 : *in_progress = true;
2290 1389 : return fd;
2291 : }
2292 0 : close(fd);
2293 0 : return -1;
2294 : }
2295 :
2296 : #ifdef RUNNING_UNIT_TESTS
2297 : // A test hook: An attempt on an address in this set gets one end of a socket
2298 : // pair with a full send buffer and a quiet peer instead of a TCP socket, which
2299 : // looks exactly like a connect whose SYN is dropped. The peer ends (stored as
2300 : // fd + 1, 0 for an empty slot) stay open until the set is emptied.
2301 : enum { SILENT_ADDRS_FOR_TESTS = 4, SILENT_PEERS_FOR_TESTS = 32 };
2302 : static struct sockaddr_storage g_silent_addrs_for_tests[SILENT_ADDRS_FOR_TESTS];
2303 : static socklen_t g_silent_lens_for_tests[SILENT_ADDRS_FOR_TESTS];
2304 : static atomic_int g_silent_count_for_tests;
2305 : static atomic_int g_silent_peers_for_tests[SILENT_PEERS_FOR_TESTS];
2306 :
2307 : // Makes one silent attempt socket for the hook above and keeps its peer.
2308 1 : static int silent_attempt_fd_for_tests(void) {
2309 1 : int sv[2];
2310 1 : if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return -1;
2311 3 : for (int i = 0; i < 2; i++) {
2312 2 : int fl = fcntl(sv[i], F_GETFL, 0);
2313 2 : (void)fcntl(sv[i], F_SETFL, fl | O_NONBLOCK);
2314 2 : (void)fcntl(sv[i], F_SETFD, FD_CLOEXEC);
2315 : }
2316 1 : char block[4096];
2317 1 : memset(block, 0, sizeof(block));
2318 46 : while (send(sv[0], block, sizeof(block), CCOL_MSG_NOSIGNAL) > 0) {
2319 45 : }
2320 1 : for (int i = 0; i < SILENT_PEERS_FOR_TESTS; i++) {
2321 1 : int empty = 0;
2322 1 : if (atomic_compare_exchange_strong(&g_silent_peers_for_tests[i], &empty,
2323 : sv[1] + 1))
2324 1 : return sv[0];
2325 : }
2326 0 : close(sv[0]);
2327 0 : close(sv[1]);
2328 0 : return -1;
2329 : }
2330 :
2331 : // Adds addr to the silent set (NULL empties it and closes the peers), so a test
2332 : // can make an address behave like one whose SYN is dropped.
2333 9 : void chttp__set_silent_addr_for_tests(const struct sockaddr *addr,
2334 : socklen_t len) {
2335 9 : if (!addr) {
2336 8 : atomic_store(&g_silent_count_for_tests, 0);
2337 264 : for (int i = 0; i < SILENT_PEERS_FOR_TESTS; i++) {
2338 256 : int stored = atomic_exchange(&g_silent_peers_for_tests[i], 0);
2339 256 : if (stored > 0) close(stored - 1);
2340 : }
2341 : return;
2342 : }
2343 1 : int n = atomic_load(&g_silent_count_for_tests);
2344 1 : if (n >= SILENT_ADDRS_FOR_TESTS || len > sizeof(g_silent_addrs_for_tests[0]))
2345 : return;
2346 1 : memcpy(&g_silent_addrs_for_tests[n], addr, len);
2347 1 : g_silent_lens_for_tests[n] = len;
2348 1 : atomic_store(&g_silent_count_for_tests, n + 1);
2349 : }
2350 :
2351 : // Tells whether a is in the silent set, so addr_connect_start hands it a silent
2352 : // socket.
2353 1389 : static bool addr_is_silent_for_tests(const chttp_resolved_addr *a) {
2354 1389 : int n = atomic_load(&g_silent_count_for_tests);
2355 1389 : for (int i = 0; i < n; i++) {
2356 1 : if (g_silent_lens_for_tests[i] == a->addr_len &&
2357 1 : memcmp(&g_silent_addrs_for_tests[i], &a->addr, a->addr_len) == 0)
2358 : return true;
2359 : }
2360 : return false;
2361 : }
2362 :
2363 : // While non-NULL, every TCP resolution returns this list in this order, so a
2364 : // test controls the candidates whatever /etc/hosts says.
2365 : static _Atomic(const chttp_addr_list *) g_addr_list_override_for_tests = NULL;
2366 :
2367 : // Installs a fixed candidate list from addrs (NULL or n == 0 clears it), so a
2368 : // test controls what every TCP resolution gives.
2369 16 : void chttp__set_addr_override_for_tests(const struct sockaddr *const *addrs,
2370 : const socklen_t *lens, size_t count) {
2371 16 : enum { MAX_OVERRIDE_ADDRS = 8 };
2372 16 : static _Alignas(max_align_t) unsigned char
2373 : storage[sizeof(chttp_addr_list) +
2374 : MAX_OVERRIDE_ADDRS * sizeof(chttp_resolved_addr)];
2375 16 : chttp_addr_list *l = (chttp_addr_list *)(void *)storage;
2376 16 : if (!addrs || count == 0) {
2377 8 : atomic_store(&g_addr_list_override_for_tests, NULL);
2378 8 : chttp__set_silent_addr_for_tests(NULL, 0);
2379 8 : return;
2380 : }
2381 8 : if (count > MAX_OVERRIDE_ADDRS) count = MAX_OVERRIDE_ADDRS;
2382 8 : memset(storage, 0, sizeof(storage));
2383 24 : for (size_t i = 0; i < count; i++) {
2384 16 : memcpy(&l->addrs[i].addr, addrs[i], lens[i]);
2385 16 : l->addrs[i].addr_len = lens[i];
2386 16 : l->addrs[i].protocol = 0;
2387 : }
2388 8 : l->count = count;
2389 8 : atomic_store(&g_addr_list_override_for_tests, l);
2390 : }
2391 : #endif
2392 :
2393 : #ifdef RUNNING_UNIT_TESTS
2394 : // Runs addr_list_interleave on a list with the given families and writes the
2395 : // new order of the original indexes to order_out, so a test can check the
2396 : // interleave.
2397 3 : void chttp__addr_list_interleave_for_tests(const int *families, size_t n,
2398 : size_t *order_out) {
2399 3 : enum { MAX_ADDRS = 16 };
2400 3 : static _Alignas(max_align_t) unsigned char
2401 : storage[sizeof(chttp_addr_list) +
2402 : MAX_ADDRS * sizeof(chttp_resolved_addr)];
2403 3 : chttp_addr_list *l = (chttp_addr_list *)(void *)storage;
2404 3 : if (n > MAX_ADDRS) n = MAX_ADDRS;
2405 3 : memset(storage, 0, sizeof(storage));
2406 14 : for (size_t i = 0; i < n; i++) {
2407 11 : l->addrs[i].addr.ss_family = (sa_family_t)families[i];
2408 11 : ((struct sockaddr_in *)&l->addrs[i].addr)->sin_port = htons((uint16_t)i);
2409 : }
2410 3 : l->count = n;
2411 3 : addr_list_interleave(l);
2412 14 : for (size_t i = 0; i < n; i++)
2413 11 : order_out[i] = ntohs(((struct sockaddr_in *)&l->addrs[i].addr)->sin_port);
2414 3 : }
2415 : #endif
2416 :
2417 : static uint64_t monotonic_now_ns(void);
2418 :
2419 : #ifdef RUNNING_UNIT_TESTS
2420 : // When non-zero, every name lookup sleeps this long first, like a resolver that
2421 : // doesn't answer. Address literals aren't affected.
2422 : static _Atomic unsigned g_name_lookup_delay_ms_for_tests = 0;
2423 :
2424 : // Sets g_name_lookup_delay_ms_for_tests, so a test can play a resolver that
2425 : // doesn't answer.
2426 9 : void chttp__set_name_lookup_delay_ms_for_tests(unsigned ms) {
2427 9 : atomic_store(&g_name_lookup_delay_ms_for_tests, ms);
2428 9 : }
2429 :
2430 : // Set by chttp__sweep_fd_wait_arm_for_tests until a sweep tick catches the
2431 : // armed hop before its connect. While set, a name lookup waits (bounded) for
2432 : // that tick after its delay, so the test doesn't depend on tick timing.
2433 : static _Atomic bool g_sweep_fd_wait_pending_for_tests = false;
2434 :
2435 : // What the armed hold saw, for explaining a failure on a system that can't be
2436 : // debugged: The ctxs the sweep showed it, why each was turned away, the last
2437 : // one's fd and state, and how the lookup's wait ended. Arming resets them.
2438 : static atomic_ulong g_sweep_fd_wait_seen_for_tests;
2439 : static atomic_ulong g_sweep_fd_wait_not_armed_for_tests;
2440 : static atomic_ulong g_sweep_fd_wait_had_fd_for_tests;
2441 : static atomic_ulong g_sweep_fd_wait_wrong_state_for_tests;
2442 : static atomic_ulong g_sweep_fd_wait_had_race_for_tests;
2443 : static atomic_int g_sweep_fd_wait_last_fd_for_tests = -2;
2444 : static atomic_int g_sweep_fd_wait_last_state_for_tests = -1;
2445 : static atomic_int g_sweep_fd_wait_lookup_end_for_tests;
2446 : static atomic_int g_sweep_fd_wait_hold_end_for_tests;
2447 :
2448 : static void client_deadline_note_ns(uint64_t at_ns);
2449 :
2450 : // The name lookups started by all tiers (address literals don't count).
2451 : static _Atomic unsigned long g_name_lookups_for_tests = 0;
2452 :
2453 : // Gives g_name_lookups_for_tests, so a test can check that a request made no
2454 : // lookup.
2455 2 : unsigned long chttp__name_lookups_for_tests(void) {
2456 2 : return atomic_load(&g_name_lookups_for_tests);
2457 : }
2458 : #endif
2459 :
2460 : // The resolution step every tier calls. It counts and delays name lookups for
2461 : // the tests, takes the override list when one is set, and interleaves the
2462 : // families.
2463 1359 : static ccol_retval addr_list_resolve_for_target(ccol_memmgmt_procs *mp,
2464 : const char *host, uint16_t port,
2465 : chttp_addr_list **out) {
2466 : #ifdef RUNNING_UNIT_TESTS
2467 1359 : if (!host_is_ip_literal(host))
2468 47 : atomic_fetch_add_explicit(&g_name_lookups_for_tests, 1,
2469 : memory_order_relaxed);
2470 1357 : unsigned delay_ms = atomic_load(&g_name_lookup_delay_ms_for_tests);
2471 1357 : if (delay_ms && !host_is_ip_literal(host)) {
2472 7 : struct timespec ts = {(time_t)(delay_ms / 1000),
2473 7 : (long)(delay_ms % 1000) * 1000000L};
2474 13 : while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {
2475 7 : }
2476 6 : struct timespec tick = {0, 1000000};
2477 6 : bool waited = atomic_load(&g_sweep_fd_wait_pending_for_tests);
2478 6 : int i = 0;
2479 7 : for (; i < 5000 && atomic_load(&g_sweep_fd_wait_pending_for_tests); i++) {
2480 1 : client_deadline_note_ns(monotonic_now_ns());
2481 1 : nanosleep(&tick, NULL);
2482 : }
2483 6 : if (waited)
2484 1 : atomic_store(&g_sweep_fd_wait_lookup_end_for_tests, i < 5000 ? 1 : 2);
2485 5 : else if (atomic_load(&g_sweep_fd_wait_lookup_end_for_tests) == 0)
2486 1 : atomic_store(&g_sweep_fd_wait_lookup_end_for_tests, 3);
2487 : }
2488 1356 : const chttp_addr_list *ov = atomic_load(&g_addr_list_override_for_tests);
2489 1356 : if (ov) {
2490 23 : size_t bytes = sizeof(*ov) + ov->count * sizeof(ov->addrs[0]);
2491 23 : chttp_addr_list *l = (chttp_addr_list *)ccol__mem_alloc(mp, bytes);
2492 23 : if (!l) return ccol_not_enough_memory;
2493 23 : memcpy(l, ov, bytes);
2494 23 : *out = l;
2495 23 : return ccol_success;
2496 : }
2497 : #endif
2498 1333 : return addr_list_resolve(mp, host, port, out);
2499 : }
2500 :
2501 : // Gives the milliseconds from now until at, rounded up (0 once it's past), for
2502 : // the Happy Eyeballs timing.
2503 49 : static int ms_until(const struct timespec *at, const struct timespec *now) {
2504 49 : chttp_deadline d = {.active = true, .deadline = *at};
2505 49 : int ms;
2506 49 : return deadline_remaining_ms_at(&d, now, &ms) ? ms : 0;
2507 : }
2508 :
2509 : // Gives t plus ms milliseconds, for the Happy Eyeballs attempt starts.
2510 599 : static struct timespec timespec_add_ms(struct timespec t, long ms) {
2511 599 : t.tv_sec += ms / 1000;
2512 599 : t.tv_nsec += (ms % 1000) * 1000000L;
2513 599 : if (t.tv_nsec >= 1000000000L) {
2514 222 : t.tv_nsec -= 1000000000L;
2515 222 : t.tv_sec += 1;
2516 : }
2517 52 : return t;
2518 : }
2519 :
2520 : // Resolves host:port and connects with the Happy Eyeballs race, for Tier 1's
2521 : // TCP connections. Both the connect deadline and the request's overall deadline
2522 : // apply, whichever is tighter. On success *fd_out is the winner; the losing
2523 : // attempts are closed.
2524 535 : static ccol_retval tcp_connect(ccol_memmgmt_procs *mp, const char *host,
2525 : uint16_t port, chttp_deadline *connect_dl,
2526 : chttp_deadline *overall, int *fd_out) {
2527 535 : chttp_addr_list *list = NULL;
2528 535 : ccol_retval rrv = addr_list_resolve_for_target(mp, host, port, &list);
2529 535 : if (rrv != ccol_success) return rrv;
2530 533 : addr_list_interleave(list);
2531 :
2532 533 : struct pollfd stack_pfds[8];
2533 533 : struct pollfd *pfds = stack_pfds;
2534 533 : if (list->count > sizeof(stack_pfds) / sizeof(stack_pfds[0])) {
2535 0 : pfds = (struct pollfd *)ccol__mem_alloc(mp, list->count * sizeof(*pfds));
2536 0 : if (!pfds) {
2537 0 : ccol__mem_free(mp, list);
2538 0 : return ccol_not_enough_memory;
2539 : }
2540 : }
2541 533 : size_t npend = 0;
2542 533 : size_t next = 0;
2543 533 : int winner = -1;
2544 533 : ccol_retval result = ccol_http_connection_failed;
2545 533 : struct timespec now;
2546 533 : clock_gettime(CLOCK_MONOTONIC, &now);
2547 533 : struct timespec next_start = now;
2548 :
2549 550 : for (;;) {
2550 555 : bool due = npend == 0 || ms_until(&next_start, &now) == 0;
2551 550 : while (due && next < list->count && winner < 0) {
2552 547 : bool in_progress = false;
2553 547 : int fd = addr_connect_start(&list->addrs[next++], &in_progress);
2554 547 : if (fd < 0) continue;
2555 547 : if (!in_progress) {
2556 : winner = fd;
2557 547 : break;
2558 : }
2559 547 : pfds[npend].fd = fd;
2560 547 : pfds[npend].events = POLLOUT;
2561 547 : pfds[npend].revents = 0;
2562 547 : npend++;
2563 1094 : next_start = timespec_add_ms(now, connect_attempt_delay_ms());
2564 : break;
2565 : }
2566 550 : if (winner >= 0) {
2567 : result = ccol_success;
2568 532 : break;
2569 : }
2570 550 : if (npend == 0) {
2571 : result = ccol_http_connection_failed;
2572 : break;
2573 : }
2574 :
2575 548 : int wait_ms, overall_ms;
2576 1094 : if (!deadline_remaining_ms_at(connect_dl, &now, &wait_ms) ||
2577 547 : !deadline_remaining_ms_at(overall, &now, &overall_ms)) {
2578 : result = ccol_timed_out;
2579 : break;
2580 : }
2581 546 : wait_ms = combine_ms(wait_ms, overall_ms);
2582 546 : if (next < list->count)
2583 42 : wait_ms = combine_ms(wait_ms, ms_until(&next_start, &now));
2584 :
2585 546 : int rc = poll(pfds, (nfds_t)npend, wait_ms);
2586 547 : if (rc < 0 && errno != EINTR) {
2587 : result = ccol_http_connection_failed;
2588 : break;
2589 : }
2590 547 : clock_gettime(CLOCK_MONOTONIC, &now);
2591 547 : if (rc <= 0) continue;
2592 :
2593 : size_t kept = 0;
2594 1088 : for (size_t i = 0; i < npend; i++) {
2595 546 : if (pfds[i].revents == 0 || winner >= 0) {
2596 3 : pfds[kept++] = pfds[i];
2597 532 : continue;
2598 : }
2599 543 : int soerr = 0;
2600 543 : socklen_t slen = sizeof(soerr);
2601 543 : int gso = getsockopt(pfds[i].fd, SOL_SOCKET, SO_ERROR, &soerr, &slen);
2602 : #ifdef RUNNING_UNIT_TESTS
2603 542 : if (gso == 0 && soerr == 0 &&
2604 530 : take_one_for_tests(&g_connect_async_failures_for_tests))
2605 1 : soerr = ECONNREFUSED;
2606 : #endif
2607 542 : if (gso == 0 && soerr == 0) {
2608 529 : winner = pfds[i].fd;
2609 529 : continue;
2610 : }
2611 13 : close(pfds[i].fd);
2612 13 : next_start = now;
2613 : }
2614 542 : npend = kept;
2615 542 : if (winner >= 0) {
2616 : result = ccol_success;
2617 : break;
2618 : }
2619 : }
2620 :
2621 536 : for (size_t i = 0; i < npend; i++) close(pfds[i].fd);
2622 533 : if (pfds != stack_pfds) ccol__mem_free(mp, pfds);
2623 533 : ccol__mem_free(mp, list);
2624 533 : if (result == ccol_success) {
2625 530 : apply_tcp_nodelay(winner);
2626 530 : *fd_out = winner;
2627 : }
2628 : return result;
2629 : }
2630 :
2631 : // Connects to the unix stream socket at path within the same deadlines as
2632 : // tcp_connect. The socket stays non-blocking with a poll step, so the deadline
2633 : // holds even in the rare EINPROGRESS case.
2634 13 : static ccol_retval unix_connect(const char *path, chttp_deadline *connect_dl,
2635 : chttp_deadline *overall, int *fd_out) {
2636 13 : struct sockaddr_un addr;
2637 13 : memset(&addr, 0, sizeof(addr));
2638 13 : addr.sun_family = AF_UNIX;
2639 13 : size_t path_len = strlen(path);
2640 13 : if (path_len >= sizeof(addr.sun_path)) return ccol_http_invalid_url;
2641 12 : memcpy(addr.sun_path, path, path_len + 1);
2642 :
2643 12 : int fd = ccol_socket_nb(AF_UNIX, SOCK_STREAM, 0);
2644 12 : if (fd < 0) return ccol_http_connection_failed;
2645 :
2646 12 : int rc = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
2647 12 : if (rc == 0) {
2648 11 : *fd_out = fd;
2649 11 : return ccol_success;
2650 : }
2651 1 : if (errno != EINPROGRESS) {
2652 1 : close(fd);
2653 1 : return ccol_http_connection_failed;
2654 : }
2655 :
2656 0 : ccol_retval prv;
2657 0 : do {
2658 0 : int wait_ms, overall_ms;
2659 0 : if (!deadline_remaining_ms(connect_dl, &wait_ms) ||
2660 0 : !deadline_remaining_ms(overall, &overall_ms)) {
2661 0 : close(fd);
2662 0 : return ccol_timed_out;
2663 : }
2664 0 : prv = conn_wait(fd, POLLOUT, combine_ms(wait_ms, overall_ms),
2665 : ccol_http_connection_failed);
2666 0 : } while (prv == ccol_timed_out);
2667 0 : if (prv != ccol_success) {
2668 0 : close(fd);
2669 0 : return prv;
2670 : }
2671 :
2672 0 : int soerr = 0;
2673 0 : socklen_t slen = sizeof(soerr);
2674 0 : if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 || soerr != 0) {
2675 0 : close(fd);
2676 0 : return ccol_http_connection_failed;
2677 : }
2678 :
2679 0 : *fd_out = fd;
2680 0 : return ccol_success;
2681 : }
2682 :
2683 : // Runs the client TLS handshake on conn for Tier 1, within the connect and
2684 : // overall deadlines (the handshake counts against the connect timeout, as in
2685 : // curl). A failed peer verification and a socket error during it are both
2686 : // ccol_http_tls_handshake_failed, as in Tiers 2 and 3.
2687 48 : static ccol_retval tls_handshake(chttp_conn *conn, chttp_deadline *connect_dl,
2688 : chttp_deadline *overall) {
2689 95 : for (;;) {
2690 95 : ctls_handshake_result r = ctls_conn_handshake_step(conn->tls);
2691 95 : if (r == CTLS_HANDSHAKE_DONE) return ccol_success;
2692 62 : if (r == CTLS_HANDSHAKE_ERROR) {
2693 14 : long vr = ctls_conn_verify_result(conn->tls);
2694 14 : return (vr != 0) ? ccol_http_tls_cert_verification_failed
2695 14 : : ccol_http_tls_handshake_failed;
2696 : }
2697 :
2698 48 : short ev = (r == CTLS_HANDSHAKE_WANT_WRITE) ? POLLOUT : POLLIN;
2699 48 : int wait_ms, overall_ms;
2700 48 : if (!deadline_remaining_ms(connect_dl, &wait_ms)) return ccol_timed_out;
2701 48 : if (!deadline_remaining_ms(overall, &overall_ms)) return ccol_timed_out;
2702 96 : ccol_retval prv = conn_wait(conn->fd, ev, combine_ms(wait_ms, overall_ms),
2703 : ccol_http_tls_handshake_failed);
2704 48 : if (prv == ccol_timed_out) continue;
2705 48 : if (prv != ccol_success) return prv;
2706 : }
2707 : }
2708 :
2709 : // Maps a failure to create the client side of a TLS connection to the code the
2710 : // request reports, from ctls's err. ctls's refusal to verify an empty host name
2711 : // is ccol_http_invalid_url (the URL can't be used for https at all); anything
2712 : // else is ccol_not_enough_memory.
2713 2 : static ccol_retval tls_client_create_failure_code(const char *err) {
2714 2 : if (!err) return ccol_not_enough_memory;
2715 2 : if (strstr(err, "verification requested with no hostname"))
2716 : return ccol_http_invalid_url;
2717 0 : if (strstr(err, "invalid arguments")) return ccol_unexpected_failure;
2718 : return ccol_not_enough_memory;
2719 : }
2720 :
2721 : // Creates the client TLS connection on fd. One trailing dot is stripped from
2722 : // the name TLS sends and verifies, as curl and Go do (SNI forbids it), while
2723 : // the Host header keeps the name as written.
2724 158 : static ctls_conn *tls_client_create(ctls_ctx *tls_ctx, int fd, const char *host,
2725 : bool verify_host, ccol_retval *rv_out) {
2726 158 : char undotted[256];
2727 158 : const char *tls_name = host;
2728 158 : size_t hlen = host ? strlen(host) : 0;
2729 157 : if (hlen > 1 && host[hlen - 1] == '.' && hlen - 1 < sizeof(undotted)) {
2730 2 : memcpy(undotted, host, hlen - 1);
2731 2 : undotted[hlen - 1] = '\0';
2732 2 : tls_name = undotted;
2733 : }
2734 158 : char *err = NULL;
2735 158 : ctls_conn *c =
2736 158 : ctls_conn_create_client(tls_ctx, fd, tls_name, verify_host, &err);
2737 158 : *rv_out = c ? ccol_success : tls_client_create_failure_code(err);
2738 158 : return c;
2739 : }
2740 :
2741 : #ifdef RUNNING_UNIT_TESTS
2742 : // Runs tls_client_create on a socket pair and gives the code a request would
2743 : // report, so a test can reach the empty-host refusal that no URL can produce.
2744 5 : ccol_retval chttp__tls_client_create_code_for_tests(const char *host,
2745 : bool verify_host) {
2746 5 : int sv[2];
2747 5 : if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0)
2748 : return ccol_unexpected_failure;
2749 5 : ctls_ctx *tctx = ctls_ctx_new_mp(NULL, NULL);
2750 5 : ccol_retval rv = ccol_unexpected_failure;
2751 5 : if (tctx) {
2752 5 : ctls_conn *c = tls_client_create(tctx, sv[0], host, verify_host, &rv);
2753 5 : if (c) ctls_conn_destroy(c);
2754 5 : ctls_ctx_release(tctx);
2755 : }
2756 5 : close(sv[0]);
2757 5 : close(sv[1]);
2758 5 : return rv;
2759 : }
2760 :
2761 : // Runs a full TLS handshake over a socket pair, so a test can check SNI and
2762 : // name verification: The client verifies host against ca_path, the server
2763 : // offers default_cert and named_cert under the SNI name named_as. Gives true
2764 : // when both sides finish.
2765 4 : bool chttp__tls_client_handshake_for_tests(
2766 : const char *host, const char *ca_path, const char *default_cert,
2767 : const char *default_key, const char *named_as, const char *named_cert,
2768 : const char *named_key) {
2769 4 : int sv[2];
2770 4 : if (ccol_socketpair_nb(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return false;
2771 4 : bool ok = false;
2772 4 : ctls_ctx *cctx = ctls_ctx_new_mp(NULL, NULL);
2773 4 : ctls_ctx *sctx = ctls_ctx_new_mp(NULL, NULL);
2774 4 : ctls_conn *cc = NULL, *sc = NULL;
2775 4 : ccol_retval rv = ccol_unexpected_failure;
2776 8 : if (cctx && sctx && ctls_ctx_trust(cctx, ca_path, NULL) == ccol_success &&
2777 4 : ctls_ctx_cert_add(sctx, NULL, default_cert, default_key, NULL, NULL) ==
2778 4 : ccol_success &&
2779 4 : ctls_ctx_cert_add(sctx, named_as, named_cert, named_key, NULL, NULL) ==
2780 : ccol_success) {
2781 4 : cc = tls_client_create(cctx, sv[0], host, true, &rv);
2782 4 : sc = ctls_conn_create_server(sctx, sv[1], NULL, NULL);
2783 : }
2784 4 : if (cc && sc) {
2785 : bool cdone = false, sdone = false, failed = false;
2786 12 : for (int i = 0; i < 2000 && !failed && !(cdone && sdone); i++) {
2787 8 : if (!cdone) {
2788 8 : ctls_handshake_result r = ctls_conn_handshake_step(cc);
2789 8 : cdone = (r == CTLS_HANDSHAKE_DONE);
2790 8 : failed = (r == CTLS_HANDSHAKE_ERROR);
2791 : }
2792 8 : if (!sdone && !failed) {
2793 7 : ctls_handshake_result r = ctls_conn_handshake_step(sc);
2794 7 : sdone = (r == CTLS_HANDSHAKE_DONE);
2795 7 : failed = (r == CTLS_HANDSHAKE_ERROR);
2796 : }
2797 8 : if (!failed && !(cdone && sdone)) {
2798 4 : struct pollfd p[2] = {{.fd = sv[0], .events = POLLIN},
2799 4 : {.fd = sv[1], .events = POLLIN}};
2800 4 : (void)poll(p, 2, 5);
2801 : }
2802 : }
2803 5 : ok = cdone && sdone && !failed;
2804 : }
2805 4 : if (cc) ctls_conn_destroy(cc);
2806 4 : if (sc) ctls_conn_destroy(sc);
2807 4 : if (cctx) ctls_ctx_release(cctx);
2808 4 : if (sctx) ctls_ctx_release(sctx);
2809 4 : close(sv[0]);
2810 4 : close(sv[1]);
2811 4 : return ok;
2812 : }
2813 : #endif
2814 :
2815 : // Opens a connection to url (unix or TCP, then TLS for https) into *out within
2816 : // the deadlines. tls_generation is the client's generation, read by the caller
2817 : // under cli->lock together with tls_ctx; we stamp it on the connection for the
2818 : // idle pool.
2819 548 : static ccol_retval conn_open(ccol_memmgmt_procs *mp, const chttp_url *url,
2820 : bool want_tls, ctls_ctx *tls_ctx, bool verify_host,
2821 : uint64_t tls_generation,
2822 : chttp_deadline *connect_dl,
2823 : chttp_deadline *overall, chttp_conn *out) {
2824 548 : memset(out, 0, sizeof(*out));
2825 548 : out->fd = -1;
2826 548 : out->tls_generation = tls_generation;
2827 :
2828 548 : int fd = -1;
2829 1096 : ccol_retval rv =
2830 548 : url->is_unix
2831 13 : ? unix_connect(url->unix_socket_path, connect_dl, overall, &fd)
2832 548 : : tcp_connect(mp, url->host, url->port, connect_dl, overall, &fd);
2833 548 : if (rv != ccol_success) return rv;
2834 541 : out->fd = fd;
2835 :
2836 541 : if (want_tls) {
2837 48 : ccol_retval crv;
2838 48 : out->tls = tls_client_create(tls_ctx, fd, url->host, verify_host, &crv);
2839 48 : if (!out->tls) {
2840 0 : close(fd);
2841 0 : out->fd = -1;
2842 15 : return crv;
2843 : }
2844 48 : rv = tls_handshake(out, connect_dl, overall);
2845 48 : if (rv != ccol_success) {
2846 15 : ctls_conn_destroy(out->tls);
2847 15 : close(fd);
2848 15 : out->fd = -1;
2849 15 : out->tls = NULL;
2850 15 : return rv;
2851 : }
2852 : }
2853 :
2854 526 : out->origin_key = ccol_strdup(mp, url->origin_key);
2855 526 : if (!out->origin_key) {
2856 1 : if (out->tls) ctls_conn_destroy(out->tls);
2857 1 : close(fd);
2858 1 : out->fd = -1;
2859 1 : out->tls = NULL;
2860 1 : return ccol_not_enough_memory;
2861 : }
2862 :
2863 525 : clock_gettime(CLOCK_MONOTONIC, &out->last_used);
2864 525 : return ccol_success;
2865 : }
2866 :
2867 : // Closes connection c (TLS first) and frees its origin key, for every path that
2868 : // drops a Tier 1 connection. c's fields are reset.
2869 524 : static void conn_teardown(ccol_memmgmt_procs *mp, chttp_conn *c) {
2870 524 : if (!c) return;
2871 524 : if (c->tls) ctls_conn_destroy(c->tls);
2872 524 : if (c->fd >= 0) close(c->fd);
2873 523 : ccol__mem_free(mp, c->origin_key);
2874 524 : memset(c, 0, sizeof(*c));
2875 524 : c->fd = -1;
2876 : }
2877 :
2878 : // Concurrency limiter
2879 : //
2880 : // Gives the limiter size for a configured pool size (0 picks a default from the
2881 : // CPU count), so create and chttpcli_set_pool_size agree on it.
2882 302 : static size_t resolve_pool_cap(size_t configured) {
2883 302 : if (configured != 0) return configured;
2884 256 : long np = sysconf(_SC_NPROCESSORS_ONLN);
2885 256 : return (np > 0) ? (size_t)np : 1;
2886 : }
2887 :
2888 : // Takes a limiter slot, blocking while the pool is full. If deadline (NULL or
2889 : // inactive for none) passes first it gives ccol_timed_out, so the request
2890 : // timeout holds while the pool is full. Fails with ccol_not_permitted once the
2891 : // client is being destroyed. Takes cli->lock.
2892 625 : static ccol_retval slot_acquire(struct chttpclient *cli,
2893 : const chttp_deadline *deadline) {
2894 625 : ccol__mutex_lock(cli->lock);
2895 625 : if (cli->destroying) {
2896 0 : ccol__mutex_unlock(cli->lock);
2897 0 : return ccol_not_permitted;
2898 : }
2899 625 : if (!cli->pool_initialized) {
2900 254 : cli->pool_cap = resolve_pool_cap(cli->configured_pool_size);
2901 254 : cli->pool_initialized = true;
2902 : }
2903 670 : while (cli->in_flight_count >= cli->pool_cap && !cli->destroying) {
2904 46 : if (deadline && deadline->active) {
2905 1 : int wrc = ccol__cond_var_timedwait(cli->available, cli->lock,
2906 : deadline->deadline);
2907 1 : if (wrc == ETIMEDOUT) {
2908 1 : ccol__mutex_unlock(cli->lock);
2909 1 : return ccol_timed_out;
2910 : }
2911 : } else {
2912 45 : ccol__cond_var_wait(cli->available, cli->lock);
2913 : }
2914 : }
2915 624 : if (cli->destroying) {
2916 1 : ccol__mutex_unlock(cli->lock);
2917 1 : return ccol_not_permitted;
2918 : }
2919 623 : cli->in_flight_count++;
2920 623 : ccol__mutex_unlock(cli->lock);
2921 623 : return ccol_success;
2922 : }
2923 :
2924 : // Gives a limiter slot back and wakes one waiter, at the end of every Tier 1
2925 : // request. Takes cli->lock and changes in_flight_count.
2926 622 : static void slot_release(struct chttpclient *cli) {
2927 622 : ccol__mutex_lock(cli->lock);
2928 622 : cli->in_flight_count--;
2929 622 : ccol__cond_var_broadcast(cli->available);
2930 622 : ccol__mutex_unlock(cli->lock);
2931 622 : }
2932 :
2933 : // Keep-alive idle pool
2934 : //
2935 : // Reads a cvec handle stored in a map value through memcpy, the pattern every
2936 : // module uses for pointers it keeps in a chmap.
2937 1465 : static inline cvec read_cvec(const void *src) {
2938 1465 : cvec v;
2939 1465 : memcpy(&v, src, sizeof(v));
2940 202 : return v;
2941 : }
2942 :
2943 : // Pops a usable idle connection for origin_key into *out, or gives false.
2944 : // Stale, dead and TLS-outdated candidates are closed on the way. The age check
2945 : // and the liveness probe run outside cli->lock, since we never do I/O under it.
2946 : // An origin whose list runs empty loses its map entry.
2947 672 : static bool idle_pool_take(struct chttpclient *cli, const char *origin_key,
2948 : chttp_conn *out) {
2949 2 : for (;;) {
2950 674 : bool got = false;
2951 674 : uint64_t cur_tls_generation;
2952 674 : ccol__mutex_lock(cli->lock);
2953 674 : cur_tls_generation = cli->tls_generation;
2954 674 : if (cli->idle_pools) {
2955 674 : cmap_pair kp = {.ptr = (void *)origin_key,
2956 674 : .size = strlen(origin_key) + 1};
2957 674 : cmap_pair vp;
2958 674 : if (chashmap_get_elem_ref(cli->idle_pools, &kp, &vp) == ccol_success) {
2959 132 : cvec list = read_cvec(vp.ptr);
2960 264 : if (list && cvector_size(list) > 0 &&
2961 132 : cvector_pop_back(list, out) == ccol_success) {
2962 132 : got = true;
2963 132 : if (cli->idle_total_count > 0) cli->idle_total_count--;
2964 132 : if (cvector_size(list) == 0) {
2965 94 : cvector__destroy(list);
2966 94 : chashmap_remove_elem(cli->idle_pools, &kp);
2967 : }
2968 : }
2969 : }
2970 : }
2971 674 : ccol__mutex_unlock(cli->lock);
2972 674 : if (!got) return false;
2973 :
2974 132 : struct timespec now;
2975 132 : clock_gettime(CLOCK_MONOTONIC, &now);
2976 132 : int64_t age_ms = ms_elapsed_floor(&out->last_used, &now);
2977 :
2978 264 : bool tls_config_current =
2979 132 : (!out->tls || out->tls_generation == cur_tls_generation);
2980 :
2981 132 : bool alive = false;
2982 132 : if (age_ms <= CHTTP_IDLE_MAX_AGE_MS && tls_config_current) {
2983 131 : char probe;
2984 131 : ssize_t pn;
2985 131 : if (out->tls) {
2986 3 : pn = ctls_conn_read(out->tls, &probe, 1);
2987 : } else {
2988 128 : do {
2989 128 : pn = recv(out->fd, &probe, 1, MSG_PEEK | MSG_DONTWAIT);
2990 128 : } while (pn < 0 && errno == EINTR);
2991 : }
2992 131 : alive = (pn < 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
2993 : }
2994 131 : if (alive) return true;
2995 :
2996 2 : conn_teardown(cli->m_procs, out);
2997 : }
2998 : }
2999 :
3000 : // Gives a good connection back to cli's idle pool, so the next request to the
3001 : // same origin skips the connect. It closes c instead when a cap is full, the
3002 : // origin cap leaves no room for a new origin, or the client is being destroyed.
3003 : // Takes cli->lock and changes idle_pools and idle_total_count.
3004 224 : static void idle_pool_offer(struct chttpclient *cli, chttp_conn *c) {
3005 224 : bool pooled = false;
3006 224 : ccol__mutex_lock(cli->lock);
3007 224 : if (!cli->destroying && cli->idle_pools &&
3008 224 : cli->idle_total_count < CHTTP_MAX_IDLE_TOTAL) {
3009 224 : cmap_pair kp = {.ptr = c->origin_key, .size = strlen(c->origin_key) + 1};
3010 224 : cmap_pair vp;
3011 224 : cvec list = NULL;
3012 224 : if (chashmap_get_elem_ref(cli->idle_pools, &kp, &vp) == ccol_success) {
3013 46 : list = read_cvec(vp.ptr);
3014 : }
3015 402 : if (!list &&
3016 178 : chashmap_size(cli->idle_pools) < effective_max_idle_origins()) {
3017 176 : char *cverr = NULL;
3018 176 : list = cvector_create_full(sizeof(chttp_conn), cli->m_procs, &cverr);
3019 176 : if (list) {
3020 176 : cmap_pair vp2 = {.ptr = &list, .size = sizeof(list)};
3021 176 : if (chashmap_insert_elem(cli->idle_pools, &kp, &vp2) != ccol_success) {
3022 0 : cvector__destroy(list);
3023 0 : list = NULL;
3024 : }
3025 : }
3026 : }
3027 224 : if (list && cvector_size(list) < CHTTP_MAX_IDLE_PER_ORIGIN) {
3028 218 : clock_gettime(CLOCK_MONOTONIC, &c->last_used);
3029 218 : if (cvector_push_back(list, c) == ccol_success) {
3030 218 : pooled = true;
3031 218 : cli->idle_total_count++;
3032 : }
3033 : }
3034 : }
3035 224 : ccol__mutex_unlock(cli->lock);
3036 224 : if (!pooled) conn_teardown(cli->m_procs, c);
3037 224 : }
3038 :
3039 : // Request serialization
3040 : //
3041 : // Which of the headers serialize_request has a default for are present, found
3042 : // in one case-insensitive pass over the map (a caller may lend a map whose keys
3043 : // keep their natural case). idempotency_key and connection_close feed the retry
3044 : // and pooling decisions.
3045 : typedef struct {
3046 : bool has_host;
3047 : bool has_accept;
3048 : bool has_user_agent;
3049 : bool has_content_length;
3050 : bool has_content_type;
3051 : bool has_authorization;
3052 : bool has_expect;
3053 : bool has_transfer_encoding;
3054 : bool has_idempotency_key;
3055 : bool request_close;
3056 : } chttp_header_presence;
3057 :
3058 : // Tells whether a Connection value v lists the "close" token (RFC 9110 section
3059 : // 7.6.1, ASCII case ignored), so a request that asks for close is never pooled.
3060 17 : static bool connection_value_has_close(const char *v) {
3061 17 : const char *p = v;
3062 26 : while (*p) {
3063 35 : while (*p == ' ' || *p == '\t' || *p == ',') p++;
3064 : const char *start = p;
3065 174 : while (*p && *p != ',') p++;
3066 : const char *end = p;
3067 26 : while (end > start && (end[-1] == ' ' || end[-1] == '\t')) end--;
3068 23 : if (end - start == 5 && ccol_ascii_ncasecmp(start, "close", 5) == 0)
3069 : return true;
3070 : }
3071 : return false;
3072 : }
3073 :
3074 : // Scans headers once for the names serialize_request and the retry rules care
3075 : // about, case ignored, since a borrowed map may keep natural case. Gives the
3076 : // flags; *failed is set when the map iterator can't be allocated, and the flags
3077 : // are unknown then.
3078 1681 : static chttp_header_presence scan_header_presence(chmap headers, bool *failed) {
3079 1681 : chttp_header_presence p = {0};
3080 1681 : *failed = false;
3081 1681 : if (!headers) return p;
3082 137 : char *ierr = NULL;
3083 137 : cmap_iterator *it = chashmap_begin_iter(headers, &ierr);
3084 137 : if (!it && ierr) {
3085 1 : *failed = true;
3086 1 : return p;
3087 : }
3088 502 : for (; it; it = it->ccol__next_fn(it)) {
3089 366 : const char *name = (const char *)it->key_pair->ptr;
3090 732 : if (ccol_ascii_casecmp(name, "host") == 0)
3091 : p.has_host = true;
3092 321 : else if (ccol_ascii_casecmp(name, "accept") == 0)
3093 : p.has_accept = true;
3094 320 : else if (ccol_ascii_casecmp(name, "user-agent") == 0)
3095 : p.has_user_agent = true;
3096 319 : else if (ccol_ascii_casecmp(name, "content-length") == 0)
3097 : p.has_content_length = true;
3098 309 : else if (ccol_ascii_casecmp(name, "content-type") == 0)
3099 : p.has_content_type = true;
3100 301 : else if (ccol_ascii_casecmp(name, "authorization") == 0)
3101 : p.has_authorization = true;
3102 236 : else if (ccol_ascii_casecmp(name, "expect") == 0)
3103 : p.has_expect = true;
3104 229 : else if (ccol_ascii_casecmp(name, "transfer-encoding") == 0)
3105 : p.has_transfer_encoding = true;
3106 228 : else if (ccol_ascii_casecmp(name, "idempotency-key") == 0 ||
3107 225 : ccol_ascii_casecmp(name, "x-idempotency-key") == 0)
3108 : p.has_idempotency_key = true;
3109 239 : else if (ccol_ascii_casecmp(name, "connection") == 0 &&
3110 17 : connection_value_has_close((const char *)it->val_pair->ptr))
3111 366 : p.request_close = true;
3112 : }
3113 136 : return p;
3114 : }
3115 :
3116 : // True when a request that went out in full on a reused connection that died
3117 : // without an answer may be sent again: An idempotent method (GET, HEAD,
3118 : // OPTIONS, PUT, DELETE) or an Idempotency-Key or X-Idempotency-Key header, as
3119 : // in Go.
3120 1641 : static bool request_is_replayable(chttp_method method,
3121 : const chttp_header_presence *hp) {
3122 1641 : switch (method) {
3123 : case CHTTP_GET:
3124 : case CHTTP_HEAD:
3125 : case CHTTP_OPTIONS:
3126 : case CHTTP_PUT:
3127 : case CHTTP_DELETE:
3128 : return true;
3129 194 : default:
3130 194 : return hp->has_idempotency_key;
3131 : }
3132 : }
3133 :
3134 : // The header names serialize_request has sent, compared ignoring case, so a
3135 : // borrowed map with both "Host" and "host" puts one line on the wire. The names
3136 : // are borrowed.
3137 : typedef struct {
3138 : const char **names;
3139 : size_t count;
3140 : size_t cap;
3141 : } chttp_seen_names;
3142 :
3143 : // Tells whether seen already holds name (ASCII case ignored), so the serializer
3144 : // writes each header name once.
3145 265 : static bool seen_names_contains(const chttp_seen_names *seen,
3146 : const char *name) {
3147 645 : for (size_t i = 0; i < seen->count; i++)
3148 762 : if (ccol_ascii_casecmp(seen->names[i], name) == 0) return true;
3149 : return false;
3150 : }
3151 :
3152 : // Records the borrowed name in seen, so later names that differ only in case
3153 : // are skipped. Gives false when the array can't grow (the size computation is
3154 : // overflow-guarded).
3155 262 : static bool seen_names_add(ccol_memmgmt_procs *mp, chttp_seen_names *seen,
3156 : const char *name) {
3157 262 : if (seen->count == seen->cap) {
3158 123 : if (seen->cap > SIZE_MAX / 2) return false;
3159 122 : size_t nc = seen->cap ? seen->cap * 2 : 8;
3160 0 : if (nc > SIZE_MAX / sizeof(*seen->names)) return false;
3161 122 : const char **nn = (const char **)ccol__mem_realloc(mp, (void *)seen->names,
3162 : nc * sizeof(*nn));
3163 122 : if (!nn) return false;
3164 122 : seen->names = nn;
3165 122 : seen->cap = nc;
3166 : }
3167 261 : seen->names[seen->count++] = name;
3168 261 : return true;
3169 : }
3170 :
3171 : #ifdef RUNNING_UNIT_TESTS
3172 : // Lets a test drive the overflow guard of seen_names_add with a made-up
3173 : // capacity and no real array.
3174 2 : bool chttp__seen_names_add_overflow_guard_for_tests(ccol_memmgmt_procs *mp,
3175 : size_t fake_cap) {
3176 2 : chttp_seen_names seen = {.names = NULL, .count = fake_cap, .cap = fake_cap};
3177 2 : bool added = seen_names_add(mp, &seen, "x");
3178 2 : ccol__mem_free(mp, (void *)seen.names);
3179 2 : return !added;
3180 : }
3181 : #endif
3182 :
3183 : // A growable output buffer. oom latches the first failed growth.
3184 : typedef struct {
3185 : char *buf;
3186 : size_t len;
3187 : size_t cap;
3188 : ccol_memmgmt_procs *mp;
3189 : bool oom;
3190 : } chttp_outbuf;
3191 :
3192 : // Gives the next capacity for a buffer of cap bytes that needs need (> cap):
3193 : // initial for an empty one, else doubled until it fits. A doubling past
3194 : // SIZE_MAX gives need, so the capacity never wraps (on ILP32 2 GiB doubles to
3195 : // 0).
3196 3012 : static size_t chttp_grow_capacity(size_t cap, size_t need, size_t initial) {
3197 3012 : if (cap == 0) {
3198 : cap = initial;
3199 : } else {
3200 122 : if (cap > SIZE_MAX / 2) return need;
3201 120 : cap *= 2;
3202 : }
3203 3533 : while (cap < need) {
3204 523 : if (cap > SIZE_MAX / 2) return need;
3205 523 : cap *= 2;
3206 : }
3207 : return cap;
3208 : }
3209 :
3210 : // Appends n bytes to b, for building the request bytes. On an overflowing size
3211 : // or a failed growth it sets b->oom and leaves the content as it was.
3212 20330 : static void ob_append(chttp_outbuf *b, const char *data, size_t n) {
3213 20330 : if (b->oom) return;
3214 20295 : if (n > SIZE_MAX - b->len || b->len + n > SIZE_MAX - 1) {
3215 1 : b->oom = true;
3216 1 : return;
3217 : }
3218 20294 : size_t need = b->len + n + 1;
3219 20294 : if (need > b->cap) {
3220 1723 : size_t nc = chttp_grow_capacity(b->cap, need, 1024);
3221 1723 : char *nb = (char *)ccol__mem_realloc(b->mp, b->buf, nc);
3222 1723 : if (!nb) {
3223 4 : b->oom = true;
3224 4 : return;
3225 : }
3226 1719 : b->buf = nb;
3227 1719 : b->cap = nc;
3228 : }
3229 20290 : memcpy(b->buf + b->len, data, n);
3230 20290 : b->len += n;
3231 20290 : b->buf[b->len] = '\0';
3232 : }
3233 :
3234 : // Appends the NUL-terminated string s to b, for the literal parts of the
3235 : // request.
3236 12628 : static void ob_append_cstr(chttp_outbuf *b, const char *s) {
3237 12628 : ob_append(b, s, strlen(s));
3238 3423 : }
3239 :
3240 : #ifdef RUNNING_UNIT_TESTS
3241 : // Let a test drive ob_append: One drives the overflow guard with a made-up
3242 : // length and a counting allocator, the other grows from a capacity whose
3243 : // doubling would pass SIZE_MAX. Both give whether b->oom was set.
3244 2 : bool chttp__ob_append_overflow_guard_for_tests(ccol_memmgmt_procs *mp,
3245 : size_t fake_len, size_t n) {
3246 2 : chttp_outbuf ob = {.mp = mp, .len = fake_len};
3247 2 : char probe[64] = {0};
3248 2 : if (n > sizeof(probe)) n = sizeof(probe);
3249 2 : ob_append(&ob, probe, n);
3250 2 : bool oom = ob.oom;
3251 2 : ccol__mem_free(mp, ob.buf);
3252 2 : return oom;
3253 : }
3254 :
3255 1 : bool chttp__ob_append_cap_overflow_for_tests(ccol_memmgmt_procs *mp,
3256 : size_t fake_cap) {
3257 1 : chttp_outbuf ob = {.mp = mp, .len = fake_cap - 1, .cap = fake_cap};
3258 1 : char probe[8] = {0};
3259 1 : ob_append(&ob, probe, sizeof(probe));
3260 1 : return ob.oom;
3261 : }
3262 : #endif
3263 :
3264 : // Which caller-set headers a redirect hop leaves off. Every tier judges each
3265 : // hop against the first request's origin, never the previous hop (curl's rule).
3266 : // DROP_CREDENTIALS: Scheme, host or port differ, so Authorization, Cookie,
3267 : // Cookie2 and WWW-Authenticate go. DROP_HOST: The host differs, so a caller-set
3268 : // Host goes too.
3269 : #define CHTTP_REDIRECT_DROP_CREDENTIALS 0x1u
3270 : #define CHTTP_REDIRECT_DROP_HOST 0x2u
3271 :
3272 : // Finds the host part of an origin key (between "://" and the port for TCP, the
3273 : // whole path for "unix://"), so redirect_header_drops can compare hosts. *start
3274 : // and *len describe it.
3275 50 : static void origin_key_host_span(const char *key, const char **start,
3276 : size_t *len) {
3277 50 : const char *sep = strstr(key, "://");
3278 50 : const char *h = sep ? sep + 3 : key;
3279 50 : if (strncmp(key, "unix://", 7) == 0) {
3280 0 : *start = h;
3281 0 : *len = strlen(h);
3282 0 : return;
3283 : }
3284 50 : const char *colon = strrchr(h, ':');
3285 50 : *start = h;
3286 50 : *len = colon ? (size_t)(colon - h) : strlen(h);
3287 : }
3288 :
3289 : // Tells whether two origin keys are the same origin for carrying credentials
3290 : // across a redirect. A TCP key compares ignoring ASCII case, like DNS names; a
3291 : // "unix://" key compares byte for byte, like a file name.
3292 1102 : static bool origin_keys_same(const char *a, const char *b) {
3293 1102 : bool a_unix = strncmp(a, "unix://", 7) == 0;
3294 1102 : bool b_unix = strncmp(b, "unix://", 7) == 0;
3295 1102 : if (a_unix || b_unix) return a_unix == b_unix && strcmp(a, b) == 0;
3296 1089 : return ccol_ascii_casecmp(a, b) == 0;
3297 : }
3298 :
3299 : // Gives the CHTTP_REDIRECT_DROP_* flags for a hop to origin_key, judged against
3300 : // the first request's origin, so every tier drops the same headers.
3301 1088 : static unsigned redirect_header_drops(const char *initial_origin_key,
3302 : const char *origin_key) {
3303 1088 : if (!initial_origin_key || origin_keys_same(initial_origin_key, origin_key))
3304 : return 0;
3305 25 : unsigned drops = CHTTP_REDIRECT_DROP_CREDENTIALS;
3306 25 : const char *a, *b;
3307 25 : size_t alen, blen;
3308 25 : origin_key_host_span(initial_origin_key, &a, &alen);
3309 25 : origin_key_host_span(origin_key, &b, &blen);
3310 25 : bool a_unix = strncmp(initial_origin_key, "unix://", 7) == 0;
3311 25 : bool b_unix = strncmp(origin_key, "unix://", 7) == 0;
3312 25 : bool same_host;
3313 25 : if (a_unix != b_unix || alen != blen) {
3314 : same_host = false;
3315 21 : } else if (a_unix) {
3316 0 : same_host = memcmp(a, b, alen) == 0;
3317 : } else {
3318 21 : same_host = ccol_ascii_ncasecmp(a, b, alen) == 0;
3319 : }
3320 21 : if (!same_host) drops |= CHTTP_REDIRECT_DROP_HOST;
3321 : return drops;
3322 : }
3323 :
3324 : // True for the headers CHTTP_REDIRECT_DROP_CREDENTIALS takes off.
3325 113 : static bool is_redirect_credential_header(const char *name) {
3326 113 : return ccol_ascii_casecmp(name, "authorization") == 0 ||
3327 90 : ccol_ascii_casecmp(name, "cookie") == 0 ||
3328 185 : ccol_ascii_casecmp(name, "cookie2") == 0 ||
3329 54 : ccol_ascii_casecmp(name, "www-authenticate") == 0;
3330 : }
3331 :
3332 : // Serializes the request line, the headers and the body into one buffer. req is
3333 : // a per-hop view, so a redirect changes the method and body there. It refuses
3334 : // an invalid method, a Transfer-Encoding header, a value that fails
3335 : // header_value_is_valid and a failed header walk; it adds Host, Content-Length,
3336 : // Content-Type and the URL's Authorization unless the caller set them, and
3337 : // writes each name once. out_presence (may be NULL) gets the header presence it
3338 : // computed.
3339 1683 : static ccol_retval serialize_request(
3340 : ccol_memmgmt_procs *mp, const chttp_request *req, const chttp_url *url,
3341 : const char *auto_authorization, unsigned redirect_drops, char **out_buf,
3342 : size_t *out_len, chttp_header_presence *out_presence) {
3343 1683 : if ((unsigned)req->method >= (unsigned)CHTTP_ANY) return ccol_invalid_args;
3344 1681 : chttp_outbuf ob = {.mp = mp};
3345 :
3346 1681 : ob_append_cstr(&ob, chttp_method_str(req->method));
3347 1681 : ob_append(&ob, " ", 1);
3348 1681 : ob_append_cstr(&ob, url->path_and_query);
3349 1681 : ob_append_cstr(&ob, " HTTP/1.1\r\n");
3350 :
3351 1681 : bool scan_failed;
3352 1681 : chttp_header_presence hp =
3353 1681 : scan_header_presence((chmap)req->headers, &scan_failed);
3354 1681 : if (scan_failed) {
3355 1 : ccol__mem_free(mp, ob.buf);
3356 1 : return ccol_not_enough_memory;
3357 : }
3358 1680 : if (hp.has_transfer_encoding) {
3359 1 : ccol__mem_free(mp, ob.buf);
3360 1 : return ccol_invalid_args;
3361 : }
3362 1679 : bool has_host = hp.has_host && !(redirect_drops & CHTTP_REDIRECT_DROP_HOST);
3363 1679 : bool has_accept = hp.has_accept;
3364 1679 : bool has_ua = hp.has_user_agent;
3365 1679 : bool has_cl = hp.has_content_length;
3366 1679 : bool has_ct = hp.has_content_type;
3367 1679 : bool has_auth = hp.has_authorization &&
3368 65 : !(redirect_drops & CHTTP_REDIRECT_DROP_CREDENTIALS);
3369 :
3370 1679 : if (!has_host) {
3371 1647 : if (url->is_unix) {
3372 29 : ob_append_cstr(&ob, "host: localhost\r\n");
3373 : } else {
3374 1618 : bool default_port = (url->is_https && url->port == 443) ||
3375 1410 : (!url->is_https && url->port == 80);
3376 1618 : ob_append_cstr(&ob, "host: ");
3377 1618 : if (url->is_ipv6) ob_append(&ob, "[", 1);
3378 1618 : ob_append_cstr(&ob, url->host);
3379 1618 : if (url->is_ipv6) ob_append(&ob, "]", 1);
3380 1618 : if (!default_port) {
3381 1594 : char portbuf[16];
3382 1594 : int pn = snprintf(portbuf, sizeof(portbuf), ":%u", (unsigned)url->port);
3383 1594 : if (pn > 0) ob_append(&ob, portbuf, (size_t)pn);
3384 : }
3385 1618 : ob_append(&ob, "\r\n", 2);
3386 : }
3387 : }
3388 1679 : if (!has_accept) ob_append_cstr(&ob, "accept: */*\r\n");
3389 1679 : if (!has_ua)
3390 1678 : ob_append_cstr(&ob, "user-agent: c_collections-chttpclient/1.0\r\n");
3391 1679 : if (!has_auth && auto_authorization) {
3392 13 : ob_append_cstr(&ob, "authorization: ");
3393 13 : ob_append_cstr(&ob, auto_authorization);
3394 13 : ob_append(&ob, "\r\n", 2);
3395 : }
3396 :
3397 1679 : bool body_carrying_method =
3398 1679 : (req->method == CHTTP_POST || req->method == CHTTP_PUT ||
3399 : req->method == CHTTP_PATCH);
3400 :
3401 1679 : if (req->headers) {
3402 135 : chttp_seen_names seen = {0};
3403 135 : char *ierr = NULL;
3404 135 : cmap_iterator *it = chashmap_begin_iter((chmap)req->headers, &ierr);
3405 135 : if (!it && ierr) {
3406 1 : ccol__mem_free(mp, ob.buf);
3407 10 : return ccol_not_enough_memory;
3408 : }
3409 490 : for (; it; it = it->ccol__next_fn(it)) {
3410 364 : const char *name = (const char *)it->key_pair->ptr;
3411 364 : const char *val = (const char *)it->val_pair->ptr;
3412 728 : if (!*name || !header_value_is_valid(val)) {
3413 2 : ccol_iter_destroy(it);
3414 2 : ccol__mem_free(mp, (void *)seen.names);
3415 2 : ccol__mem_free(mp, ob.buf);
3416 2 : return ccol_invalid_args;
3417 : }
3418 3747 : for (const char *p = name; *p; p++) {
3419 3387 : if (!chttp1_is_tchar((unsigned char)*p)) {
3420 2 : ccol_iter_destroy(it);
3421 2 : ccol__mem_free(mp, (void *)seen.names);
3422 2 : ccol__mem_free(mp, ob.buf);
3423 2 : return ccol_invalid_args;
3424 : }
3425 : }
3426 360 : if (!body_carrying_method &&
3427 325 : (ccol_ascii_casecmp(name, "content-length") == 0 ||
3428 323 : ccol_ascii_casecmp(name, "content-type") == 0 ||
3429 321 : ccol_ascii_casecmp(name, "expect") == 0))
3430 6 : continue;
3431 467 : if ((redirect_drops & CHTTP_REDIRECT_DROP_CREDENTIALS) &&
3432 113 : is_redirect_credential_header(name))
3433 77 : continue;
3434 277 : if ((redirect_drops & CHTTP_REDIRECT_DROP_HOST) &&
3435 24 : ccol_ascii_casecmp(name, "host") == 0)
3436 12 : continue;
3437 265 : if (seen_names_contains(&seen, name)) continue;
3438 264 : if (body_carrying_method &&
3439 35 : ccol_ascii_casecmp(name, "content-length") == 0) {
3440 8 : size_t expected = req->body.data ? req->body.len : (size_t)0;
3441 8 : size_t val_len = strlen(val);
3442 8 : bool all_digits = val_len > 0;
3443 20 : for (size_t vi = 0; vi < val_len; vi++) {
3444 14 : if (!isdigit((unsigned char)val[vi])) {
3445 : all_digits = false;
3446 : break;
3447 : }
3448 : }
3449 8 : char *endp = NULL;
3450 8 : errno = 0;
3451 8 : unsigned long long declared = all_digits ? strtoull(val, &endp, 10) : 0;
3452 8 : if (!all_digits || *endp != '\0' || errno == ERANGE ||
3453 : (unsigned long long)expected != declared) {
3454 4 : ccol_iter_destroy(it);
3455 4 : ccol__mem_free(mp, (void *)seen.names);
3456 4 : ccol__mem_free(mp, ob.buf);
3457 4 : return ccol_invalid_args;
3458 : }
3459 : }
3460 260 : if (!seen_names_add(mp, &seen, name)) {
3461 0 : ccol_iter_destroy(it);
3462 0 : ccol__mem_free(mp, (void *)seen.names);
3463 0 : ccol__mem_free(mp, ob.buf);
3464 0 : return ccol_not_enough_memory;
3465 : }
3466 260 : ob_append_cstr(&ob, name);
3467 260 : ob_append(&ob, ": ", 2);
3468 260 : ob_append_cstr(&ob, val);
3469 260 : ob_append(&ob, "\r\n", 2);
3470 : }
3471 126 : ccol__mem_free(mp, (void *)seen.names);
3472 : }
3473 :
3474 1670 : if (!has_ct && body_carrying_method && req->body.content_type) {
3475 192 : if (!header_value_is_valid(req->body.content_type)) {
3476 2 : ccol__mem_free(mp, ob.buf);
3477 2 : return ccol_invalid_args;
3478 : }
3479 190 : ob_append_cstr(&ob, "content-type: ");
3480 190 : ob_append_cstr(&ob, req->body.content_type);
3481 190 : ob_append(&ob, "\r\n", 2);
3482 : }
3483 :
3484 1668 : if (body_carrying_method && !has_cl) {
3485 202 : char clbuf[48];
3486 192 : int cln = snprintf(clbuf, sizeof(clbuf), "content-length: %zu\r\n",
3487 202 : req->body.data ? req->body.len : (size_t)0);
3488 202 : if (cln > 0) ob_append(&ob, clbuf, (size_t)cln);
3489 : }
3490 :
3491 1668 : bool has_expect = hp.has_expect;
3492 1668 : if (!has_expect && req->expect_continue && body_carrying_method &&
3493 39 : req->body.data && req->body.len > 0) {
3494 38 : ob_append_cstr(&ob, "expect: 100-continue\r\n");
3495 : }
3496 :
3497 1668 : ob_append(&ob, "\r\n", 2);
3498 :
3499 1668 : if (body_carrying_method && req->body.data && req->body.len > 0)
3500 196 : ob_append(&ob, (const char *)req->body.data, req->body.len);
3501 :
3502 1668 : if (ob.oom) {
3503 3 : ccol__mem_free(mp, ob.buf);
3504 3 : return ccol_not_enough_memory;
3505 : }
3506 1665 : *out_buf = ob.buf;
3507 1665 : *out_len = ob.len;
3508 1665 : if (out_presence) *out_presence = hp;
3509 : return ccol_success;
3510 : }
3511 :
3512 : // chttp1_parser integration
3513 : //
3514 : // A body sink that throws the bytes away, for a redirect response whose body
3515 : // nobody reads. Gives len.
3516 7 : static size_t sink_discard(const void *data, size_t len, void *ctx) {
3517 7 : (void)data;
3518 7 : (void)ctx;
3519 7 : return len;
3520 : }
3521 :
3522 : // The buffered body sink, which collects the body of a non-streaming request
3523 : // into the chttp_bodybuf in ctx. It gives a short count when the size would
3524 : // overflow, growth fails, or the cap of chttpcli_set_max_response_body_size is
3525 : // passed (whatever the framing), which stops the parse.
3526 9571 : static size_t sink_buffered(const void *data, size_t len, void *ctx) {
3527 9571 : chttp_bodybuf *bb = (chttp_bodybuf *)ctx;
3528 9571 : if (len == 0) return 0;
3529 9571 : if (len > SIZE_MAX - bb->len || bb->len + len > SIZE_MAX - 1) {
3530 1 : bb->oom = true;
3531 1 : return 0;
3532 : }
3533 9570 : if (bb->max_size > 0 && bb->len + len > bb->max_size) {
3534 2 : bb->too_large = true;
3535 2 : return 0;
3536 : }
3537 9568 : if (bb->len + len + 1 > bb->cap) {
3538 1289 : size_t nc = chttp_grow_capacity(bb->cap, bb->len + len + 1, 4096);
3539 1289 : char *nb = (char *)ccol__mem_realloc(bb->mp, bb->buf, nc);
3540 1289 : if (!nb) {
3541 5 : bb->oom = true;
3542 5 : return 0;
3543 : }
3544 1284 : bb->buf = nb;
3545 1284 : bb->cap = nc;
3546 : }
3547 9563 : memcpy(bb->buf + bb->len, data, len);
3548 9563 : bb->len += len;
3549 9563 : bb->buf[bb->len] = '\0';
3550 9563 : return len;
3551 : }
3552 :
3553 : #ifdef RUNNING_UNIT_TESTS
3554 : // Let a test drive sink_buffered: Its overflow guard with a made-up length, and
3555 : // a growth from a capacity whose doubling would pass SIZE_MAX.
3556 2 : bool chttp__sink_buffered_overflow_guard_for_tests(ccol_memmgmt_procs *mp,
3557 : size_t fake_len) {
3558 2 : chttp_bodybuf bb = {0};
3559 2 : bb.mp = mp;
3560 2 : bb.len = fake_len;
3561 2 : char probe[8] = {0};
3562 2 : size_t n = sink_buffered(probe, sizeof(probe), &bb);
3563 2 : bool rejected = (n != sizeof(probe)) && bb.oom && !bb.too_large;
3564 2 : ccol__mem_free(mp, bb.buf);
3565 2 : return rejected;
3566 : }
3567 :
3568 1 : bool chttp__sink_buffered_cap_overflow_for_tests(ccol_memmgmt_procs *mp,
3569 : size_t fake_cap) {
3570 1 : chttp_bodybuf bb = {0};
3571 1 : bb.mp = mp;
3572 1 : bb.len = fake_cap - 1;
3573 1 : bb.cap = fake_cap;
3574 1 : char probe[8] = {0};
3575 1 : size_t n = sink_buffered(probe, sizeof(probe), &bb);
3576 1 : return (n == 0) && bb.oom && !bb.too_large;
3577 : }
3578 : #endif
3579 :
3580 : #ifdef RUNNING_UNIT_TESTS
3581 : // How many field record headers the code below has read; a test keeps it at or
3582 : // below the record count, so nothing rescans the block.
3583 : static _Atomic unsigned long g_field_rec_reads_for_tests = 0;
3584 : // Gives g_field_rec_reads_for_tests, so a test can check that no operation
3585 : // rescans the field lines.
3586 2 : unsigned long chttpcli__field_rec_reads_for_tests(void) {
3587 2 : return atomic_load_explicit(&g_field_rec_reads_for_tests,
3588 : memory_order_relaxed);
3589 : }
3590 : #endif
3591 :
3592 : // Read a field record (its header at off, its name and its value) and give the
3593 : // padded size of a record, for the field-lines code below.
3594 1289 : static inline chttp_field_rec field_rec_at(const chttp_field_lines *lines,
3595 : uint32_t off) {
3596 : #ifdef RUNNING_UNIT_TESTS
3597 1289 : atomic_fetch_add_explicit(&g_field_rec_reads_for_tests, 1,
3598 : memory_order_relaxed);
3599 : #endif
3600 1289 : chttp_field_rec r;
3601 1289 : memcpy(&r, lines->data + off, sizeof(r));
3602 1289 : return r;
3603 : }
3604 :
3605 890 : static inline const char *field_rec_name(const chttp_field_lines *lines,
3606 : uint32_t off) {
3607 890 : return lines->data + off + sizeof(chttp_field_rec);
3608 : }
3609 :
3610 351 : static inline const char *field_rec_value(const chttp_field_lines *lines,
3611 : uint32_t off,
3612 : const chttp_field_rec *r) {
3613 351 : return field_rec_name(lines, off) + r->name_len + 1;
3614 : }
3615 :
3616 330 : static inline size_t field_rec_size(size_t name_len, size_t value_len) {
3617 330 : size_t n = sizeof(chttp_field_rec) + name_len + 1 + value_len + 1;
3618 330 : return (n + 3) & ~(size_t)3;
3619 : }
3620 :
3621 : // Frees a field-lines block, when a response or a parse context goes away.
3622 3891 : static void field_lines_free(ccol_memmgmt_procs *mp, chttp_field_lines *lines) {
3623 3891 : if (!lines) return;
3624 28 : ccol__mem_free(mp, lines->index);
3625 28 : ccol__mem_free(mp, lines);
3626 : }
3627 :
3628 : // Picks the index slot of a lower-case name for the field-lines table: FNV-1a
3629 : // over it, then a multiply whose high bits pick the slot, so every byte of the
3630 : // name counts.
3631 429 : static inline size_t field_name_slot(const char *name, size_t name_len,
3632 : size_t index_cap) {
3633 429 : uint64_t h = 1469598103934665603ULL;
3634 3648 : for (size_t i = 0; i < name_len; i++) {
3635 3219 : h ^= (unsigned char)name[i];
3636 3219 : h *= 1099511628211ULL;
3637 : }
3638 429 : h *= 0x9E3779B97F4A7C15ULL;
3639 429 : return (size_t)(h >> 32) & (index_cap - 1);
3640 : }
3641 :
3642 : // Finds the index slot of a lower-case name, for adding and reading
3643 : // occurrences. Gives NULL when the name has no records.
3644 321 : static chttp_field_slot *field_lines_find(const chttp_field_lines *lines,
3645 : const char *name, size_t name_len) {
3646 321 : if (!lines || !lines->index) return NULL;
3647 293 : size_t mask = lines->index_cap - 1;
3648 586 : for (size_t i = field_name_slot(name, name_len, lines->index_cap);;
3649 188 : i = (i + 1) & mask) {
3650 481 : chttp_field_slot *slot = &lines->index[i];
3651 700 : if (!slot->head) return NULL;
3652 407 : uint32_t off = slot->head - 1;
3653 407 : chttp_field_rec r = field_rec_at(lines, off);
3654 407 : if (r.name_len == name_len &&
3655 403 : memcmp(field_rec_name(lines, off), name, name_len) == 0)
3656 219 : return slot;
3657 : }
3658 : }
3659 :
3660 : // Makes room for need more record bytes and one more name in the index (kept at
3661 : // most half full), before field_lines_put. A failed allocation gives false and
3662 : // leaves every record and slot as it was.
3663 85 : static bool field_lines_reserve(ccol_memmgmt_procs *mp,
3664 : chttp_field_lines **linesp, size_t need) {
3665 85 : chttp_field_lines *lines = *linesp;
3666 85 : size_t len = lines ? lines->len : 0;
3667 57 : size_t cap = lines ? lines->cap : 0;
3668 85 : if (cap - len < need) {
3669 32 : size_t new_cap = cap ? cap * 2 : 256;
3670 152 : while (new_cap - len < need) new_cap *= 2;
3671 32 : chttp_field_lines *grown = (chttp_field_lines *)ccol__mem_realloc(
3672 : mp, lines, sizeof(chttp_field_lines) + new_cap);
3673 32 : if (!grown) return false;
3674 32 : if (!lines) {
3675 28 : grown->len = 0;
3676 28 : grown->index = NULL;
3677 28 : grown->index_cap = 0;
3678 28 : grown->names = 0;
3679 : }
3680 32 : grown->cap = new_cap;
3681 32 : lines = grown;
3682 32 : *linesp = lines;
3683 : }
3684 85 : if ((lines->names + 1) * 2 > lines->index_cap) {
3685 31 : size_t new_icap = lines->index_cap ? lines->index_cap * 2 : 16;
3686 31 : chttp_field_slot *idx = (chttp_field_slot *)ccol__mem_calloc(
3687 : mp, new_icap, sizeof(chttp_field_slot));
3688 31 : if (!idx) return false;
3689 143 : for (size_t i = 0; i < lines->index_cap; i++) {
3690 112 : chttp_field_slot old = lines->index[i];
3691 112 : if (!old.head) continue;
3692 56 : chttp_field_rec r = field_rec_at(lines, old.head - 1);
3693 112 : size_t j = field_name_slot(field_rec_name(lines, old.head - 1),
3694 56 : r.name_len, new_icap);
3695 82 : while (idx[j].head) j = (j + 1) & (new_icap - 1);
3696 56 : idx[j] = old;
3697 : }
3698 31 : ccol__mem_free(mp, lines->index);
3699 31 : lines->index = idx;
3700 31 : lines->index_cap = new_icap;
3701 : }
3702 : return true;
3703 : }
3704 :
3705 : // Appends one record into room that field_lines_reserve made, and gives its
3706 : // offset for the chain.
3707 165 : static uint32_t field_lines_put(chttp_field_lines *lines, const char *name,
3708 : size_t name_len, const char *value,
3709 : size_t value_len) {
3710 165 : uint32_t off = (uint32_t)lines->len;
3711 165 : chttp_field_rec r = {.name_len = (uint32_t)name_len,
3712 165 : .value_len = (uint32_t)value_len,
3713 : .next = 0};
3714 165 : char *dst = lines->data + off;
3715 165 : memcpy(dst, &r, sizeof(r));
3716 165 : dst += sizeof(r);
3717 165 : memcpy(dst, name, name_len);
3718 165 : dst[name_len] = '\0';
3719 165 : memcpy(dst + name_len + 1, value, value_len);
3720 165 : dst[name_len + 1 + value_len] = '\0';
3721 165 : lines->len += field_rec_size(name_len, value_len);
3722 165 : return off;
3723 : }
3724 :
3725 : // Records one more occurrence of a lower-case name; for a name seen for the
3726 : // first time, first_value (the map's value) is recorded first. A failed
3727 : // allocation gives false and leaves *linesp untouched. Out of line, since
3728 : // repeated names are rare.
3729 85 : __attribute__((noinline, cold)) static bool field_lines_add(
3730 : ccol_memmgmt_procs *mp, chttp_field_lines **linesp, const char *name,
3731 : size_t name_len, const char *first_value, size_t first_len,
3732 : const char *value, size_t value_len) {
3733 85 : chttp_field_slot *slot = field_lines_find(*linesp, name, name_len);
3734 85 : size_t need = field_rec_size(name_len, value_len);
3735 85 : if (!slot) need += field_rec_size(name_len, first_len);
3736 85 : if (!field_lines_reserve(mp, linesp, need)) return false;
3737 85 : chttp_field_lines *lines = *linesp;
3738 85 : if (!slot) {
3739 80 : uint32_t head =
3740 80 : field_lines_put(lines, name, name_len, first_value, first_len);
3741 80 : size_t j = field_name_slot(name, name_len, lines->index_cap);
3742 130 : while (lines->index[j].head) j = (j + 1) & (lines->index_cap - 1);
3743 80 : slot = &lines->index[j];
3744 80 : slot->head = head + 1;
3745 80 : slot->tail = head + 1;
3746 80 : lines->names++;
3747 : } else {
3748 5 : slot = field_lines_find(lines, name, name_len);
3749 : }
3750 85 : uint32_t off = field_lines_put(lines, name, name_len, value, value_len);
3751 85 : uint32_t tail = slot->tail - 1;
3752 85 : chttp_field_rec tr = field_rec_at(lines, tail);
3753 85 : tr.next = off + 1;
3754 85 : memcpy(lines->data + tail, &tr, sizeof(tr));
3755 85 : slot->tail = off + 1;
3756 85 : return true;
3757 : }
3758 :
3759 : // Replaces the map value of every repeated name with all occurrences joined by
3760 : // ", " (RFC 9110 section 5.3), once per response. Set-Cookie keeps its first
3761 : // occurrence. False means an allocation failed.
3762 28 : static bool field_lines_combine(chttp_parse_ctx *ctx) {
3763 28 : const chttp_field_lines *lines = ctx->field_lines;
3764 588 : for (size_t i = 0; i < lines->index_cap; i++) {
3765 560 : const chttp_field_slot *slot = &lines->index[i];
3766 568 : if (!slot->head) continue;
3767 80 : uint32_t off = slot->head - 1;
3768 80 : chttp_field_rec r = field_rec_at(lines, off);
3769 80 : const char *name = field_rec_name(lines, off);
3770 80 : if (r.name_len == sizeof("set-cookie") - 1 &&
3771 8 : memcmp(name, "set-cookie", r.name_len) == 0)
3772 8 : continue;
3773 72 : size_t total = 0;
3774 220 : for (uint32_t o = slot->head; o;) {
3775 148 : chttp_field_rec cr = field_rec_at(lines, o - 1);
3776 148 : total += cr.value_len + 2;
3777 148 : o = cr.next;
3778 : }
3779 72 : char *combined = (char *)ccol__mem_alloc(ctx->mp, total - 1);
3780 72 : if (!combined) return false;
3781 72 : size_t pos = 0;
3782 220 : for (uint32_t o = slot->head; o;) {
3783 148 : chttp_field_rec cr = field_rec_at(lines, o - 1);
3784 148 : if (o != slot->head) {
3785 76 : combined[pos++] = ',';
3786 76 : combined[pos++] = ' ';
3787 : }
3788 148 : memcpy(combined + pos, field_rec_value(lines, o - 1, &cr), cr.value_len);
3789 148 : pos += cr.value_len;
3790 148 : o = cr.next;
3791 : }
3792 72 : combined[pos] = '\0';
3793 72 : cmap_pair kp = {.ptr = (void *)name, .size = r.name_len + 1};
3794 72 : cmap_pair vp = {.ptr = combined, .size = pos + 1};
3795 72 : ccol_retval rv = chashmap_insert_elem(ctx->headers, &kp, &vp);
3796 72 : ccol__mem_free(ctx->mp, combined);
3797 72 : if (rv != ccol_key_already_present && rv != ccol_success) return false;
3798 : }
3799 : return true;
3800 : }
3801 :
3802 : // Stores one response header line (the parser's header callback; trailers have
3803 : // no callback). The first occurrence of a name goes into the map, later ones
3804 : // into ctx->field_lines. Location is captured before any combining, so a
3805 : // redirect follows the first one.
3806 4953 : static int http1_on_header(chttp1_parser *p, const char *name, size_t name_len,
3807 : const char *value, size_t value_len) {
3808 4953 : chttp_parse_ctx *ctx = (chttp_parse_ctx *)p->data;
3809 :
3810 4953 : char stack_buf[CHTTP1_MAX_LINE_LEN + 1];
3811 4953 : size_t need = name_len + 1 + value_len + 1;
3812 4953 : char *buf = stack_buf;
3813 4953 : if (need > sizeof(stack_buf)) {
3814 18 : buf = (char *)ccol__mem_alloc(ctx->mp, need);
3815 18 : if (!buf) {
3816 0 : ctx->error = true;
3817 0 : return 1;
3818 : }
3819 : }
3820 4953 : char *lower_name = buf;
3821 57495 : for (size_t i = 0; i < name_len; i++)
3822 59467 : lower_name[i] = (char)ccol_ascii_tolower((unsigned char)name[i]);
3823 4953 : lower_name[name_len] = '\0';
3824 :
3825 4953 : char *value_copy = buf + name_len + 1;
3826 4953 : memcpy(value_copy, value, value_len);
3827 4953 : value_copy[value_len] = '\0';
3828 :
3829 4953 : int ret = 0;
3830 4953 : cmap_pair kp = {.ptr = lower_name, .size = name_len + 1};
3831 4953 : cmap_pair vp = {.ptr = value_copy, .size = value_len + 1};
3832 4953 : cmap_pair slot;
3833 4953 : ccol_retval rv = ccol_chmap_insert_or_get_elem(ctx->headers, &kp, &vp, &slot);
3834 4953 : if (rv != ccol_success &&
3835 85 : (rv != ccol_key_already_present ||
3836 85 : !field_lines_add(ctx->mp, &ctx->field_lines, lower_name, name_len,
3837 85 : (const char *)slot.ptr, slot.size - 1, value_copy,
3838 : value_len))) {
3839 8 : ctx->error = true;
3840 8 : ret = 1;
3841 : }
3842 4953 : if (buf != stack_buf) ccol__mem_free(ctx->mp, buf);
3843 : return ret;
3844 : }
3845 :
3846 : // Checks the response once its header block is complete, before any body byte
3847 : // reaches the sink. It fails a 101 (we never send Upgrade) and a final response
3848 : // with a transfer coding other than chunked (the parser only decodes chunked),
3849 : // decides whether this hop redirects (ctx->will_redirect, ctx->location),
3850 : // refuses a declared body over the size cap, and combines repeated fields.
3851 2142 : static int http1_on_headers_complete(chttp1_parser *p) {
3852 2142 : chttp_parse_ctx *ctx = (chttp_parse_ctx *)p->data;
3853 2142 : ctx->status_code = p->status_code;
3854 :
3855 2142 : if (p->status_code == 101) return -1;
3856 :
3857 2136 : if (p->status_code >= 200 && chttp1_has_other_transfer_coding(p)) return -1;
3858 :
3859 2129 : bool is_redirect_status = ctx->status_code == 301 ||
3860 : ctx->status_code == 302 ||
3861 2129 : ctx->status_code == 303 ||
3862 2129 : ctx->status_code == 307 || ctx->status_code == 308;
3863 : if (is_redirect_status) {
3864 222 : cmap_pair kp = {.ptr = (void *)"location", .size = sizeof("location")};
3865 222 : cmap_pair vp;
3866 222 : if (chashmap_get_elem_ref(ctx->headers, &kp, &vp) == ccol_success &&
3867 222 : ((const char *)vp.ptr)[0] != '\0') {
3868 218 : ctx->location = ccol_strdup(ctx->mp, (const char *)vp.ptr);
3869 218 : if (!ctx->location) {
3870 0 : ctx->error = true;
3871 0 : return -1;
3872 : }
3873 218 : ctx->will_redirect = true;
3874 : }
3875 : }
3876 :
3877 2129 : if (ctx->field_lines && !field_lines_combine(ctx)) {
3878 0 : ctx->error = true;
3879 0 : return -1;
3880 : }
3881 :
3882 2129 : bool is_informational_status =
3883 2129 : ctx->status_code >= 100 && ctx->status_code < 200;
3884 1543 : bool is_always_bodyless_status = is_informational_status ||
3885 3669 : ctx->status_code == 204 ||
3886 : ctx->status_code == 304;
3887 2129 : if (!ctx->will_redirect && !ctx->is_head_request &&
3888 1318 : !is_always_bodyless_status && ctx->requested_sink_fn == sink_buffered) {
3889 1286 : chttp_bodybuf *bb = (chttp_bodybuf *)ctx->requested_sink_ctx;
3890 1286 : if (bb->max_size > 0 && chttp1_has_content_length(p) &&
3891 9 : chttp1_declared_content_length(p) > (uint64_t)bb->max_size) {
3892 3 : ctx->too_large = true;
3893 3 : return -1;
3894 : }
3895 : }
3896 :
3897 2126 : ctx->sink_fn = ctx->will_redirect ? sink_discard : ctx->requested_sink_fn;
3898 2126 : ctx->sink_ctx = ctx->will_redirect ? NULL : ctx->requested_sink_ctx;
3899 :
3900 2126 : return ctx->is_head_request ? 1 : 0;
3901 : }
3902 :
3903 : // Passes body bytes to the sink chosen for this parse (the parser's body
3904 : // callback). A short count becomes an allocation failure, a cap breach or an
3905 : // abort by the caller's write_fn, recorded in ctx so the caller reports the
3906 : // right code.
3907 9623 : static int http1_on_body(chttp1_parser *p, const char *at, size_t len) {
3908 9623 : chttp_parse_ctx *ctx = (chttp_parse_ctx *)p->data;
3909 9623 : size_t n = ctx->sink_fn ? ctx->sink_fn(at, len, ctx->sink_ctx) : len;
3910 9617 : if (n != len) {
3911 10 : if (ctx->sink_fn == sink_buffered) {
3912 6 : chttp_bodybuf *bb = (chttp_bodybuf *)ctx->sink_ctx;
3913 6 : if (bb->too_large)
3914 2 : ctx->too_large = true;
3915 : else
3916 4 : ctx->error = true;
3917 : } else {
3918 4 : ctx->aborted = true;
3919 : }
3920 10 : return 1;
3921 : }
3922 : return 0;
3923 : }
3924 :
3925 : // Marks the response complete (the parser's message-complete callback), so the
3926 : // read loop knows the message ended.
3927 2097 : static int http1_on_message_complete(chttp1_parser *p) {
3928 2097 : chttp_parse_ctx *ctx = (chttp_parse_ctx *)p->data;
3929 2097 : ctx->message_complete = true;
3930 2097 : return 0;
3931 : }
3932 :
3933 : // The parser settings shared by every response parse, built once.
3934 : static struct {
3935 : chttp1_settings settings;
3936 : ccol__once_flag once;
3937 : } client_http1_settings_bundler = {0};
3938 :
3939 : // Fills the settings above. on_trailer stays NULL, so trailer fields are
3940 : // dropped.
3941 37 : static void init_chttp1_settings(void) {
3942 37 : chttp1_settings_init(&client_http1_settings_bundler.settings);
3943 37 : client_http1_settings_bundler.settings.on_header = http1_on_header;
3944 37 : client_http1_settings_bundler.settings.on_headers_complete =
3945 : http1_on_headers_complete;
3946 37 : client_http1_settings_bundler.settings.on_body = http1_on_body;
3947 37 : client_http1_settings_bundler.settings.on_message_complete =
3948 : http1_on_message_complete;
3949 37 : }
3950 :
3951 : // Frees the header map, the field lines and the redirect location of ctx, for
3952 : // the reset and the error paths of a parse.
3953 2030 : static void parse_ctx_free_fields(chttp_parse_ctx *ctx) {
3954 2030 : ccol__mem_free(ctx->mp, ctx->location);
3955 2029 : if (ctx->headers) chashmap__destroy(ctx->headers);
3956 2029 : field_lines_free(ctx->mp, ctx->field_lines);
3957 2030 : ctx->location = NULL;
3958 2030 : ctx->headers = NULL;
3959 2030 : ctx->field_lines = NULL;
3960 2030 : }
3961 :
3962 : // Resets ctx for the final response that follows a "100 Continue" on the same
3963 : // connection, so the interim response's headers never leak into it. Fields that
3964 : // belong to the request stay.
3965 582 : static ccol_retval parse_ctx_reset_for_continue(chttp_parse_ctx *ctx) {
3966 582 : ccol__mem_free(ctx->mp, ctx->location);
3967 582 : ctx->location = NULL;
3968 582 : if (ctx->headers) chashmap__destroy(ctx->headers);
3969 582 : field_lines_free(ctx->mp, ctx->field_lines);
3970 582 : ctx->field_lines = NULL;
3971 582 : char *herr = NULL;
3972 1164 : ctx->headers =
3973 582 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_string,
3974 : ccol_string, ctx->mp, NULL, NULL, &herr);
3975 582 : ctx->will_redirect = false;
3976 582 : ctx->message_complete = false;
3977 582 : ctx->trailing_garbage = false;
3978 582 : ctx->error = false;
3979 582 : ctx->aborted = false;
3980 582 : ctx->too_large = false;
3981 582 : ctx->status_code = 0;
3982 582 : ctx->sink_fn = NULL;
3983 582 : ctx->sink_ctx = NULL;
3984 582 : return ctx->headers ? ccol_success : ccol_not_enough_memory;
3985 : }
3986 :
3987 : #ifdef RUNNING_UNIT_TESTS
3988 : // Counters of Tier 1 reads and of the reads that had to wait for the socket,
3989 : // for the test that a large body isn't read with a wait per read.
3990 : static unsigned long chttp_tier1_reads;
3991 : static unsigned long chttp_tier1_read_waits;
3992 : // Give the Tier 1 read and read-wait counters, so a test can check that a large
3993 : // body isn't read with a wait per read.
3994 2 : unsigned long chttp__tier1_reads_for_tests(void) {
3995 2 : return __atomic_load_n(&chttp_tier1_reads, __ATOMIC_RELAXED);
3996 : }
3997 2 : unsigned long chttp__tier1_read_waits_for_tests(void) {
3998 2 : return __atomic_load_n(&chttp_tier1_read_waits, __ATOMIC_RELAXED);
3999 : }
4000 : // Counts the Tier 1 hops that open a 100-continue window.
4001 : static unsigned long chttp_tier1_continue_waits;
4002 : // Gives chttp_tier1_continue_waits, so a test can check that a request which
4003 : // must not wait never opens a 100-continue window.
4004 4 : unsigned long chttp__tier1_continue_waits_for_tests(void) {
4005 4 : return __atomic_load_n(&chttp_tier1_continue_waits, __ATOMIC_RELAXED);
4006 : }
4007 : #endif
4008 :
4009 : // Reads and parses one message from conn into ctx. carry_in goes to the parser
4010 : // before the socket. first_byte bounds only the wait for the first byte (the
4011 : // 100-continue window); once a byte has arrived only overall applies. After a
4012 : // read that made progress we read again at once, and wait only after one that
4013 : // blocked. Bytes past the message come back in *leftover_out from mp;
4014 : // *keep_alive_out is the parser's answer.
4015 934 : static ccol_retval chttp_read_message_with(
4016 : chttp1_parser *parser, chttp_conn *conn, chttp_parse_ctx *pctx,
4017 : chttp_deadline *overall, chttp_deadline *first_byte, const char *carry_in,
4018 : size_t carry_in_len, bool *keep_alive_out, bool *any_bytes_read_out,
4019 : char **leftover_out, size_t *leftover_len_out) {
4020 934 : *leftover_out = NULL;
4021 934 : *leftover_len_out = 0;
4022 934 : bool started = carry_in_len > 0;
4023 :
4024 934 : if (carry_in_len > 0) {
4025 216 : *any_bytes_read_out = true;
4026 216 : chttp1_errno err = chttp1_parser_execute(parser, carry_in, carry_in_len);
4027 216 : if (err == CHTTP1_PAUSED) {
4028 215 : size_t consumed = chttp1_parser_consumed(parser);
4029 215 : *keep_alive_out = chttp1_should_keep_alive(parser);
4030 215 : if (consumed < carry_in_len) {
4031 191 : size_t rem = carry_in_len - consumed;
4032 191 : char *lb = (char *)ccol__mem_alloc(pctx->mp, rem);
4033 191 : if (!lb) return ccol_not_enough_memory;
4034 191 : memcpy(lb, carry_in + consumed, rem);
4035 191 : *leftover_out = lb;
4036 191 : *leftover_len_out = rem;
4037 : }
4038 215 : return ccol_success;
4039 : }
4040 1 : if (err == CHTTP1_USER) {
4041 0 : if (pctx->too_large) return ccol_msg_too_large;
4042 0 : return pctx->error ? ccol_not_enough_memory : ccol_http_transfer_aborted;
4043 : }
4044 1 : if (err != CHTTP1_OK) return ccol_http_transfer_aborted;
4045 : }
4046 :
4047 : char buf[8192];
4048 : short want_events = POLLIN;
4049 : bool read_blocked = false;
4050 : bool wait_first = true;
4051 1811 : for (;;) {
4052 1811 : int wait_ms;
4053 1811 : chttp_deadline *dl = (started || !first_byte) ? overall : first_byte;
4054 3618 : if (read_deadline_passed(dl, conn->fd) ||
4055 1807 : !deadline_remaining_ms(dl, &wait_ms) ||
4056 1811 : !conn_inactivity_left_ms(conn, &wait_ms))
4057 718 : return ccol_timed_out;
4058 1853 : bool buffered = conn->tls && want_events == POLLIN && !read_blocked &&
4059 48 : ctls_conn_has_pending_input(conn->tls);
4060 1805 : if (wait_first && !buffered) {
4061 : #ifdef RUNNING_UNIT_TESTS
4062 932 : __atomic_fetch_add(&chttp_tier1_read_waits, 1, __ATOMIC_RELAXED);
4063 : #endif
4064 932 : ccol_retval prv =
4065 932 : conn_wait_io(conn, want_events, wait_ms, ccol_http_transfer_aborted);
4066 1147 : if (prv == ccol_timed_out) continue;
4067 927 : if (prv != ccol_success) return prv;
4068 : }
4069 :
4070 : #ifdef RUNNING_UNIT_TESTS
4071 1799 : __atomic_fetch_add(&chttp_tier1_reads, 1, __ATOMIC_RELAXED);
4072 : #endif
4073 1799 : ssize_t n = conn_read(conn, buf, sizeof(buf));
4074 1798 : if (n < 0) {
4075 220 : if (errno == EWOULDBLOCK) {
4076 215 : read_blocked = true;
4077 215 : wait_first = true;
4078 215 : if (conn->tls)
4079 37 : want_events = conn_tls_wants_write(conn->tls) ? POLLOUT : POLLIN;
4080 215 : continue;
4081 : }
4082 : return ccol_http_transfer_aborted;
4083 : }
4084 1578 : read_blocked = false;
4085 1578 : wait_first = false;
4086 1578 : want_events = POLLIN;
4087 1578 : if (n > 0) {
4088 1566 : *any_bytes_read_out = true;
4089 1566 : started = true;
4090 : }
4091 1578 : if (n == 0) {
4092 13 : chttp1_errno fe = chttp1_parser_finish(parser);
4093 13 : if ((fe != CHTTP1_OK && fe != CHTTP1_PAUSED) || !pctx->message_complete)
4094 : return ccol_http_transfer_aborted;
4095 2 : *keep_alive_out = false;
4096 2 : return ccol_success;
4097 : }
4098 :
4099 1565 : chttp1_errno err = chttp1_parser_execute(parser, buf, (size_t)n);
4100 1565 : if (err == CHTTP1_PAUSED) {
4101 678 : size_t consumed = chttp1_parser_consumed(parser);
4102 678 : *keep_alive_out = chttp1_should_keep_alive(parser);
4103 678 : if (consumed < (size_t)n) {
4104 29 : size_t rem = (size_t)n - consumed;
4105 29 : char *lb = (char *)ccol__mem_alloc(pctx->mp, rem);
4106 29 : if (!lb) return ccol_not_enough_memory;
4107 29 : memcpy(lb, buf + consumed, rem);
4108 29 : *leftover_out = lb;
4109 29 : *leftover_len_out = rem;
4110 : }
4111 678 : return ccol_success;
4112 : }
4113 887 : if (err == CHTTP1_USER) {
4114 13 : if (pctx->too_large) return ccol_msg_too_large;
4115 10 : return pctx->error ? ccol_not_enough_memory : ccol_http_transfer_aborted;
4116 : }
4117 874 : if (err != CHTTP1_OK) return ccol_http_transfer_aborted;
4118 : }
4119 : }
4120 :
4121 : // Reads one message from conn for Tier 1, through chttp_read_message_with, with
4122 : // a parser set up here. It enables the 64 KiB response line spill and releases
4123 : // it on every path, so no caller can leak it.
4124 931 : static ccol_retval chttp_read_message(
4125 : chttp_conn *conn, chttp_parse_ctx *pctx, chttp_deadline *overall,
4126 : chttp_deadline *first_byte, const char *carry_in, size_t carry_in_len,
4127 : bool *keep_alive_out, bool *any_bytes_read_out, char **leftover_out,
4128 : size_t *leftover_len_out) {
4129 931 : ccol__call_once(client_http1_settings_bundler.once, init_chttp1_settings);
4130 :
4131 931 : chttp1_parser parser;
4132 931 : chttp1_parser_init(&parser, &client_http1_settings_bundler.settings);
4133 931 : parser.data = pctx;
4134 931 : (void)chttp1_parser_enable_line_spill(&parser, pctx->mp);
4135 931 : ccol_retval rv = chttp_read_message_with(
4136 : &parser, conn, pctx, overall, first_byte, carry_in, carry_in_len,
4137 : keep_alive_out, any_bytes_read_out, leftover_out, leftover_len_out);
4138 930 : chttp1_parser_release(&parser);
4139 930 : return rv;
4140 : }
4141 :
4142 : // Reads messages like chttp_read_message but skips every interim 1xx other than
4143 : // stop_at_status (0 skips them all), so a 1xx the server sends on its own never
4144 : // reads as the response. It stops after CHTTP_MAX_INTERIM_RESPONSES skipped
4145 : // messages; leftover bytes of a skipped message feed the next one.
4146 651 : static ccol_retval chttp_read_message_loop(
4147 : chttp_conn *conn, chttp_parse_ctx *pctx, chttp_deadline *overall,
4148 : chttp_deadline *first_byte, const char *carry_in, size_t carry_in_len,
4149 : int stop_at_status, size_t discarded_before, bool *keep_alive_out,
4150 : bool *any_bytes_read_out, char **leftover_out, size_t *leftover_len_out) {
4151 651 : char *cur_carry = NULL;
4152 651 : size_t cur_carry_len = 0;
4153 651 : if (carry_in_len > 0) {
4154 0 : cur_carry = (char *)ccol__mem_alloc(pctx->mp, carry_in_len);
4155 0 : if (!cur_carry) return ccol_not_enough_memory;
4156 0 : memcpy(cur_carry, carry_in, carry_in_len);
4157 0 : cur_carry_len = carry_in_len;
4158 : }
4159 :
4160 280 : for (size_t n_discarded = discarded_before;;) {
4161 931 : char *leftover = NULL;
4162 931 : size_t leftover_len = 0;
4163 931 : ccol_retval rv = chttp_read_message(
4164 : conn, pctx, overall, first_byte, cur_carry, cur_carry_len,
4165 : keep_alive_out, any_bytes_read_out, &leftover, &leftover_len);
4166 930 : ccol__mem_free(pctx->mp, cur_carry);
4167 930 : cur_carry = NULL;
4168 930 : cur_carry_len = 0;
4169 930 : if (rv != ccol_success) {
4170 38 : ccol__mem_free(pctx->mp, leftover);
4171 650 : return rv;
4172 : }
4173 :
4174 1784 : bool is_skippable_1xx = pctx->status_code >= 100 &&
4175 892 : pctx->status_code < 200 &&
4176 : pctx->status_code != stop_at_status;
4177 892 : if (!is_skippable_1xx) {
4178 610 : *leftover_out = leftover;
4179 610 : *leftover_len_out = leftover_len;
4180 610 : return ccol_success;
4181 : }
4182 :
4183 282 : if (n_discarded >= CHTTP_MAX_INTERIM_RESPONSES) {
4184 2 : ccol__mem_free(pctx->mp, leftover);
4185 2 : return ccol_http_transfer_aborted;
4186 : }
4187 280 : n_discarded++;
4188 :
4189 280 : ccol_retval rrv = parse_ctx_reset_for_continue(pctx);
4190 280 : if (rrv != ccol_success) {
4191 0 : ccol__mem_free(pctx->mp, leftover);
4192 0 : return rrv;
4193 : }
4194 280 : cur_carry = leftover;
4195 280 : cur_carry_len = leftover_len;
4196 : }
4197 : }
4198 :
4199 : // TLS context management
4200 : //
4201 : // Tells whether path names a regular file we can read, so a rebuild can mark
4202 : // the context unusable instead of failing when a configured file isn't there
4203 : // yet.
4204 147 : static bool file_readable(const char *path) {
4205 147 : return path && access(path, R_OK) == 0;
4206 : }
4207 :
4208 : // Builds cli->tls_ctx from cli->tls, at create, from chttpcli_set_tls, and at a
4209 : // request after a rebuild that ran out of memory. The generation is bumped
4210 : // first on every path. A missing or unreadable file only marks the context
4211 : // unusable (requests then fail with ccol_http_tls_cert_load_failed), because
4212 : // TLS may be configured before its files exist. An allocation failure is
4213 : // returned as ccol_not_enough_memory. The caller holds cli->lock.
4214 2993 : static ccol_retval rebuild_tls_ctx_body_locked(struct chttpclient *cli) {
4215 2993 : cli->tls_generation++;
4216 2993 : if (cli->tls_ctx) {
4217 139 : ctls_ctx_release(cli->tls_ctx);
4218 139 : cli->tls_ctx = NULL;
4219 : }
4220 2993 : cli->tls_ctx_usable = false;
4221 :
4222 2993 : bool have_cert_pair = cli->tls.cert_path && cli->tls.key_path;
4223 34 : if (have_cert_pair && (!file_readable(cli->tls.cert_path) ||
4224 24 : !file_readable(cli->tls.key_path))) {
4225 5 : return ccol_success;
4226 : }
4227 3106 : if (cli->tls.ca_bundle_path && !file_readable(cli->tls.ca_bundle_path)) {
4228 : return ccol_success;
4229 : }
4230 :
4231 2984 : ctls_ctx *ctx = ctls_ctx_new_mp(cli->m_procs, NULL);
4232 2984 : if (!ctx) return ccol_not_enough_memory;
4233 :
4234 2969 : if (have_cert_pair) {
4235 12 : ccol_retval crv = ctls_ctx_cert_add(ctx, NULL, cli->tls.cert_path,
4236 : cli->tls.key_path, NULL, NULL);
4237 12 : if (crv != ccol_success) {
4238 0 : ctls_ctx_release(ctx);
4239 0 : return crv == ccol_not_enough_memory ? crv : ccol_success;
4240 : }
4241 : }
4242 :
4243 2969 : if (cli->tls.ca_bundle_path) {
4244 111 : ccol_retval trv = ctls_ctx_trust(ctx, cli->tls.ca_bundle_path, NULL);
4245 111 : if (trv != ccol_success) {
4246 3 : ctls_ctx_release(ctx);
4247 3 : return trv == ccol_not_enough_memory ? trv : ccol_success;
4248 : }
4249 2858 : } else if (!cli->tls.insecure_skip_verify) {
4250 2856 : ccol_retval srv = ctls_ctx_trust_system(ctx);
4251 2856 : if (srv != ccol_success) {
4252 0 : ctls_ctx_release(ctx);
4253 0 : return srv == ccol_not_enough_memory ? srv : ccol_success;
4254 : }
4255 : }
4256 :
4257 2966 : cli->tls_ctx = ctx;
4258 2966 : cli->tls_ctx_usable = true;
4259 2966 : return ccol_success;
4260 : }
4261 :
4262 : // Rebuilds cli->tls_ctx for create, chttpcli_set_tls and the retry after an
4263 : // out-of-memory rebuild, and records in cli->tls_ctx_oom whether it ran out of
4264 : // memory. Gives the rebuild's code. The caller holds cli->lock.
4265 2993 : static ccol_retval rebuild_tls_ctx_locked(struct chttpclient *cli) {
4266 5986 : ccol_retval rv = rebuild_tls_ctx_body_locked(cli);
4267 2993 : cli->tls_ctx_oom = rv == ccol_not_enough_memory;
4268 2993 : return rv;
4269 : }
4270 :
4271 : // Tries the rebuild again when the last one ran out of memory, so a client
4272 : // recovers once memory comes back. The caller holds cli->lock.
4273 1705 : static void tls_ctx_retry_if_oom_locked(struct chttpclient *cli) {
4274 1705 : if (!cli->tls_ctx_usable && cli->tls_ctx_oom)
4275 9 : (void)rebuild_tls_ctx_locked(cli);
4276 1705 : }
4277 :
4278 : // Gives the code a request that needs TLS reports when the client has no usable
4279 : // context: ccol_not_enough_memory when oom is set, else
4280 : // ccol_http_tls_cert_load_failed. Every tier uses it so they agree.
4281 3 : static ccol_retval tls_ctx_unusable_code(bool oom) {
4282 3 : return oom ? ccol_not_enough_memory : ccol_http_tls_cert_load_failed;
4283 : }
4284 :
4285 : // The client engine
4286 : //
4287 : // One ceventloop reactor for the whole process, shared by every client, and
4288 : // independent of chttpserver's. It starts with the first async request and is
4289 : // reaped on its own thread once the last user goes away. Everything here is
4290 : // guarded by mutex, except the atomics read without it. The installed logger is
4291 : // kept across stop and start; the reaper closes only the fallback logger.
4292 : static struct {
4293 : ceventloop reactor;
4294 : size_t reactor_refs;
4295 : ccol__mutex mutex;
4296 : ccol__cond_var stopped_cv;
4297 : ccol__once_flag once;
4298 : bool stopping;
4299 : ccol__thread_id reaper_thread;
4300 : bool reaper_joinable;
4301 : ccol_memmgmt_procs mprocs_storage;
4302 : ccol_memmgmt_procs *mprocs;
4303 :
4304 : size_t num_reactor_threads;
4305 : size_t last_resolved_num_reactor_threads;
4306 :
4307 : clog logger;
4308 :
4309 : clog user_logger;
4310 :
4311 : cthrpool dns_pool;
4312 :
4313 : size_t chains_live;
4314 : bool exit_waiting;
4315 :
4316 : ccol__once_flag exit_hook_once;
4317 : #if CCOL_FORK_SAFETY_REQUIRED
4318 : ccol__once_flag atfork_once;
4319 : #endif
4320 : } cli_engine_bundler = {0};
4321 :
4322 : // The process that built the engine or installed the exit hook; client_at_exit
4323 : // acts only there, since a fork child inherits the state but not the threads.
4324 : // Atomic because the exit hook reads it before taking any lock.
4325 : static _Atomic pid_t g_client_engine_pid = 0;
4326 :
4327 : // Async requests from any client whose future isn't fulfilled yet. A zero
4328 : // proves to client_at_exit that exit() isn't called from a write_fn and that no
4329 : // request is in flight.
4330 : static _Atomic size_t g_async_requests_pending = 0;
4331 : // Async requests the sweep fulfilled while their hop is still alive (stuck in a
4332 : // name lookup, or waiting for a dispatch that never comes). The exit handler
4333 : // counts them as in flight.
4334 : static _Atomic size_t g_async_hops_abandoned = 0;
4335 :
4336 : static ccol_retval client_deadline_sweep_start(void);
4337 : static void client_deadline_sweep_stop_and_join(void);
4338 : static void client_exit_hook_install(void);
4339 : static void default_client_destroy_if_idle(void);
4340 :
4341 : #if CCOL_FORK_SAFETY_REQUIRED
4342 : static void chttpcli_atfork_prepare(void);
4343 : static void chttpcli_atfork_parent(void);
4344 : static void chttpcli_atfork_child(void);
4345 : #endif
4346 :
4347 : #if CCOL_FORK_SAFETY_REQUIRED
4348 : // Registers this module's fork handlers, once. ceventloop, cthrpool and clog
4349 : // register first, so our prepare handler runs before theirs.
4350 33 : static void client_atfork_install(void) {
4351 33 : cthreadcomm__ensure_atfork_registered_before_caller();
4352 33 : cthrpool__ensure_atfork_registered_before_caller();
4353 33 : clog__ensure_atfork_registered_before_caller();
4354 33 : ccol__at_fork(chttpcli_atfork_prepare, chttpcli_atfork_parent,
4355 : chttpcli_atfork_child);
4356 33 : }
4357 : #endif
4358 :
4359 : #if defined(CCOL__ATFORK_AT_LOAD) && CCOL_FORK_SAFETY_REQUIRED
4360 : // Registers the fork handlers at load on systems that need it; see
4361 : // CCOL__ATFORK_AT_LOAD in common.h.
4362 : __attribute__((constructor)) static void client_atfork_at_load(void) {
4363 : ccol__call_once(cli_engine_bundler.atfork_once, client_atfork_install);
4364 : }
4365 : #endif
4366 :
4367 : // Set first thing in client_engine_globals_init, so the destructor knows
4368 : // whether the engine globals were ever initialized.
4369 : static _Atomic bool g_engine_globals_entered = false;
4370 :
4371 : // Initializes the engine mutex and condition variables, once, before the first
4372 : // engine use, and sets g_engine_globals_entered first. SIGPIPE is left to the
4373 : // application; every write of this module avoids it.
4374 36 : static void client_engine_globals_init(void) {
4375 36 : atomic_store(&g_engine_globals_entered, true);
4376 36 : if (ccol__mutex_init(cli_engine_bundler.mutex) != 0)
4377 0 : ccol__fatal_err("chttpclient engine: failed to initialize mutex");
4378 36 : if (ccol__cond_var_init(cli_engine_bundler.stopped_cv) != 0)
4379 0 : ccol__fatal_err(
4380 : "chttpclient engine: failed to initialize condition variable");
4381 36 : }
4382 :
4383 : // Logs fmt and its arguments (as for clog_info) through the engine logger, for
4384 : // diagnostics from engine threads. The pointer is read and used inside one
4385 : // critical section of the engine mutex, because chttpcli_set_engine_logger
4386 : // closes the old logger right after it swaps it. Expands to a statement.
4387 : #define CLIENT_ENGINE_LOG_INFO(fmt, ...) \
4388 : do { \
4389 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init); \
4390 : ccol__mutex_lock(cli_engine_bundler.mutex); \
4391 : if (cli_engine_bundler.logger) \
4392 : clog_info(cli_engine_bundler.logger, fmt, ##__VA_ARGS__); \
4393 : ccol__mutex_unlock(cli_engine_bundler.mutex); \
4394 : } while (0)
4395 :
4396 : #ifdef RUNNING_UNIT_TESTS
4397 : // Reaper threads created and joined; they match once the engine is quiescent.
4398 : static _Atomic unsigned g_reaper_created_for_tests = 0;
4399 : static _Atomic unsigned g_reaper_joined_for_tests = 0;
4400 : #endif
4401 :
4402 : // Joins a reaper that has finished, so its handle is never overwritten
4403 : // unjoined. The caller holds the engine mutex.
4404 2508 : static void client_engine_join_reaper_if_needed_locked(void) {
4405 2508 : if (cli_engine_bundler.reaper_joinable) {
4406 403 : ccol__thread_join(cli_engine_bundler.reaper_thread);
4407 403 : cli_engine_bundler.reaper_joinable = false;
4408 : #ifdef RUNNING_UNIT_TESTS
4409 403 : atomic_fetch_add(&g_reaper_joined_for_tests, 1u);
4410 : #endif
4411 : }
4412 2508 : }
4413 :
4414 : // True while the engine runs with no reference because no thread could be had
4415 : // for its teardown. The sweep reads it each tick, without the engine lock, and
4416 : // retries the reap.
4417 : static _Atomic bool g_engine_reap_abandoned = false;
4418 :
4419 : // In a fork child, forgets the inherited reaper handle, stopping flag and
4420 : // unreferenced reactor, all of which name parent threads; joining such a handle
4421 : // could join an unrelated thread that reuses its descriptor. It checks the pid,
4422 : // so it holds without the fork handlers too. The caller holds the engine mutex.
4423 1871 : static void client_engine_forget_inherited_locked(void) {
4424 1871 : if (!cli_engine_bundler.stopping && !cli_engine_bundler.reaper_joinable &&
4425 1498 : !(cli_engine_bundler.reactor && cli_engine_bundler.reactor_refs == 0))
4426 : return;
4427 374 : if (atomic_load(&g_client_engine_pid) == getpid()) return;
4428 0 : clog inherited_logger = cli_engine_bundler.logger;
4429 0 : cli_engine_bundler.logger = CLOG_NULL;
4430 0 : if (inherited_logger && inherited_logger != cli_engine_bundler.user_logger)
4431 0 : clog_close(inherited_logger);
4432 0 : cli_engine_bundler.reactor = CEVENTLOOP_NULL;
4433 0 : cli_engine_bundler.dns_pool = CTHRPOOL_NULL;
4434 0 : cli_engine_bundler.reactor_refs = 0;
4435 0 : cli_engine_bundler.stopping = false;
4436 0 : cli_engine_bundler.reaper_joinable = false;
4437 0 : cli_engine_bundler.chains_live = 0;
4438 0 : cli_engine_bundler.exit_waiting = false;
4439 0 : atomic_store(&g_async_requests_pending, 0);
4440 0 : atomic_store(&g_async_hops_abandoned, 0);
4441 0 : atomic_store(&g_engine_reap_abandoned, false);
4442 : }
4443 :
4444 : #ifdef RUNNING_UNIT_TESTS
4445 : // While non-zero, the next reaper holds the engine mutex this many ms in its
4446 : // final critical section and sets the entered flag, so a test can race it.
4447 : static _Atomic int g_reaper_final_hold_ms_for_tests = 0;
4448 : static _Atomic bool g_reaper_final_hold_entered_for_tests = false;
4449 :
4450 : // Runs the reaper's final-section hold, once, so a test can race the end of a
4451 : // teardown.
4452 406 : static void reaper_final_hold_for_tests(void) {
4453 406 : int ms = atomic_exchange(&g_reaper_final_hold_ms_for_tests, 0);
4454 406 : if (ms <= 0) return;
4455 4 : atomic_store(&g_reaper_final_hold_entered_for_tests, true);
4456 4 : struct timespec ts = {ms / 1000, (long)(ms % 1000) * 1000000L};
4457 4 : nanosleep(&ts, NULL);
4458 : }
4459 :
4460 : // While non-zero, the next reaper waits this many ms after it closes the
4461 : // fallback logger, the last thing it does, holding no lock. Fires once.
4462 : static _Atomic int g_reaper_tail_hold_ms_for_tests = 0;
4463 : static _Atomic bool g_reaper_tail_hold_entered_for_tests = false;
4464 : static _Atomic bool g_reaper_tail_hold_left_for_tests = false;
4465 :
4466 : // Runs the reaper's tail hold, once, so a test can fork while the reaper
4467 : // finishes after clearing stopping.
4468 406 : static void reaper_tail_hold_for_tests(void) {
4469 406 : int ms = atomic_exchange(&g_reaper_tail_hold_ms_for_tests, 0);
4470 406 : if (ms <= 0) return;
4471 1 : atomic_store(&g_reaper_tail_hold_entered_for_tests, true);
4472 1 : struct timespec ts = {ms / 1000, (long)(ms % 1000) * 1000000L};
4473 1 : nanosleep(&ts, NULL);
4474 1 : atomic_store(&g_reaper_tail_hold_left_for_tests, true);
4475 : }
4476 : #endif
4477 :
4478 : // Tears the engine down on the reaper thread. It stops the deadline sweep first
4479 : // (a tick may use the reactor and the DNS pool), then destroys the reactor and
4480 : // the DNS pool outside the lock, clears stopping last so a waiting acquirer can
4481 : // go on, and closes the fallback logger. It never runs on the thread that
4482 : // dropped the last reference, which is often an engine thread.
4483 409 : static void *client_engine_reaper_fn(void *arg) {
4484 409 : (void)arg;
4485 409 : ceventloop loop_to_destroy;
4486 409 : cthrpool dns_pool_to_destroy;
4487 409 : ccol__mutex_lock(cli_engine_bundler.mutex);
4488 409 : loop_to_destroy = cli_engine_bundler.reactor;
4489 409 : dns_pool_to_destroy = cli_engine_bundler.dns_pool;
4490 409 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4491 :
4492 409 : client_deadline_sweep_stop_and_join();
4493 409 : if (loop_to_destroy) ceventloop_destroy(loop_to_destroy);
4494 409 : if (dns_pool_to_destroy) cthrpool_destroy(dns_pool_to_destroy);
4495 :
4496 406 : ccol__mutex_lock(cli_engine_bundler.mutex);
4497 : #ifdef RUNNING_UNIT_TESTS
4498 406 : reaper_final_hold_for_tests();
4499 : #endif
4500 406 : cli_engine_bundler.dns_pool = CTHRPOOL_NULL;
4501 406 : cli_engine_bundler.reactor = CEVENTLOOP_NULL;
4502 406 : cli_engine_bundler.stopping = false;
4503 406 : if (cli_engine_bundler.logger)
4504 406 : clog_info(cli_engine_bundler.logger,
4505 : "The http client reactor engine has been destroyed");
4506 812 : clog old_logger = cli_engine_bundler.logger != cli_engine_bundler.user_logger
4507 : ? cli_engine_bundler.logger
4508 406 : : CLOG_NULL;
4509 406 : cli_engine_bundler.logger = CLOG_NULL;
4510 406 : ccol__cond_var_broadcast(cli_engine_bundler.stopped_cv);
4511 406 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4512 406 : if (old_logger) clog_close(old_logger);
4513 : #ifdef RUNNING_UNIT_TESTS
4514 406 : reaper_tail_hold_for_tests();
4515 : #endif
4516 406 : return NULL;
4517 : }
4518 :
4519 : // Extra attempts and the pause between them when pthread_create fails (EAGAIN
4520 : // under a thread ceiling clears quickly). The total stays small because this
4521 : // may run on a dispatch thread.
4522 : #define CHTTP_REAPER_SPAWN_RETRIES 5
4523 : #define CHTTP_REAPER_SPAWN_RETRY_NS (1000L * 1000L)
4524 :
4525 : #ifdef RUNNING_UNIT_TESTS
4526 : // While set, client_engine_spawn_reaper treats every thread creation as failed,
4527 : // so a test reaches the give-up path; the counter says how often it gave up.
4528 : static _Atomic bool g_force_reaper_spawn_fail_for_tests = false;
4529 : static _Atomic unsigned g_reaper_abandoned_count_for_tests = 0;
4530 :
4531 : // -1 until a shutdown of an abandoned ctx has run, then 1 if it ran with the
4532 : // ctx's idle_lock held and 0 if not. Only 1 is safe: After the unlock a
4533 : // dispatch can close the fd and the number can name another socket.
4534 : static _Atomic int g_abandon_shutdown_under_lock_for_tests = -1;
4535 :
4536 : // While set, the next reaper is held between its creation and the publish of
4537 : // its handle until a test opens the gate (10 s at most), so a second spawn can
4538 : // start in that window. Fires once.
4539 : static _Atomic bool g_reaper_spawn_hold_for_tests = false;
4540 : static _Atomic bool g_reaper_spawn_held_for_tests = false;
4541 : static _Atomic bool g_reaper_spawn_gate_for_tests = false;
4542 :
4543 : // Runs the reaper spawn hold, so a test can start a second spawn while the
4544 : // first one's handle isn't published yet.
4545 409 : static void reaper_spawn_hook_for_tests(void) {
4546 409 : if (!atomic_exchange(&g_reaper_spawn_hold_for_tests, false)) return;
4547 1 : atomic_store(&g_reaper_spawn_held_for_tests, true);
4548 1002 : for (int i = 0; i < 10000 && !atomic_load(&g_reaper_spawn_gate_for_tests);
4549 1001 : ++i) {
4550 1001 : struct timespec ts = {0, 1000000L};
4551 1001 : nanosleep(&ts, NULL);
4552 : }
4553 : }
4554 : #endif
4555 :
4556 : // Hands the engine teardown to a new reaper thread, with a few retries, when
4557 : // the last reference goes away. The teardown can't run inline: On a dispatch
4558 : // thread or a DNS worker it would join itself. When no thread can be had, the
4559 : // engine stays up with no reference and g_engine_reap_abandoned set, and the
4560 : // sweep retries. The handle (cli_engine_bundler.reaper) is published in the
4561 : // critical section that creates the thread. The caller holds the engine mutex.
4562 414 : static void client_engine_spawn_reaper(void) {
4563 414 : ccol__thread_id reaper;
4564 414 : int rc = -1;
4565 444 : for (int attempt = 0; attempt <= CHTTP_REAPER_SPAWN_RETRIES; attempt++) {
4566 439 : if (attempt > 0) {
4567 25 : struct timespec pause = {.tv_sec = 0,
4568 : .tv_nsec = CHTTP_REAPER_SPAWN_RETRY_NS};
4569 25 : nanosleep(&pause, NULL);
4570 : }
4571 : #ifdef RUNNING_UNIT_TESTS
4572 439 : if (atomic_load(&g_force_reaper_spawn_fail_for_tests)) {
4573 30 : rc = -1;
4574 30 : continue;
4575 : }
4576 : #endif
4577 409 : ccol__mutex_lock(cli_engine_bundler.mutex);
4578 409 : rc = ccol__thread_create(reaper, client_engine_reaper_fn, NULL);
4579 409 : if (rc == 0) {
4580 : #ifdef RUNNING_UNIT_TESTS
4581 409 : atomic_fetch_add(&g_reaper_created_for_tests, 1u);
4582 409 : reaper_spawn_hook_for_tests();
4583 : #endif
4584 409 : client_engine_join_reaper_if_needed_locked();
4585 409 : cli_engine_bundler.reaper_thread = reaper;
4586 409 : cli_engine_bundler.reaper_joinable = true;
4587 409 : atomic_store(&g_engine_reap_abandoned, false);
4588 : }
4589 409 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4590 409 : if (rc == 0) break;
4591 : }
4592 414 : if (rc != 0) {
4593 : #ifdef RUNNING_UNIT_TESTS
4594 5 : atomic_fetch_add(&g_reaper_abandoned_count_for_tests, 1u);
4595 : #endif
4596 5 : ccol__mutex_lock(cli_engine_bundler.mutex);
4597 5 : cli_engine_bundler.stopping = false;
4598 5 : bool first_give_up = !atomic_exchange(&g_engine_reap_abandoned, true);
4599 5 : ccol__cond_var_broadcast(cli_engine_bundler.stopped_cv);
4600 5 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4601 5 : if (first_give_up)
4602 3 : CLIENT_ENGINE_LOG_INFO(
4603 : "The http client reactor engine could not be reaped (no thread "
4604 : "available); the deadline sweep retries the teardown");
4605 5 : return;
4606 : }
4607 : }
4608 :
4609 : // Retries the teardown of an engine left with no reference. Only the sweep
4610 : // calls it, once a tick, holding no lock.
4611 606 : static void client_engine_retry_abandoned_reap(void) {
4612 606 : if (!atomic_load_explicit(&g_engine_reap_abandoned, memory_order_relaxed))
4613 : return;
4614 3 : bool reap = false;
4615 3 : ccol__mutex_lock(cli_engine_bundler.mutex);
4616 3 : if (atomic_load(&g_engine_reap_abandoned) && cli_engine_bundler.reactor &&
4617 3 : cli_engine_bundler.reactor_refs == 0 && !cli_engine_bundler.stopping) {
4618 3 : cli_engine_bundler.stopping = true;
4619 3 : reap = true;
4620 : }
4621 3 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4622 3 : if (reap) client_engine_spawn_reaper();
4623 : }
4624 :
4625 : // Takes a reference to the engine. The first one creates the reactor, the DNS
4626 : // pool and the deadline sweep, and registers the exit hook after OpenSSL's
4627 : // cleanup so the hook runs first. A failed step clears its fields under the
4628 : // mutex and destroys outside it. for_chain also counts the reference in
4629 : // chains_live and the request in g_async_requests_pending. Every success pairs
4630 : // with one release.
4631 1505 : static ccol_retval client_engine_acquire_impl(bool for_chain) {
4632 1505 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4633 1504 : ccol__call_once(cli_engine_bundler.exit_hook_once, client_exit_hook_install);
4634 : #if CCOL_FORK_SAFETY_REQUIRED
4635 1504 : ccol__call_once(cli_engine_bundler.atfork_once, client_atfork_install);
4636 : #endif
4637 1505 : ccol__mutex_lock(cli_engine_bundler.mutex);
4638 1505 : client_engine_forget_inherited_locked();
4639 1588 : while (cli_engine_bundler.stopping)
4640 83 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
4641 : cli_engine_bundler.mutex);
4642 1505 : client_engine_join_reaper_if_needed_locked();
4643 :
4644 1505 : if (!cli_engine_bundler.reactor) {
4645 419 : atomic_store(&g_client_engine_pid, getpid());
4646 419 : size_t nthreads = cli_engine_bundler.num_reactor_threads;
4647 419 : if (nthreads == 0) {
4648 408 : long cpus = sysconf(_SC_NPROCESSORS_ONLN);
4649 408 : nthreads = (cpus > 0) ? (size_t)cpus : 1;
4650 : }
4651 419 : cli_engine_bundler.last_resolved_num_reactor_threads = nthreads;
4652 419 : char *err = NULL;
4653 838 : cli_engine_bundler.reactor =
4654 419 : ceventloop_create_mp(256, 4, nthreads, cli_engine_bundler.mprocs, &err);
4655 419 : if (!cli_engine_bundler.reactor) {
4656 0 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4657 0 : return ccol_not_enough_memory;
4658 : }
4659 :
4660 419 : char *dns_err = NULL;
4661 838 : cli_engine_bundler.dns_pool =
4662 419 : cthrpool_create_mp(nthreads, 0, cli_engine_bundler.mprocs, &dns_err);
4663 419 : if (!cli_engine_bundler.dns_pool) {
4664 0 : ceventloop stale_reactor = cli_engine_bundler.reactor;
4665 0 : cli_engine_bundler.reactor = CEVENTLOOP_NULL;
4666 0 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4667 0 : ceventloop__destroy(stale_reactor);
4668 0 : return ccol_not_enough_memory;
4669 : }
4670 :
4671 838 : if (client_deadline_sweep_start() != ccol_success) {
4672 0 : cthrpool stale_dns_pool = cli_engine_bundler.dns_pool;
4673 0 : ceventloop stale_reactor = cli_engine_bundler.reactor;
4674 0 : cli_engine_bundler.dns_pool = CTHRPOOL_NULL;
4675 0 : cli_engine_bundler.reactor = CEVENTLOOP_NULL;
4676 0 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4677 0 : cthrpool__destroy(stale_dns_pool);
4678 0 : ceventloop__destroy(stale_reactor);
4679 0 : return ccol_unexpected_failure;
4680 : }
4681 :
4682 419 : if (!cli_engine_bundler.logger && cli_engine_bundler.user_logger)
4683 125 : cli_engine_bundler.logger = cli_engine_bundler.user_logger;
4684 419 : if (!cli_engine_bundler.logger) {
4685 294 : cli_engine_bundler.logger = clog_create_from_fd_mp(
4686 : 2, CLOG_FATAL, NULL, cli_engine_bundler.mprocs);
4687 294 : if (!cli_engine_bundler.logger) {
4688 0 : cli_engine_bundler.stopping = true;
4689 0 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4690 0 : client_engine_spawn_reaper();
4691 0 : return ccol_not_enough_memory;
4692 : }
4693 294 : clog_set_field(cli_engine_bundler.logger, "component",
4694 : "http-client-engine");
4695 : }
4696 :
4697 419 : clog_info(cli_engine_bundler.logger,
4698 : "New http client reactor engine has been created");
4699 : }
4700 1505 : cli_engine_bundler.reactor_refs++;
4701 1505 : if (for_chain) {
4702 923 : cli_engine_bundler.chains_live++;
4703 923 : atomic_fetch_add_explicit(&g_async_requests_pending, 1,
4704 : memory_order_relaxed);
4705 923 : if (cli_engine_bundler.exit_waiting)
4706 0 : ccol__cond_var_broadcast(cli_engine_bundler.stopped_cv);
4707 : }
4708 1505 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4709 1505 : return ccol_success;
4710 : }
4711 :
4712 : // Takes an engine reference that isn't tied to a chain, for an idle pooled
4713 : // connection and for the tests.
4714 582 : static ccol_retval client_engine_acquire(void) {
4715 582 : return client_engine_acquire_impl(false);
4716 : }
4717 :
4718 : // Takes the engine reference of an async chain, which also counts the request
4719 : // in g_async_requests_pending so client_at_exit knows one is in flight. Pairs
4720 : // with client_engine_release_chain.
4721 923 : static ccol_retval client_engine_acquire_chain(void) {
4722 923 : return client_engine_acquire_impl(true);
4723 : }
4724 :
4725 : // Takes a request off g_async_requests_pending right before its future is
4726 : // fulfilled, so whoever sees the future ready also sees the count without it.
4727 917 : static inline void client_async_request_settled(void) {
4728 917 : atomic_fetch_sub_explicit(&g_async_requests_pending, 1, memory_order_release);
4729 : }
4730 :
4731 : // Drops a reference. The last one hands the teardown to a reaper thread, since
4732 : // the caller is often a reactor thread that must not join the sweep or drain
4733 : // the DNS pool.
4734 1497 : static void client_engine_release_impl(bool for_chain) {
4735 1497 : bool should_reap = false;
4736 1497 : ccol__mutex_lock(cli_engine_bundler.mutex);
4737 1497 : if (for_chain && cli_engine_bundler.chains_live > 0 &&
4738 916 : --cli_engine_bundler.chains_live == 0 && cli_engine_bundler.exit_waiting)
4739 0 : ccol__cond_var_broadcast(cli_engine_bundler.stopped_cv);
4740 1497 : if (cli_engine_bundler.reactor_refs > 0) cli_engine_bundler.reactor_refs--;
4741 1497 : if (cli_engine_bundler.reactor_refs == 0 && cli_engine_bundler.reactor) {
4742 411 : cli_engine_bundler.stopping = true;
4743 411 : should_reap = true;
4744 : }
4745 1497 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4746 1497 : if (should_reap) client_engine_spawn_reaper();
4747 1497 : }
4748 :
4749 : // Drops an engine reference that client_engine_acquire took.
4750 581 : static void client_engine_release(void) { client_engine_release_impl(false); }
4751 :
4752 : // Drops the reference of client_engine_acquire_chain, when its chain is freed.
4753 916 : static void client_engine_release_chain(void) {
4754 916 : client_engine_release_impl(true);
4755 : }
4756 :
4757 : #ifdef RUNNING_UNIT_TESTS
4758 : // Waits until a reaper in progress has finished, so a test can wait for a
4759 : // teardown it caused. Returns at once when nothing is stopping.
4760 340 : static void client_engine_wait_for_quiescence(void) {
4761 340 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4762 340 : ccol__mutex_lock(cli_engine_bundler.mutex);
4763 340 : client_engine_forget_inherited_locked();
4764 557 : while (cli_engine_bundler.stopping)
4765 217 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
4766 : cli_engine_bundler.mutex);
4767 340 : client_engine_join_reaper_if_needed_locked();
4768 340 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4769 340 : }
4770 : #endif
4771 :
4772 : // Waits while the engine runs or stops, and joins the reaper. A reaper that
4773 : // couldn't start leaves an unreferenced reactor that the sweep tears down, and
4774 : // this waits for that too. Fatal on an engine thread, which would wait for
4775 : // itself.
4776 5 : void chttpcli_engine_wait(void) {
4777 10 : if (chttpcli_runs_on_engine_thread())
4778 0 : ccol__fatal_err(
4779 : "chttpcli_engine_wait: called on a thread of the async engine (a "
4780 : "write_fn of chttpcli_do_async_streaming or "
4781 : "chttpcli_do_pooled_streaming), which would wait for its own "
4782 : "thread; call it from another thread");
4783 5 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4784 5 : ccol__mutex_lock(cli_engine_bundler.mutex);
4785 5 : client_engine_forget_inherited_locked();
4786 9 : while (cli_engine_bundler.reactor || cli_engine_bundler.stopping)
4787 4 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
4788 : cli_engine_bundler.mutex);
4789 5 : client_engine_join_reaper_if_needed_locked();
4790 5 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4791 5 : }
4792 :
4793 : // Stops the client engine at exit (the atexit handler). It destroys the default
4794 : // client and tears the engine down before OpenSSL's cleanup, so no engine
4795 : // thread frees OpenSSL's per-thread state after it. It stands aside in a fork
4796 : // child, while any async request is pending and while an abandoned hop exists,
4797 : // so an exit() from a write_fn can't deadlock.
4798 33 : static void client_at_exit(void) {
4799 33 : if (atomic_load(&g_client_engine_pid) != getpid()) return;
4800 33 : if (atomic_load_explicit(&g_async_requests_pending, memory_order_acquire) ||
4801 31 : atomic_load_explicit(&g_async_hops_abandoned, memory_order_acquire))
4802 3 : return;
4803 30 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4804 :
4805 30 : ccol__mutex_lock(cli_engine_bundler.mutex);
4806 30 : cli_engine_bundler.exit_waiting = true;
4807 30 : while (cli_engine_bundler.chains_live > 0 &&
4808 30 : atomic_load(&g_async_requests_pending) == 0 &&
4809 0 : atomic_load(&g_async_hops_abandoned) == 0)
4810 0 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
4811 : cli_engine_bundler.mutex);
4812 30 : cli_engine_bundler.exit_waiting = false;
4813 30 : bool in_flight = cli_engine_bundler.chains_live > 0;
4814 30 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4815 30 : if (in_flight) return;
4816 :
4817 30 : default_client_destroy_if_idle();
4818 :
4819 30 : ccol__mutex_lock(cli_engine_bundler.mutex);
4820 55 : while (cli_engine_bundler.stopping)
4821 25 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
4822 : cli_engine_bundler.mutex);
4823 30 : client_engine_join_reaper_if_needed_locked();
4824 60 : bool reap_here =
4825 30 : cli_engine_bundler.reactor && cli_engine_bundler.reactor_refs == 0;
4826 0 : if (reap_here) {
4827 0 : cli_engine_bundler.stopping = true;
4828 0 : atomic_store(&g_engine_reap_abandoned, false);
4829 : }
4830 30 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4831 30 : if (reap_here) (void)client_engine_reaper_fn(NULL);
4832 : }
4833 :
4834 : // Calls OPENSSL_init_ssl first (which registers OpenSSL's cleanup) and then
4835 : // registers client_at_exit, once, so ours runs first.
4836 36 : static void client_exit_hook_install(void) {
4837 36 : atomic_store(&g_client_engine_pid, getpid());
4838 36 : (void)OPENSSL_init_ssl(0, NULL);
4839 36 : (void)atexit(client_at_exit);
4840 36 : }
4841 :
4842 : // Installs a logger for engine diagnostics (a handle derived from cl), or
4843 : // releases it for CLOG_NULL, so the application decides where engine messages
4844 : // go. The logger is kept across engine stops and starts. A release waits for a
4845 : // full stop and is ccol_not_permitted while the engine runs or stops. A closed
4846 : // or stale handle is ccol_invalid_args and the installed logger stays. Takes
4847 : // the engine mutex.
4848 9 : ccol_retval chttpcli_set_engine_logger(clog cl) {
4849 9 : if (!cl) {
4850 3 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4851 3 : ccol__mutex_lock(cli_engine_bundler.mutex);
4852 3 : client_engine_forget_inherited_locked();
4853 3 : if (cli_engine_bundler.reactor || cli_engine_bundler.stopping) {
4854 1 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4855 1 : return ccol_not_permitted;
4856 : }
4857 2 : clog old_user = cli_engine_bundler.user_logger;
4858 2 : cli_engine_bundler.user_logger = CLOG_NULL;
4859 2 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4860 2 : if (old_user) clog_close(old_user);
4861 2 : return ccol_success;
4862 : }
4863 6 : ccol_retval derive_rv = ccol_success;
4864 6 : clog derived = clog__derive_checked(cl, &derive_rv);
4865 6 : if (!derived) return derive_rv;
4866 5 : clog_set_field(derived, "component", "http-client-engine");
4867 5 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4868 5 : ccol__mutex_lock(cli_engine_bundler.mutex);
4869 5 : clog old_user = cli_engine_bundler.user_logger;
4870 5 : clog old_active = cli_engine_bundler.logger;
4871 5 : cli_engine_bundler.user_logger = derived;
4872 5 : if (old_active) cli_engine_bundler.logger = derived;
4873 5 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4874 5 : if (old_active && old_active != old_user) clog_close(old_active);
4875 5 : if (old_user) clog_close(old_user);
4876 : return ccol_success;
4877 : }
4878 :
4879 : // At exit or unload, closes the installed engine logger, but only when the
4880 : // engine is fully stopped. It returns at once when the engine globals were
4881 : // never initialized, since initializing them here would leave resources no
4882 : // destructor frees.
4883 39 : __attribute__((destructor)) static void cleanup_engine_user_logger(void) {
4884 39 : if (!atomic_load(&g_engine_globals_entered)) return;
4885 33 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4886 33 : ccol__mutex_lock(cli_engine_bundler.mutex);
4887 33 : clog user = CLOG_NULL;
4888 33 : if (!cli_engine_bundler.reactor && !cli_engine_bundler.stopping &&
4889 30 : cli_engine_bundler.logger != cli_engine_bundler.user_logger) {
4890 0 : user = cli_engine_bundler.user_logger;
4891 0 : cli_engine_bundler.user_logger = CLOG_NULL;
4892 : }
4893 33 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4894 33 : if (user) clog_close(user);
4895 : }
4896 :
4897 : // Sets the allocator of the engine's own objects, so an application can route
4898 : // them through its allocator. ccol_not_permitted while the engine runs.
4899 4 : ccol_retval chttpcli_set_engine_mem_mgmt_procs(ccol_memmgmt_procs *mp) {
4900 4 : if (mp && (!mp->malloc || !mp->free || !mp->calloc || !mp->realloc))
4901 : return ccol_invalid_args;
4902 4 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4903 4 : ccol__mutex_lock(cli_engine_bundler.mutex);
4904 4 : client_engine_forget_inherited_locked();
4905 4 : if (cli_engine_bundler.reactor) {
4906 0 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4907 0 : return ccol_not_permitted;
4908 : }
4909 4 : if (mp) {
4910 2 : cli_engine_bundler.mprocs_storage = *mp;
4911 2 : cli_engine_bundler.mprocs = &cli_engine_bundler.mprocs_storage;
4912 : } else {
4913 2 : cli_engine_bundler.mprocs = NULL;
4914 : }
4915 4 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4916 4 : return ccol_success;
4917 : }
4918 :
4919 : // Sets the reactor thread count of the next engine (0 picks the CPU count), so
4920 : // an application can size the engine. ccol_not_permitted while the engine runs.
4921 14 : ccol_retval chttpcli_set_engine_num_reactor_threads(size_t num_threads) {
4922 14 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
4923 14 : ccol__mutex_lock(cli_engine_bundler.mutex);
4924 14 : client_engine_forget_inherited_locked();
4925 14 : if (cli_engine_bundler.reactor) {
4926 2 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4927 2 : return ccol_not_permitted;
4928 : }
4929 12 : cli_engine_bundler.num_reactor_threads = num_threads;
4930 12 : ccol__mutex_unlock(cli_engine_bundler.mutex);
4931 12 : return ccol_success;
4932 : }
4933 :
4934 : // Async connection state machine
4935 : //
4936 : // Tier 2 and Tier 3 run each hop as a non-blocking state machine on the client
4937 : // engine, with the same ctls API and parser as Tier 1. One reactor registration
4938 : // per connection carries every step, and redirects sit on top of it as a chain
4939 : // of hops.
4940 : typedef enum {
4941 : CHTTP_ASYNC_CONNECTING,
4942 : CHTTP_ASYNC_TLS_HANDSHAKING,
4943 : CHTTP_ASYNC_WRITING,
4944 : CHTTP_ASYNC_AWAITING_CONTINUE,
4945 : CHTTP_ASYNC_READING,
4946 : CHTTP_ASYNC_IDLE,
4947 : } chttp_async_state;
4948 :
4949 : // The shared state of one async request, one per redirect chain (not per hop).
4950 : // Every hop holds a reference; lock guards fulfilled, result and refcount,
4951 : // because an old hop's teardown can run while the next hop's dispatch runs. The
4952 : // fields written per hop (carried_auth, redirect_drops, the body fields) need
4953 : // no lock, since only the thread that parsed a hop's response submits the next
4954 : // hop.
4955 : typedef struct {
4956 : ccol_memmgmt_procs *mp;
4957 : struct chttpclient *cli;
4958 : cthrpool_future *future;
4959 :
4960 : // The caller's streaming sink (NULL for a buffered request). sink_closed and
4961 : // in_sink make sure no write_fn call starts after the future is fulfilled.
4962 : chttpcli_write_fn write_fn;
4963 : void *write_ctx;
4964 : _Atomic bool sink_closed;
4965 : _Atomic bool in_sink;
4966 :
4967 : // The request as submitted: Headers, body and content type. body_dropped is
4968 : // set once a redirect turns the request into a bodiless GET.
4969 : chmap req_headers;
4970 : void *body_data;
4971 : size_t body_len;
4972 : char *body_content_type;
4973 : bool body_dropped;
4974 :
4975 : // The URL's Authorization value, carried across hops on the same origin and
4976 : // dropped for good once the origin changes, and the origin it was made for.
4977 : char *carried_auth;
4978 : char *carried_auth_origin;
4979 :
4980 : // The origin of hop 0, and the CHTTP_REDIRECT_DROP_* flags of the current hop
4981 : // judged against it.
4982 : char *initial_origin_key;
4983 : unsigned redirect_drops;
4984 :
4985 : // A snapshot of the client's TLS context and settings, taken once when the
4986 : // request starts.
4987 : ctls_ctx *tls_ctx;
4988 : bool tls_ctx_usable;
4989 : bool tls_ctx_oom;
4990 : bool verify_host;
4991 : uint64_t tls_generation;
4992 :
4993 : // Timeouts and options of the request, copied at submit.
4994 : uint64_t connect_timeout_us;
4995 : chttp_deadline overall_deadline;
4996 : size_t max_response_body_size;
4997 : bool prevent_tls_downgrade_on_redirect;
4998 : bool expect_continue;
4999 :
5000 : // Guards fulfilled, result and refcount. result is allocated ahead, so the
5001 : // fulfilment allocates nothing.
5002 : ccol__mutex lock;
5003 : bool fulfilled;
5004 : chttpcli_async_result *result;
5005 : int refcount;
5006 : // The inactivity timeout and when write_fn last returned, which the sweep
5007 : // compares with the connection's last I/O.
5008 : uint64_t inactivity_timeout_us;
5009 : _Atomic uint64_t sink_returned_ns;
5010 : } chttp_async_chain;
5011 :
5012 : static void async_fulfill_chain(chttp_async_chain *chain, ccol_retval rv,
5013 : chttpcli_response *resp);
5014 :
5015 : // Passes body bytes of a streaming Tier 2 or Tier 3 request to the caller's
5016 : // write_fn (the chain's sink), with a frame of the client pushed so a destroy
5017 : // from inside write_fn is fatal instead of a wait for itself. It never calls
5018 : // write_fn after the sweep closed the sink (sink_closed, in_sink); a call it
5019 : // refuses fulfils ccol_timed_out itself. Gives the count write_fn gave, or a
5020 : // short count to stop.
5021 30 : static size_t sink_async_user(const void *data, size_t len, void *ctx) {
5022 30 : chttp_async_chain *chain = (chttp_async_chain *)ctx;
5023 30 : atomic_store(&chain->in_sink, true);
5024 30 : if (atomic_load(&chain->sink_closed)) {
5025 1 : atomic_store(&chain->in_sink, false);
5026 1 : async_fulfill_chain(chain, ccol_timed_out, NULL);
5027 1 : return 0;
5028 : }
5029 29 : chttpcli_call_frame frame;
5030 29 : chttpcli_call_push(&frame, chain->cli, true);
5031 29 : size_t n = chain->write_fn(data, len, chain->write_ctx);
5032 24 : chttpcli_call_pop(&frame);
5033 24 : atomic_store(&chain->sink_returned_ns, monotonic_now_ns());
5034 24 : atomic_store(&chain->in_sink, false);
5035 24 : return n;
5036 : }
5037 :
5038 : // Closes a streaming chain's sink and waits until no write_fn call runs, so the
5039 : // future is fulfilled with no call after it.
5040 1 : static void async_sink_close(chttp_async_chain *chain) {
5041 1 : atomic_store(&chain->sink_closed, true);
5042 474 : while (atomic_load(&chain->in_sink)) {
5043 473 : struct timespec ts = {.tv_sec = 0, .tv_nsec = 1000000L};
5044 473 : nanosleep(&ts, NULL);
5045 : }
5046 1 : }
5047 :
5048 : // See the async Happy Eyeballs section.
5049 : typedef struct chttp_connect_race_s chttp_connect_race;
5050 :
5051 : // The values of ctx->flip_watch. ON_INPUT: The send waits for room, and a
5052 : // response arriving turns the registration to reading. ON_ROOM: A paused duplex
5053 : // send waits for input, and room turns it to writing. See async_upload_pause.
5054 : #define CHTTP_FLIP_NONE 0
5055 : #define CHTTP_FLIP_ON_INPUT 1
5056 : #define CHTTP_FLIP_ON_ROOM 2
5057 :
5058 : // One async connection and the hop it serves. It's tagged so the deadline list
5059 : // links can point at it. A connection outlives its chain when it goes back to
5060 : // the idle pool (state CHTTP_ASYNC_IDLE, chain NULL).
5061 : typedef struct chttp_async_ctx_s {
5062 : ccol_memmgmt_procs *mp;
5063 : struct chttpclient *cli;
5064 : chttp_async_chain *_Atomic chain;
5065 : // The hop index and the method this hop's bytes were built with.
5066 : int hop;
5067 : chttp_method cur_method;
5068 : // The state, the fd and the reactor registration. reg is atomic because
5069 : // ceventloop_add publishes it before the call returns. room_reg exists only
5070 : // while a paused duplex send waits for room; it shares reg's dispatch lock.
5071 : _Atomic chttp_async_state state;
5072 : _Atomic int fd;
5073 : _Atomic(ceventloop_reg) reg;
5074 : _Atomic(ceventloop_reg) room_reg;
5075 :
5076 : // The target of this connection, the candidate addresses and the Happy
5077 : // Eyeballs race in progress.
5078 : bool is_unix;
5079 : char *unix_socket_path;
5080 : char *host;
5081 : uint16_t port;
5082 : chttp_addr_list *addrs;
5083 : _Atomic(chttp_connect_race *) race;
5084 : bool is_ipv6;
5085 : char *path_and_query;
5086 : char *origin_key;
5087 : // The retry-once and pooling bookkeeping: Whether the connection came from
5088 : // the pool, whether any byte was read, and the interim responses skipped.
5089 : bool reused;
5090 : bool any_bytes_read;
5091 : size_t interim_responses_seen;
5092 : struct timespec last_used;
5093 : // Duplex upload state: A paused send, the direction the sweep watches
5094 : // (CHTTP_FLIP_*), a response that began while sending, and when to look for
5095 : // input next.
5096 : bool upload_paused;
5097 : _Atomic unsigned char flip_watch;
5098 : bool answered_early;
5099 : bool duplex;
5100 : size_t upload_check_at;
5101 : // Set when the IDLE dispatch's own read took input, so a later take sends the
5102 : // hop to the retry path; reuse_checked and tls_read_blocked go with the probe
5103 : // of a reused connection.
5104 : bool idle_tainted;
5105 : bool reuse_checked;
5106 : bool tls_read_blocked;
5107 : bool resp_msg_started;
5108 : // The serialized request and how much of it went out.
5109 : char *wire;
5110 : size_t wire_len;
5111 : size_t wire_sent;
5112 :
5113 : bool is_https;
5114 : bool verify_host;
5115 : uint64_t tls_generation;
5116 : #ifdef RUNNING_UNIT_TESTS
5117 : bool idle_lock_held_for_tests;
5118 : #endif
5119 : // hop_completed settles which dispatch finishes the hop, since a spurious
5120 : // extra dispatch would run the redirect hand-off twice. pending_app_teardown
5121 : // marks a teardown that an application-thread path left to the dispatch.
5122 : _Atomic bool hop_completed;
5123 : _Atomic bool pending_app_teardown;
5124 : ctls_conn *tls;
5125 :
5126 : // Guards state and chain together while the connection moves between idle and
5127 : // active.
5128 : ccol__mutex idle_lock;
5129 :
5130 : // The deadlines. deadline_lock is a leaf lock that makes the sweep's snapshot
5131 : // and verdict one step against the idle pool's offer and take.
5132 : chttp_deadline connect_deadline;
5133 : ccol__mutex deadline_lock;
5134 : chttp_deadline overall_deadline;
5135 : // abandoned: The sweep fulfilled this live hop's future. timed_out: The sweep
5136 : // marked it and shut its fd down. Both are written without a lock.
5137 : _Atomic bool abandoned;
5138 : _Atomic bool timed_out;
5139 : bool deadline_registered;
5140 : struct chttp_async_ctx_s *deadline_prev, *deadline_next;
5141 :
5142 : // The response parse of this hop.
5143 : chttp1_parser parser;
5144 : chttp_parse_ctx pctx;
5145 : chttp_bodybuf bb;
5146 :
5147 : // "Expect: 100-continue" state. continue_decided lets exactly one of the "100
5148 : // seen" and the timeout branches send the body; continue_msg_started ends the
5149 : // window once a message's first byte arrived.
5150 : bool want_100_continue;
5151 : size_t header_len;
5152 : _Atomic bool continue_decided;
5153 : _Atomic bool continue_msg_started;
5154 : chttp_deadline continue_deadline;
5155 : // retry_unsafe: The body went out after a "100 Continue", so it is never sent
5156 : // again. replayable and request_close come from the request.
5157 : bool retry_unsafe;
5158 : bool replayable;
5159 : bool request_close;
5160 : // Bytes that arrived with the "100 Continue" line, fed to the next parse.
5161 : char *continue_carry;
5162 : size_t continue_carry_len;
5163 : // The inactivity timeout and the last instant a byte moved (0 at hop start).
5164 : uint64_t inactivity_us;
5165 : _Atomic uint64_t last_io_ns;
5166 : } chttp_async_ctx;
5167 :
5168 : // Async deadline sweep
5169 : //
5170 : // ceventloop has no timers, so one sweep thread enforces the connect, request,
5171 : // 100-continue and inactivity deadlines of Tier 2 and Tier 3 and starts the
5172 : // next Happy Eyeballs attempt. It shuts an expired connection's fd down under
5173 : // its stripe lock, and the dispatch that follows ends the hop. The registry is
5174 : // striped by ctx address, so registering costs one stripe lock.
5175 : #define CHTTP_DEADLINE_SWEEP_STRIPES 16
5176 :
5177 : // One stripe of the registry: A lock and a doubly linked list of ctxs.
5178 : typedef struct {
5179 : ccol__mutex mutex;
5180 : chttp_async_ctx *head;
5181 : } chttp_deadline_stripe;
5182 :
5183 : // The sweep thread and its registry. mutex and cv guard only the thread's
5184 : // start, stop and sleep; the stripes guard the lists.
5185 : static struct {
5186 : ccol__mutex mutex;
5187 : ccol__cond_var cond_var;
5188 : ccol__once_flag once;
5189 : chttp_deadline_stripe stripes[CHTTP_DEADLINE_SWEEP_STRIPES];
5190 : ccol__thread_id thread;
5191 : bool stop;
5192 : } client_deadline_bundle = {0};
5193 :
5194 : // The earliest future instant (CLOCK_MONOTONIC ns) at which the sweep has work.
5195 : // Each tick sets it to UINT64_MAX before its walk and lowers it to what the
5196 : // walk finds, and a thread setting a deadline lowers it too, so no deadline is
5197 : // lost.
5198 : static _Atomic uint64_t g_sweep_next_ns = UINT64_MAX;
5199 :
5200 : // When the sleeping sweep plans to wake, or 0 while it is awake. A deadline
5201 : // earlier than this wakes it; all four accesses are sequentially consistent, so
5202 : // either the sweep sees the new deadline or the setter sees the planned wake.
5203 : static _Atomic uint64_t g_sweep_planned_ns = 0;
5204 :
5205 : // True on the sweep thread, which plans its own wait and holds a stripe lock
5206 : // under which the bundle mutex must not be taken.
5207 : static __thread bool t_on_sweep_thread = false;
5208 :
5209 : #ifdef RUNNING_UNIT_TESTS
5210 : // The number of sweep ticks the process has run.
5211 : static atomic_ulong g_sweep_ticks_for_tests;
5212 :
5213 : // Gives g_sweep_ticks_for_tests, so a test can count sweep walks.
5214 4 : unsigned long chttp__sweep_ticks_for_tests(void) {
5215 4 : return atomic_load(&g_sweep_ticks_for_tests);
5216 : }
5217 :
5218 : // The instant the sweep planned the current walk for; only the sweep thread
5219 : // uses it.
5220 : static uint64_t g_sweep_walk_plan_ns_for_tests;
5221 :
5222 : // For each kind of timed work (0: An expired deadline, 1: A Happy Eyeballs
5223 : // start), how often a walk acted on it and the largest gap between the walk's
5224 : // planned instant and the due instant, so a test can check the plan on a loaded
5225 : // machine.
5226 : static atomic_ulong g_sweep_due_events_for_tests[2];
5227 : static _Atomic int64_t g_sweep_due_max_late_ns_for_tests[2];
5228 :
5229 : // Records one piece of due work for the counters above.
5230 38 : static void sweep_note_due_for_tests(int kind, uint64_t due_ns) {
5231 38 : int64_t late = (int64_t)g_sweep_walk_plan_ns_for_tests - (int64_t)due_ns;
5232 38 : atomic_fetch_add(&g_sweep_due_events_for_tests[kind], 1);
5233 38 : int64_t cur = atomic_load(&g_sweep_due_max_late_ns_for_tests[kind]);
5234 41 : while (late > cur &&
5235 3 : !atomic_compare_exchange_weak(&g_sweep_due_max_late_ns_for_tests[kind],
5236 : &cur, late)) {
5237 38 : }
5238 38 : }
5239 :
5240 : // Resets the due-work counts and maxima, so a test measures only its own
5241 : // requests.
5242 2 : void chttp__sweep_due_reset_for_tests(void) {
5243 6 : for (int k = 0; k < 2; k++) {
5244 4 : atomic_store(&g_sweep_due_events_for_tests[k], 0);
5245 4 : atomic_store(&g_sweep_due_max_late_ns_for_tests[k], INT64_MIN);
5246 : }
5247 2 : }
5248 :
5249 : // The count for kind since the reset, and in *max_late_ns its largest lateness
5250 : // (INT64_MIN with a count of 0).
5251 2 : unsigned long chttp__sweep_due_for_tests(int kind, int64_t *max_late_ns) {
5252 2 : *max_late_ns = atomic_load(&g_sweep_due_max_late_ns_for_tests[kind]);
5253 2 : return atomic_load(&g_sweep_due_events_for_tests[kind]);
5254 : }
5255 : #endif
5256 :
5257 : // Gives the registry stripe of ctx, so register and unregister lock the same
5258 : // stripe without storing it: The pointer is folded to 32 bits and hashed with a
5259 : // multiply read from the high bits.
5260 1667 : static size_t deadline_stripe_index_for_ctx(const chttp_async_ctx *ctx) {
5261 1667 : uintptr_t p = (uintptr_t)ctx;
5262 1667 : uint32_t folded;
5263 : #if UINTPTR_MAX > 0xFFFFFFFFu
5264 1667 : folded = (uint32_t)p ^ (uint32_t)(p >> 32);
5265 : #else
5266 : folded = (uint32_t)p;
5267 : #endif
5268 1667 : uint32_t h = folded * 2654435761u;
5269 1667 : return (size_t)h % CHTTP_DEADLINE_SWEEP_STRIPES;
5270 : }
5271 :
5272 : // Initializes the sweep lock, its CLOCK_MONOTONIC condition variable (the clock
5273 : // of every deadline here) and the stripe locks, once.
5274 33 : static void client_deadline_init_globals(void) {
5275 33 : if (ccol__mutex_init(client_deadline_bundle.mutex) != 0)
5276 0 : ccol__fatal_err("chttpclient deadline sweep: failed to initialize mutex");
5277 561 : for (size_t i = 0; i < CHTTP_DEADLINE_SWEEP_STRIPES; i++) {
5278 528 : if (ccol__mutex_init(client_deadline_bundle.stripes[i].mutex) != 0)
5279 528 : ccol__fatal_err(
5280 : "chttpclient deadline sweep: failed to initialize stripe mutex");
5281 : }
5282 33 : if (ccol_cond_var_init_monotonic(&client_deadline_bundle.cond_var) != 0)
5283 0 : ccol__fatal_err(
5284 : "chttpclient deadline sweep: failed to initialize condition "
5285 : "variable");
5286 33 : }
5287 :
5288 : // The longest the sweep sleeps between walks. It also paces the work that has
5289 : // no deadline of its own (flipping a stalled send, retrying a reap).
5290 : #define CHTTP_DEADLINE_SWEEP_INTERVAL_MS 100
5291 : // The most expired connections one tick shuts down; the rest wait for the next
5292 : // tick, which follows at once.
5293 : #define CHTTP_DEADLINE_SWEEP_BATCH 256
5294 :
5295 : // Adds ctx to the registry unless it's there. It takes only ctx's stripe lock,
5296 : // so a caller may hold an idle_lock.
5297 834 : static void client_deadline_register(chttp_async_ctx *ctx) {
5298 834 : ccol__call_once(client_deadline_bundle.once, client_deadline_init_globals);
5299 834 : chttp_deadline_stripe *stripe =
5300 834 : &client_deadline_bundle.stripes[deadline_stripe_index_for_ctx(ctx)];
5301 834 : ccol__mutex_lock(stripe->mutex);
5302 834 : if (!ctx->deadline_registered) {
5303 834 : ctx->deadline_prev = NULL;
5304 834 : ctx->deadline_next = stripe->head;
5305 834 : if (stripe->head) stripe->head->deadline_prev = ctx;
5306 834 : stripe->head = ctx;
5307 834 : ctx->deadline_registered = true;
5308 : }
5309 834 : ccol__mutex_unlock(stripe->mutex);
5310 834 : }
5311 :
5312 : // Converts t to nanoseconds, for the sweep's arithmetic.
5313 13440 : static uint64_t timespec_to_ns(const struct timespec *t) {
5314 13440 : if (t->tv_sec < 0) return 0;
5315 13440 : if ((uint64_t)t->tv_sec >= UINT64_MAX / 1000000000u) return UINT64_MAX - 1;
5316 13434 : return (uint64_t)t->tv_sec * 1000000000u + (uint64_t)t->tv_nsec;
5317 : }
5318 :
5319 : // Gives CLOCK_MONOTONIC now in nanoseconds, the clock of every deadline.
5320 11834 : static uint64_t monotonic_now_ns(void) {
5321 11834 : struct timespec now;
5322 11834 : clock_gettime(CLOCK_MONOTONIC, &now);
5323 11834 : return timespec_to_ns(&now);
5324 : }
5325 :
5326 : // Tells the sweep that it has work at at_ns: Lowers g_sweep_next_ns, and wakes
5327 : // the sleeping sweep to replan when that's earlier than g_sweep_planned_ns
5328 : // (never from the sweep thread itself). Every path that sets a deadline calls
5329 : // it; the common case costs one atomic load.
5330 1679 : static void client_deadline_note_ns(uint64_t at_ns) {
5331 1679 : uint64_t cur = atomic_load(&g_sweep_next_ns);
5332 1679 : while (at_ns < cur) {
5333 536 : if (atomic_compare_exchange_weak(&g_sweep_next_ns, &cur, at_ns)) {
5334 536 : if (t_on_sweep_thread) return;
5335 167 : if (at_ns >= atomic_load(&g_sweep_planned_ns)) return;
5336 7 : ccol__call_once(client_deadline_bundle.once,
5337 : client_deadline_init_globals);
5338 7 : ccol__mutex_lock(client_deadline_bundle.mutex);
5339 7 : ccol__cond_var_signal(client_deadline_bundle.cond_var);
5340 7 : ccol__mutex_unlock(client_deadline_bundle.mutex);
5341 7 : return;
5342 : }
5343 : }
5344 : }
5345 :
5346 : // Tells the sweep about deadline d when it's active (through
5347 : // client_deadline_note_ns), for the paths that set a chttp_deadline.
5348 1886 : static void client_deadline_note(const chttp_deadline *d) {
5349 2932 : if (d->active) client_deadline_note_ns(timespec_to_ns(&d->deadline));
5350 1886 : }
5351 :
5352 : // Removes ctx from the registry. It runs once, first thing in async_ctx_free;
5353 : // the stripe is a function of the address, so nothing remembers it.
5354 833 : static void client_deadline_unregister(chttp_async_ctx *ctx) {
5355 833 : ccol__call_once(client_deadline_bundle.once, client_deadline_init_globals);
5356 833 : chttp_deadline_stripe *stripe =
5357 833 : &client_deadline_bundle.stripes[deadline_stripe_index_for_ctx(ctx)];
5358 833 : ccol__mutex_lock(stripe->mutex);
5359 833 : if (ctx->deadline_registered) {
5360 827 : if (ctx->deadline_prev) {
5361 288 : ctx->deadline_prev->deadline_next = ctx->deadline_next;
5362 : } else {
5363 539 : stripe->head = ctx->deadline_next;
5364 : }
5365 827 : if (ctx->deadline_next)
5366 105 : ctx->deadline_next->deadline_prev = ctx->deadline_prev;
5367 827 : ctx->deadline_prev = ctx->deadline_next = NULL;
5368 827 : ctx->deadline_registered = false;
5369 : }
5370 833 : ccol__mutex_unlock(stripe->mutex);
5371 833 : }
5372 :
5373 : #ifdef RUNNING_UNIT_TESTS
5374 : // Test hooks for the race between the sweep's verdict and the idle-pool offer:
5375 : // a forced verdict for one ctx, a park at a given phase until released, and
5376 : // counters around the offer's critical section.
5377 : static _Atomic bool g_sweep_race_armed_for_tests = false;
5378 : static void *_Atomic g_sweep_race_forced_ctx_for_tests = NULL;
5379 : static _Atomic int g_sweep_race_parked_for_tests = 0;
5380 : static _Atomic int g_sweep_race_release_for_tests = 0;
5381 : static _Atomic unsigned g_offer_entered_for_tests = 0;
5382 : static _Atomic unsigned g_offer_done_for_tests = 0;
5383 :
5384 : // Gives the forced verdict for node once, when a test armed one, so the race
5385 : // test decides which ctx expires.
5386 301 : static bool sweep_race_take_forced_verdict_for_tests(void *node) {
5387 301 : if (!atomic_exchange(&g_sweep_race_armed_for_tests, false)) return false;
5388 1 : atomic_store(&g_sweep_race_forced_ctx_for_tests, node);
5389 1 : return true;
5390 : }
5391 :
5392 : // Parks the sweep at phase until a test releases it (bounded), so the test can
5393 : // run the offer path inside the sweep's window.
5394 2 : static void sweep_race_park_for_tests(int phase) {
5395 2 : atomic_store(&g_sweep_race_parked_for_tests, phase);
5396 2 : struct timespec ts = {0, 1000000};
5397 2 : for (int i = 0;
5398 305 : i < 10000 && atomic_load(&g_sweep_race_release_for_tests) < phase; i++)
5399 303 : nanosleep(&ts, NULL);
5400 2 : atomic_store(&g_sweep_race_parked_for_tests, 0);
5401 2 : }
5402 :
5403 : // Arm, query, release and disarm the sweep race hooks, and read the offer
5404 : // counters, for the tests of the sweep against the idle-pool offer.
5405 1 : void chttp__sweep_race_arm_for_tests(void) {
5406 1 : atomic_store(&g_sweep_race_forced_ctx_for_tests, NULL);
5407 1 : atomic_store(&g_sweep_race_release_for_tests, 0);
5408 1 : atomic_store(&g_sweep_race_parked_for_tests, 0);
5409 1 : atomic_store(&g_sweep_race_armed_for_tests, true);
5410 1 : }
5411 :
5412 98 : int chttp__sweep_race_parked_phase_for_tests(void) {
5413 98 : return atomic_load(&g_sweep_race_parked_for_tests);
5414 : }
5415 :
5416 1 : void chttp__sweep_race_release_for_tests(int phase) {
5417 1 : atomic_store(&g_sweep_race_release_for_tests, phase);
5418 1 : }
5419 :
5420 1 : void chttp__sweep_race_disarm_for_tests(void) {
5421 1 : atomic_store(&g_sweep_race_armed_for_tests, false);
5422 1 : atomic_store(&g_sweep_race_release_for_tests, 1000);
5423 1 : atomic_store(&g_sweep_race_forced_ctx_for_tests, NULL);
5424 1 : }
5425 :
5426 3 : unsigned chttp__offer_entered_count_for_tests(void) {
5427 3 : return atomic_load(&g_offer_entered_for_tests);
5428 : }
5429 :
5430 301 : unsigned chttp__offer_done_count_for_tests(void) {
5431 301 : return atomic_load(&g_offer_done_for_tests);
5432 : }
5433 :
5434 : // While armed, the next sweep tick that snapshots a ctx awaiting a "100
5435 : // Continue" parks right after its deadline_lock section until released (10 s at
5436 : // most). A release bumps a generation the arm only records, so a release can't
5437 : // be taken back by a later arm. The last counter counts stores of
5438 : // continue_deadline.
5439 : static _Atomic bool g_continue_sweep_armed_for_tests = false;
5440 : static _Atomic bool g_continue_sweep_parked_for_tests = false;
5441 : static _Atomic unsigned g_continue_sweep_release_gen_for_tests = 0;
5442 : static _Atomic unsigned g_continue_sweep_armed_gen_for_tests = 0;
5443 : static _Atomic unsigned g_continue_deadline_stores_for_tests = 0;
5444 :
5445 : // Parks the sweep after its deadline_lock section on an awaiting-continue ctx,
5446 : // until released (10 s at most), so a test can race the continue decision.
5447 87 : static void continue_sweep_park_for_tests(void) {
5448 87 : if (!atomic_exchange(&g_continue_sweep_armed_for_tests, false)) return;
5449 1 : unsigned armed_gen = atomic_load(&g_continue_sweep_armed_gen_for_tests);
5450 1 : atomic_store(&g_continue_sweep_parked_for_tests, true);
5451 1 : struct timespec ts = {0, 1000000};
5452 1 : for (int i = 0;
5453 1144 : i < 10000 &&
5454 1144 : atomic_load(&g_continue_sweep_release_gen_for_tests) == armed_gen;
5455 1143 : i++)
5456 1143 : nanosleep(&ts, NULL);
5457 1 : atomic_store(&g_continue_sweep_parked_for_tests, false);
5458 : }
5459 :
5460 : // Counts one store of continue_deadline, for the continue race test.
5461 24 : static void continue_deadline_stored_for_tests(void) {
5462 24 : atomic_fetch_add_explicit(&g_continue_deadline_stores_for_tests, 1,
5463 : memory_order_relaxed);
5464 : }
5465 :
5466 : // Arm, query and release the continue hook, and read the store count, for the
5467 : // continue race test.
5468 1 : void chttp__continue_sweep_arm_for_tests(void) {
5469 1 : atomic_store(&g_continue_sweep_armed_gen_for_tests,
5470 : atomic_load(&g_continue_sweep_release_gen_for_tests));
5471 1 : atomic_store(&g_continue_sweep_armed_for_tests, true);
5472 1 : }
5473 :
5474 96 : bool chttp__continue_sweep_parked_for_tests(void) {
5475 96 : return atomic_load(&g_continue_sweep_parked_for_tests);
5476 : }
5477 :
5478 3 : void chttp__continue_sweep_release_for_tests(void) {
5479 3 : atomic_store(&g_continue_sweep_armed_for_tests, false);
5480 3 : atomic_fetch_add(&g_continue_sweep_release_gen_for_tests, 1);
5481 3 : }
5482 :
5483 9 : unsigned chttp__continue_deadline_stores_for_tests(void) {
5484 9 : return atomic_load_explicit(&g_continue_deadline_stores_for_tests,
5485 : memory_order_relaxed);
5486 : }
5487 :
5488 : // While armed, the first sweep that meets a connecting ctx with no fd and no
5489 : // race waits (bounded by the clock) until the connect task registers its fd and
5490 : // then until the connect deadline passes, which puts the deadline between the
5491 : // task's check and the sweep's verdict.
5492 : static _Atomic bool g_sweep_fd_wait_armed_for_tests = false;
5493 : static _Atomic bool g_sweep_fd_wait_held_for_tests = false;
5494 :
5495 : // Holds the sweep on a connecting ctx with no fd until the connect registers
5496 : // its fd and the deadline passes, and records how it ended, so a test hits the
5497 : // connect that starts as the sweep judges it.
5498 826 : static void sweep_fd_wait_for_tests(chttp_async_ctx *node) {
5499 826 : atomic_fetch_add(&g_sweep_fd_wait_seen_for_tests, 1);
5500 826 : if (!atomic_load(&g_sweep_fd_wait_armed_for_tests)) {
5501 825 : atomic_fetch_add(&g_sweep_fd_wait_not_armed_for_tests, 1);
5502 825 : return;
5503 : }
5504 1 : int fd = node->fd;
5505 1 : chttp_async_state state = node->state;
5506 1 : bool raced = atomic_load(&node->race) != NULL;
5507 1 : if (fd >= 0 || state != CHTTP_ASYNC_CONNECTING || raced) {
5508 0 : if (fd >= 0) atomic_fetch_add(&g_sweep_fd_wait_had_fd_for_tests, 1);
5509 0 : if (state != CHTTP_ASYNC_CONNECTING)
5510 0 : atomic_fetch_add(&g_sweep_fd_wait_wrong_state_for_tests, 1);
5511 0 : if (raced) atomic_fetch_add(&g_sweep_fd_wait_had_race_for_tests, 1);
5512 0 : atomic_store(&g_sweep_fd_wait_last_fd_for_tests, fd);
5513 0 : atomic_store(&g_sweep_fd_wait_last_state_for_tests, (int)state);
5514 0 : return;
5515 : }
5516 1 : if (!atomic_exchange(&g_sweep_fd_wait_armed_for_tests, false)) return;
5517 1 : atomic_store(&g_sweep_fd_wait_pending_for_tests, false);
5518 1 : struct timespec ts = {0, 1000000};
5519 1 : uint64_t give_up = monotonic_now_ns() + 5000000000ull;
5520 3 : while (!atomic_load(&node->reg) && monotonic_now_ns() < give_up)
5521 2 : nanosleep(&ts, NULL);
5522 1 : if (!atomic_load(&node->reg)) {
5523 0 : atomic_store(&g_sweep_fd_wait_hold_end_for_tests, 1);
5524 0 : return;
5525 : }
5526 1 : give_up = monotonic_now_ns() + 10000000000ull;
5527 1871 : while (monotonic_now_ns() < give_up) {
5528 1871 : int ms;
5529 1871 : ccol__mutex_lock(node->deadline_lock);
5530 1871 : bool passed = !deadline_remaining_ms(&node->connect_deadline, &ms);
5531 1871 : ccol__mutex_unlock(node->deadline_lock);
5532 1871 : if (passed) break;
5533 1870 : nanosleep(&ts, NULL);
5534 : }
5535 1 : atomic_store(&g_sweep_fd_wait_hold_end_for_tests, 2);
5536 1 : atomic_store(&g_sweep_fd_wait_held_for_tests, true);
5537 : }
5538 :
5539 : // Arms the fd wait hook and resets its trace, for the test of a connect that
5540 : // starts as the sweep judges it.
5541 1 : void chttp__sweep_fd_wait_arm_for_tests(void) {
5542 1 : atomic_store(&g_sweep_fd_wait_seen_for_tests, 0);
5543 1 : atomic_store(&g_sweep_fd_wait_not_armed_for_tests, 0);
5544 1 : atomic_store(&g_sweep_fd_wait_had_fd_for_tests, 0);
5545 1 : atomic_store(&g_sweep_fd_wait_wrong_state_for_tests, 0);
5546 1 : atomic_store(&g_sweep_fd_wait_had_race_for_tests, 0);
5547 1 : atomic_store(&g_sweep_fd_wait_last_fd_for_tests, -2);
5548 1 : atomic_store(&g_sweep_fd_wait_last_state_for_tests, -1);
5549 1 : atomic_store(&g_sweep_fd_wait_lookup_end_for_tests, 0);
5550 1 : atomic_store(&g_sweep_fd_wait_hold_end_for_tests, 0);
5551 1 : atomic_store(&g_sweep_fd_wait_held_for_tests, false);
5552 1 : atomic_store(&g_sweep_fd_wait_pending_for_tests, true);
5553 1 : atomic_store(&g_sweep_fd_wait_armed_for_tests, true);
5554 1 : }
5555 :
5556 : // Tells whether the sweep held as described, and disarms the hook, so the test
5557 : // knows its scenario really happened.
5558 1 : bool chttp__sweep_fd_wait_held_for_tests(void) {
5559 1 : atomic_store(&g_sweep_fd_wait_armed_for_tests, false);
5560 1 : atomic_store(&g_sweep_fd_wait_pending_for_tests, false);
5561 1 : return atomic_load(&g_sweep_fd_wait_held_for_tests);
5562 : }
5563 :
5564 : // Writes the trace of the armed hold into buf, so a failing test can print why.
5565 1 : void chttp__sweep_fd_wait_trace_for_tests(char *buf, size_t size) {
5566 1 : if (!buf || size == 0) return;
5567 1 : snprintf(buf, size,
5568 : "ctxs seen %lu, not armed %lu, had an fd %lu, wrong state %lu, "
5569 : "had a race %lu, last turned away fd %d state %d, lookup wait "
5570 : "end %d (1 caught, 2 ran out, 3 not waited), hold end %d (0 not "
5571 : "entered or still waiting, 1 no fd registered within 5 s, 2 "
5572 : "held)",
5573 1 : atomic_load(&g_sweep_fd_wait_seen_for_tests),
5574 1 : atomic_load(&g_sweep_fd_wait_not_armed_for_tests),
5575 1 : atomic_load(&g_sweep_fd_wait_had_fd_for_tests),
5576 1 : atomic_load(&g_sweep_fd_wait_wrong_state_for_tests),
5577 1 : atomic_load(&g_sweep_fd_wait_had_race_for_tests),
5578 1 : atomic_load(&g_sweep_fd_wait_last_fd_for_tests),
5579 1 : atomic_load(&g_sweep_fd_wait_last_state_for_tests),
5580 1 : atomic_load(&g_sweep_fd_wait_lookup_end_for_tests),
5581 1 : atomic_load(&g_sweep_fd_wait_hold_end_for_tests));
5582 : }
5583 :
5584 : // Gives g_async_hops_abandoned, so a test can check that abandoned hops are
5585 : // counted and released.
5586 3 : size_t chttp__async_hops_abandoned_for_tests(void) {
5587 3 : return atomic_load(&g_async_hops_abandoned);
5588 : }
5589 : #endif
5590 :
5591 : static uint64_t async_race_tick(chttp_connect_race *r, bool expired);
5592 :
5593 : static void async_chain_retain(chttp_async_chain *chain);
5594 : static void async_chain_release(chttp_async_chain *chain);
5595 : static void async_fulfill_chain(chttp_async_chain *chain, ccol_retval rv,
5596 : chttpcli_response *resp);
5597 :
5598 : // Gives the earlier of next_ns and d's instant when d is active and still
5599 : // ahead, so a walk can find the sweep's next wake.
5600 871 : static uint64_t sweep_earlier(uint64_t next_ns, const chttp_deadline *d,
5601 : bool remaining) {
5602 36 : if (!remaining || !d->active) return next_ns;
5603 480 : uint64_t at = timespec_to_ns(&d->deadline);
5604 480 : return at < next_ns ? at : next_ns;
5605 : }
5606 :
5607 : // Runs one sweep pass. It walks the stripes one at a time, holding only that
5608 : // stripe's lock. For each ctx it snapshots state and chain, judges the connect,
5609 : // request, 100-continue and inactivity deadlines and marks timed_out, all under
5610 : // the ctx's deadline_lock, so the verdict is one step against the idle pool's
5611 : // offer and take. An expired connection gets its fd shut down (timed_out first,
5612 : // so the teardown reports a timeout and repeated ticks are harmless). A hop
5613 : // with no fd before its connect, or one marked earlier that never got its
5614 : // dispatch, is answered with ccol_timed_out after the stripes are unlocked. The
5615 : // pass also starts Happy Eyeballs attempts, flips stalled duplex sends, retries
5616 : // an abandoned reap, and lowers g_sweep_next_ns to the next work.
5617 606 : static void client_deadline_sweep_once(void) {
5618 606 : ccol__call_once(client_deadline_bundle.once, client_deadline_init_globals);
5619 : #ifdef RUNNING_UNIT_TESTS
5620 606 : atomic_fetch_add(&g_sweep_ticks_for_tests, 1);
5621 : #endif
5622 606 : size_t n_shutdown = 0;
5623 606 : uint64_t next_ns = UINT64_MAX;
5624 606 : chttp_async_chain *abandoned[CHTTP_DEADLINE_SWEEP_BATCH];
5625 606 : size_t n_abandoned = 0;
5626 :
5627 606 : for (size_t s = 0; s < CHTTP_DEADLINE_SWEEP_STRIPES &&
5628 10302 : n_shutdown < CHTTP_DEADLINE_SWEEP_BATCH;
5629 9696 : s++) {
5630 9696 : chttp_deadline_stripe *stripe = &client_deadline_bundle.stripes[s];
5631 9696 : ccol__mutex_lock(stripe->mutex);
5632 9696 : chttp_async_ctx *node = stripe->head;
5633 10522 : while (node && n_shutdown < CHTTP_DEADLINE_SWEEP_BATCH) {
5634 826 : chttp_async_ctx *next = node->deadline_next;
5635 : #ifdef RUNNING_UNIT_TESTS
5636 826 : sweep_fd_wait_for_tests(node);
5637 : #endif
5638 :
5639 826 : bool expired = false;
5640 826 : ccol__mutex_lock(node->deadline_lock);
5641 826 : chttp_async_state state = node->state;
5642 826 : chttp_deadline continue_dl = node->continue_deadline;
5643 826 : chttp_async_chain *chain_snap = node->chain;
5644 826 : bool has_chain = (chain_snap != NULL);
5645 826 : if (node->timed_out) {
5646 103 : if (has_chain && n_abandoned < CHTTP_DEADLINE_SWEEP_BATCH &&
5647 103 : !atomic_exchange(&node->abandoned, true)) {
5648 3 : atomic_fetch_add(&g_async_hops_abandoned, 1);
5649 6 : async_chain_retain(chain_snap);
5650 3 : abandoned[n_abandoned++] = chain_snap;
5651 3 : n_shutdown++;
5652 : }
5653 : } else {
5654 723 : int ms;
5655 723 : if (state == CHTTP_ASYNC_CONNECTING ||
5656 : state == CHTTP_ASYNC_TLS_HANDSHAKING) {
5657 210 : bool left = deadline_remaining_ms(&node->connect_deadline, &ms);
5658 210 : if (!left) {
5659 5 : expired = true;
5660 : #ifdef RUNNING_UNIT_TESTS
5661 10 : sweep_note_due_for_tests(
5662 5 : 0, timespec_to_ns(&node->connect_deadline.deadline));
5663 : #endif
5664 : }
5665 210 : next_ns = sweep_earlier(next_ns, &node->connect_deadline, left);
5666 : }
5667 723 : if (!expired && has_chain) {
5668 622 : bool left = deadline_remaining_ms(&node->overall_deadline, &ms);
5669 622 : if (!left) {
5670 19 : expired = true;
5671 : #ifdef RUNNING_UNIT_TESTS
5672 38 : sweep_note_due_for_tests(
5673 19 : 0, timespec_to_ns(&node->overall_deadline.deadline));
5674 : #endif
5675 : }
5676 622 : next_ns = sweep_earlier(next_ns, &node->overall_deadline, left);
5677 : }
5678 723 : if (!expired && has_chain && node->inactivity_us != 0 &&
5679 : (state == CHTTP_ASYNC_WRITING ||
5680 589 : state == CHTTP_ASYNC_AWAITING_CONTINUE ||
5681 390 : state == CHTTP_ASYNC_READING) &&
5682 390 : !atomic_load(&chain_snap->in_sink)) {
5683 352 : uint64_t now_ns = monotonic_now_ns();
5684 352 : uint64_t last = atomic_load(&node->last_io_ns);
5685 352 : uint64_t sink = atomic_load(&chain_snap->sink_returned_ns);
5686 352 : if (sink > last) last = sink;
5687 327 : if (last == 0) {
5688 1 : atomic_store(&node->last_io_ns, now_ns);
5689 1 : last = now_ns;
5690 : }
5691 704 : uint64_t budget_ns = node->inactivity_us > UINT64_MAX / 1000
5692 : ? UINT64_MAX
5693 352 : : node->inactivity_us * 1000;
5694 704 : uint64_t due =
5695 352 : last > UINT64_MAX - budget_ns ? UINT64_MAX : last + budget_ns;
5696 352 : if (now_ns >= due) {
5697 4 : expired = true;
5698 : #ifdef RUNNING_UNIT_TESTS
5699 4 : sweep_note_due_for_tests(0, due);
5700 : #endif
5701 348 : } else if (due < next_ns) {
5702 : next_ns = due;
5703 : }
5704 : }
5705 723 : if (!expired && state == CHTTP_ASYNC_AWAITING_CONTINUE &&
5706 87 : !atomic_load(&node->continue_decided) &&
5707 87 : !atomic_load(&node->continue_msg_started))
5708 39 : next_ns = sweep_earlier(next_ns, &continue_dl,
5709 39 : deadline_remaining_ms(&continue_dl, &ms));
5710 : #ifdef RUNNING_UNIT_TESTS
5711 1024 : bool forced = !expired && has_chain && state == CHTTP_ASYNC_READING &&
5712 301 : sweep_race_take_forced_verdict_for_tests(node);
5713 723 : if (forced) {
5714 1 : expired = true;
5715 1 : sweep_race_park_for_tests(1);
5716 : }
5717 : #endif
5718 723 : if (expired) node->timed_out = true;
5719 : }
5720 826 : ccol__mutex_unlock(node->deadline_lock);
5721 826 : int fd = node->fd;
5722 : #ifdef RUNNING_UNIT_TESTS
5723 826 : if (state == CHTTP_ASYNC_AWAITING_CONTINUE)
5724 87 : continue_sweep_park_for_tests();
5725 : #endif
5726 :
5727 87 : chttp_connect_race *race =
5728 739 : (state == CHTTP_ASYNC_CONNECTING) ? atomic_load(&node->race) : NULL;
5729 826 : if (expired && fd < 0 && !race && has_chain &&
5730 6 : state == CHTTP_ASYNC_CONNECTING &&
5731 6 : n_abandoned < CHTTP_DEADLINE_SWEEP_BATCH &&
5732 6 : !atomic_exchange(&node->abandoned, true)) {
5733 6 : atomic_fetch_add(&g_async_hops_abandoned, 1);
5734 12 : async_chain_retain(chain_snap);
5735 6 : abandoned[n_abandoned++] = chain_snap;
5736 : }
5737 826 : if (expired) {
5738 : #ifdef RUNNING_UNIT_TESTS
5739 29 : if (atomic_load(&g_sweep_race_forced_ctx_for_tests) == node)
5740 1 : sweep_race_park_for_tests(2);
5741 : #endif
5742 29 : if (fd >= 0) shutdown(fd, SHUT_RDWR);
5743 29 : if (race) (void)async_race_tick(race, true);
5744 29 : n_shutdown++;
5745 797 : } else if (race) {
5746 38 : uint64_t start_ns = async_race_tick(race, false);
5747 38 : if (start_ns < next_ns) next_ns = start_ns;
5748 767 : } else if (fd >= 0 && atomic_load(&node->flip_watch) != CHTTP_FLIP_NONE) {
5749 8 : unsigned char watch = atomic_load(&node->flip_watch);
5750 8 : bool on_input = (watch == CHTTP_FLIP_ON_INPUT);
5751 8 : struct pollfd p = {
5752 : .fd = fd, .events = on_input ? POLLIN : POLLOUT, .revents = 0};
5753 8 : if (poll(&p, 1, 0) > 0 && (p.revents & p.events) != 0) {
5754 2 : ceventloop_reg reg = atomic_load(&node->reg);
5755 2 : if (reg && atomic_load(&node->flip_watch) == watch)
5756 2 : ceventloop_modify(cli_engine_bundler.reactor, reg,
5757 2 : on_input ? cselect_read : cselect_write);
5758 : }
5759 751 : } else if (state == CHTTP_ASYNC_AWAITING_CONTINUE) {
5760 87 : int cms;
5761 87 : if (!deadline_remaining_ms(&continue_dl, &cms) &&
5762 16 : !atomic_load(&node->continue_decided) &&
5763 16 : !atomic_load(&node->continue_msg_started)) {
5764 4 : ceventloop_reg reg = atomic_load(&node->reg);
5765 4 : if (reg && node->state == CHTTP_ASYNC_AWAITING_CONTINUE &&
5766 4 : !atomic_load(&node->continue_decided)) {
5767 4 : ceventloop_modify(cli_engine_bundler.reactor, reg, cselect_write);
5768 : }
5769 : }
5770 : }
5771 826 : node = next;
5772 : }
5773 9696 : ccol__mutex_unlock(stripe->mutex);
5774 : }
5775 606 : if (n_shutdown >= CHTTP_DEADLINE_SWEEP_BATCH) next_ns = 0;
5776 606 : client_deadline_note_ns(next_ns);
5777 :
5778 615 : for (size_t i = 0; i < n_abandoned; i++) {
5779 9 : if (abandoned[i]->write_fn) async_sink_close(abandoned[i]);
5780 9 : async_fulfill_chain(abandoned[i], ccol_timed_out, NULL);
5781 9 : async_chain_release(abandoned[i]);
5782 : }
5783 :
5784 606 : if (n_shutdown > 0) {
5785 29 : CLIENT_ENGINE_LOG_INFO("deadline sweep shut down %zu connection(s)",
5786 : n_shutdown);
5787 : }
5788 606 : }
5789 :
5790 : // Runs the sweep thread: It sleeps until g_sweep_next_ns, and at most the
5791 : // interval after the end of its previous walk. A wake for an earlier deadline
5792 : // only replans; the walk runs once the planned instant has come, so requests
5793 : // that start in a row don't cost a walk each.
5794 419 : static void *client_deadline_sweep_fn(void *arg) {
5795 419 : (void)arg;
5796 419 : t_on_sweep_thread = true;
5797 419 : ccol__call_once(client_deadline_bundle.once, client_deadline_init_globals);
5798 419 : const uint64_t interval_ns =
5799 : (uint64_t)CHTTP_DEADLINE_SWEEP_INTERVAL_MS * 1000000u;
5800 419 : uint64_t last_walk_ns = monotonic_now_ns();
5801 419 : ccol__mutex_lock(client_deadline_bundle.mutex);
5802 2043 : while (!client_deadline_bundle.stop) {
5803 1634 : uint64_t now_ns = monotonic_now_ns();
5804 1634 : uint64_t wake_ns = last_walk_ns + interval_ns;
5805 1634 : for (;;) {
5806 1634 : uint64_t next_ns = atomic_load(&g_sweep_next_ns);
5807 1634 : uint64_t plan_ns = next_ns < wake_ns ? next_ns : wake_ns;
5808 1634 : atomic_store(&g_sweep_planned_ns, plan_ns > 0 ? plan_ns : 1);
5809 1634 : if (atomic_load(&g_sweep_next_ns) == next_ns) {
5810 1634 : wake_ns = plan_ns;
5811 1634 : break;
5812 : }
5813 : }
5814 1634 : if (wake_ns > now_ns) {
5815 1028 : struct timespec wake = {.tv_sec = (time_t)(wake_ns / 1000000000u),
5816 1028 : .tv_nsec = (long)(wake_ns % 1000000000u)};
5817 1028 : ccol__cond_var_timedwait(client_deadline_bundle.cond_var,
5818 : client_deadline_bundle.mutex, wake);
5819 1018 : continue;
5820 : }
5821 606 : atomic_store(&g_sweep_planned_ns, 0);
5822 606 : ccol__mutex_unlock(client_deadline_bundle.mutex);
5823 606 : atomic_store(&g_sweep_next_ns, UINT64_MAX);
5824 : #ifdef RUNNING_UNIT_TESTS
5825 606 : g_sweep_walk_plan_ns_for_tests = wake_ns;
5826 : #endif
5827 606 : client_deadline_sweep_once();
5828 606 : client_engine_retry_abandoned_reap();
5829 606 : last_walk_ns = monotonic_now_ns();
5830 606 : ccol__mutex_lock(client_deadline_bundle.mutex);
5831 : }
5832 409 : atomic_store(&g_sweep_planned_ns, 0);
5833 409 : ccol__mutex_unlock(client_deadline_bundle.mutex);
5834 409 : return NULL;
5835 : }
5836 :
5837 : // Starts the sweep thread, from the first engine acquire. Gives
5838 : // ccol_unexpected_failure when the thread can't start.
5839 419 : static ccol_retval client_deadline_sweep_start(void) {
5840 419 : client_deadline_bundle.stop = false;
5841 419 : int rc = ccol__thread_create(client_deadline_bundle.thread,
5842 : client_deadline_sweep_fn, NULL);
5843 419 : return (rc == 0) ? ccol_success : ccol_unexpected_failure;
5844 : }
5845 :
5846 : // Stops the sweep thread and joins it, from the reaper, before the reactor and
5847 : // the DNS pool go away.
5848 409 : static void client_deadline_sweep_stop_and_join(void) {
5849 409 : ccol__call_once(client_deadline_bundle.once, client_deadline_init_globals);
5850 409 : ccol__mutex_lock(client_deadline_bundle.mutex);
5851 409 : client_deadline_bundle.stop = true;
5852 409 : ccol__cond_var_broadcast(client_deadline_bundle.cond_var);
5853 409 : ccol__mutex_unlock(client_deadline_bundle.mutex);
5854 409 : ccol__thread_join(client_deadline_bundle.thread);
5855 409 : }
5856 :
5857 : #if CCOL_FORK_SAFETY_REQUIRED
5858 :
5859 : // Fork safety
5860 : //
5861 : // Takes every lock of this module before fork(): It waits for a stopping engine
5862 : // and joins its reaper (which keeps running after it clears stopping and may
5863 : // hold an allocator lock), then takes the engine mutex, the sweep mutex and
5864 : // every stripe lock, so no lock of this module is held by a thread the child
5865 : // doesn't inherit.
5866 219 : static void chttpcli_atfork_prepare(void) {
5867 : #ifdef RUNNING_UNIT_TESTS
5868 219 : ccol__atfork_order_record(ccol__atfork_module_chttpclient);
5869 : #endif
5870 219 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
5871 219 : ccol__call_once(client_deadline_bundle.once, client_deadline_init_globals);
5872 219 : ccol__mutex_lock(cli_engine_bundler.mutex);
5873 219 : if (atomic_load(&g_client_engine_pid) == getpid()) {
5874 219 : while (cli_engine_bundler.stopping)
5875 0 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
5876 : cli_engine_bundler.mutex);
5877 219 : client_engine_join_reaper_if_needed_locked();
5878 : }
5879 219 : ccol__mutex_lock(client_deadline_bundle.mutex);
5880 3723 : for (size_t i = 0; i < CHTTP_DEADLINE_SWEEP_STRIPES; i++)
5881 3504 : ccol__mutex_lock(client_deadline_bundle.stripes[i].mutex);
5882 219 : }
5883 :
5884 : // Releases every lock the prepare handler took, in reverse order, for both the
5885 : // parent and the child handler.
5886 219 : static void chttpcli_atfork_unlock_all(void) {
5887 3723 : for (size_t i = CHTTP_DEADLINE_SWEEP_STRIPES; i-- > 0;)
5888 3504 : ccol__mutex_unlock(client_deadline_bundle.stripes[i].mutex);
5889 219 : ccol__mutex_unlock(client_deadline_bundle.mutex);
5890 219 : ccol__mutex_unlock(cli_engine_bundler.mutex);
5891 219 : }
5892 :
5893 : // Releases every lock of this module in the parent after fork().
5894 219 : static void chttpcli_atfork_parent(void) { chttpcli_atfork_unlock_all(); }
5895 :
5896 : // Forgets the inherited engine in the child after fork(), then unlocks every
5897 : // lock; the forking thread holds every lock in the child too, so a plain unlock
5898 : // is right.
5899 0 : static void chttpcli_atfork_child(void) {
5900 0 : client_engine_forget_inherited_locked();
5901 0 : chttpcli_atfork_unlock_all();
5902 0 : }
5903 : #endif
5904 :
5905 : // Deep-copies a header map (char * -> char *) for a redirect chain, through the
5906 : // insertion-order cursor, which can't fail. Gives NULL for no memory and also
5907 : // for a NULL src; *oom tells the two apart.
5908 47 : static chmap clone_headers_map(ccol_memmgmt_procs *mp, chmap src) {
5909 47 : char *err = NULL;
5910 47 : chmap dst =
5911 47 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_string,
5912 : ccol_string, mp, NULL, NULL, &err);
5913 47 : if (!dst) return NULL;
5914 157 : for (const ccol_chmap_entry_ref *e = ccol_chmap_oldest_entry(src); e;) {
5915 110 : const cmap_pair *k, *v;
5916 110 : e = ccol_chmap_entry_read(e, &k, &v);
5917 110 : if (chashmap_insert_elem(dst, k, v) != ccol_success) {
5918 0 : chashmap__destroy(dst);
5919 0 : return NULL;
5920 : }
5921 : }
5922 : return dst;
5923 : }
5924 :
5925 : // Allocates the shared state of a redirect chain for chttp_do_async_internal
5926 : // and counts it in cli's async in-flight total, so destroy waits for it. On
5927 : // success it owns tls_ctx; on failure tls_ctx stays with the caller. Headers,
5928 : // body and content type are deep-copied, so the caller can free its request at
5929 : // once.
5930 920 : static chttp_async_chain *async_chain_create(
5931 : ccol_memmgmt_procs *mp, struct chttpclient *cli, cthrpool_future *future,
5932 : chmap req_headers, const void *body_data, size_t body_len,
5933 : const char *body_content_type, const char *initial_origin_key,
5934 : ctls_ctx *tls_ctx, bool tls_ctx_usable, bool verify_host,
5935 : uint64_t tls_generation, uint64_t connect_timeout_us,
5936 : uint64_t request_timeout_us, size_t max_response_body_size,
5937 : chttpcli_write_fn write_fn, void *write_ctx, bool expect_continue,
5938 : bool prevent_tls_downgrade_on_redirect) {
5939 920 : chttp_async_chain *chain =
5940 920 : (chttp_async_chain *)ccol__mem_calloc(mp, 1, sizeof(*chain));
5941 920 : if (!chain) return NULL;
5942 915 : if (ccol__mutex_init(chain->lock) != 0) {
5943 0 : ccol__mem_free(mp, chain);
5944 0 : return NULL;
5945 : }
5946 915 : chain->mp = mp;
5947 915 : chain->cli = cli;
5948 915 : chain->future = future;
5949 915 : chain->tls_ctx = tls_ctx;
5950 915 : chain->tls_ctx_usable = tls_ctx_usable;
5951 915 : chain->verify_host = verify_host;
5952 915 : chain->tls_generation = tls_generation;
5953 915 : chain->connect_timeout_us = connect_timeout_us;
5954 915 : chain->overall_deadline = deadline_make(request_timeout_us);
5955 915 : chain->max_response_body_size = max_response_body_size;
5956 915 : chain->write_fn = write_fn;
5957 915 : chain->write_ctx = write_ctx;
5958 915 : chain->expect_continue = expect_continue;
5959 915 : chain->prevent_tls_downgrade_on_redirect = prevent_tls_downgrade_on_redirect;
5960 :
5961 915 : if (req_headers) {
5962 47 : chain->req_headers = clone_headers_map(mp, req_headers);
5963 47 : if (!chain->req_headers) goto fail;
5964 : }
5965 915 : if (body_data && body_len > 0) {
5966 64 : chain->body_data = ccol__mem_alloc(mp, body_len);
5967 64 : if (!chain->body_data) goto fail;
5968 64 : memcpy(chain->body_data, body_data, body_len);
5969 64 : chain->body_len = body_len;
5970 : }
5971 915 : if (body_content_type) {
5972 64 : chain->body_content_type = ccol_strdup(mp, body_content_type);
5973 64 : if (!chain->body_content_type) goto fail;
5974 : }
5975 915 : if (initial_origin_key) {
5976 915 : chain->initial_origin_key = ccol_strdup(mp, initial_origin_key);
5977 915 : if (!chain->initial_origin_key) goto fail;
5978 : }
5979 :
5980 912 : ccol__mutex_lock(cli->async_count_lock);
5981 912 : cli->async_in_flight_count++;
5982 912 : ccol__mutex_unlock(cli->async_count_lock);
5983 :
5984 912 : return chain;
5985 :
5986 3 : fail:
5987 3 : if (chain->req_headers) chashmap__destroy(chain->req_headers);
5988 3 : ccol__mem_free(mp, chain->body_data);
5989 3 : ccol__mem_free(mp, chain->body_content_type);
5990 3 : ccol__mem_free(mp, chain->initial_origin_key);
5991 3 : ccol__mutex_destroy(chain->lock);
5992 3 : ccol__mem_free(mp, chain);
5993 : return NULL;
5994 : }
5995 :
5996 : // Allocates size bytes plus, for a non-NULL mp, a copy of the procs right after
5997 : // them, pointed to by *procs_slot. A response or a result may be freed after
5998 : // its client is gone, so it carries its own allocator.
5999 2205 : static void *alloc_with_procs_copy(ccol_memmgmt_procs *mp, size_t size,
6000 : ccol_memmgmt_procs **copy_out) {
6001 2205 : size_t off = (size + _Alignof(ccol_memmgmt_procs) - 1) &
6002 : ~(size_t)(_Alignof(ccol_memmgmt_procs) - 1);
6003 2205 : char *block = (char *)ccol__mem_calloc(
6004 : mp, 1, mp ? off + sizeof(ccol_memmgmt_procs) : size);
6005 2204 : if (!block) return NULL;
6006 2198 : *copy_out = NULL;
6007 2198 : if (mp) {
6008 270 : ccol_memmgmt_procs *copy = (ccol_memmgmt_procs *)(block + off);
6009 270 : *copy = *mp;
6010 270 : *copy_out = copy;
6011 : }
6012 : return block;
6013 : }
6014 :
6015 : // Allocate a response and an async result with their own procs copy, since both
6016 : // may be freed after their client is destroyed.
6017 1282 : static chttpcli_response *resp_alloc(ccol_memmgmt_procs *mp) {
6018 1282 : ccol_memmgmt_procs *copy;
6019 2564 : chttpcli_response *resp = (chttpcli_response *)alloc_with_procs_copy(
6020 : mp, sizeof(chttpcli_response), ©);
6021 1282 : if (resp) resp->ccol__m_procs = copy;
6022 1282 : return resp;
6023 : }
6024 :
6025 923 : static chttpcli_async_result *async_result_alloc(ccol_memmgmt_procs *mp) {
6026 923 : ccol_memmgmt_procs *copy;
6027 923 : chttpcli_async_result *result =
6028 1846 : (chttpcli_async_result *)alloc_with_procs_copy(
6029 : mp, sizeof(chttpcli_async_result), ©);
6030 923 : if (result) result->ccol__m_procs = copy;
6031 923 : return result;
6032 : }
6033 :
6034 : static void async_fulfill_chain(chttp_async_chain *chain, ccol_retval rv,
6035 : chttpcli_response *resp);
6036 :
6037 : // Adds one hop reference to a live chain, for a redirect hand-off or a retry.
6038 : // Pairs with async_chain_release.
6039 1958 : static void async_chain_retain(chttp_async_chain *chain) {
6040 9 : ccol__mutex_lock(chain->lock);
6041 1957 : chain->refcount++;
6042 1957 : ccol__mutex_unlock(chain->lock);
6043 : }
6044 :
6045 : // Drops one hop reference. The last one is the one reliable place to end the
6046 : // request: It fulfils the future as a backstop (a no-op when a hop already
6047 : // did), takes the chain off cli's async count under async_count_lock and wakes
6048 : // a waiting destroy, frees the chain and drops its engine reference.
6049 1951 : static void async_chain_release(chttp_async_chain *chain) {
6050 1951 : if (!chain) return;
6051 1951 : ccol__mutex_lock(chain->lock);
6052 1951 : int remaining = --chain->refcount;
6053 1951 : ccol__mutex_unlock(chain->lock);
6054 1951 : if (remaining > 0) return;
6055 :
6056 905 : struct chttpclient *cli = chain->cli;
6057 :
6058 905 : async_fulfill_chain(chain, ccol_http_transfer_aborted, NULL);
6059 905 : if (chain->tls_ctx) ctls_ctx_release(chain->tls_ctx);
6060 905 : if (chain->req_headers) chashmap__destroy(chain->req_headers);
6061 905 : ccol__mem_free(chain->mp, chain->body_data);
6062 905 : ccol__mem_free(chain->mp, chain->body_content_type);
6063 905 : ccol__mem_free(chain->mp, chain->carried_auth);
6064 905 : ccol__mem_free(chain->mp, chain->carried_auth_origin);
6065 905 : ccol__mem_free(chain->mp, chain->initial_origin_key);
6066 905 : ccol__mutex_destroy(chain->lock);
6067 905 : ccol__mem_free(chain->mp, chain);
6068 905 : client_engine_release_chain();
6069 :
6070 905 : ccol__mutex_lock(cli->async_count_lock);
6071 905 : if (cli->async_in_flight_count > 0) cli->async_in_flight_count--;
6072 905 : if (cli->async_in_flight_count == 0)
6073 584 : ccol__cond_var_broadcast(cli->async_count_drained);
6074 905 : ccol__mutex_unlock(cli->async_count_lock);
6075 : }
6076 :
6077 : // Allocates a ctx with its locks, fd -1 and no registration, for a fresh hop or
6078 : // a retry. Gives NULL on failure.
6079 841 : static chttp_async_ctx *async_ctx_create(ccol_memmgmt_procs *mp) {
6080 841 : chttp_async_ctx *ctx =
6081 841 : (chttp_async_ctx *)ccol__mem_calloc(mp, 1, sizeof(*ctx));
6082 841 : if (!ctx) return NULL;
6083 840 : ctx->mp = mp;
6084 840 : ctx->fd = -1;
6085 840 : if (ccol__mutex_init(ctx->idle_lock) != 0) {
6086 0 : ccol__mem_free(mp, ctx);
6087 0 : return NULL;
6088 : }
6089 840 : if (ccol__mutex_init(ctx->deadline_lock) != 0) {
6090 0 : ccol__mutex_destroy(ctx->idle_lock);
6091 0 : ccol__mem_free(mp, ctx);
6092 0 : return NULL;
6093 : }
6094 : return ctx;
6095 : }
6096 :
6097 : // Gets ctx->parser ready for the next response, releasing the line spill of an
6098 : // earlier one.
6099 1319 : static void async_parser_start(chttp_async_ctx *ctx) {
6100 1319 : ccol__call_once(client_http1_settings_bundler.once, init_chttp1_settings);
6101 1319 : chttp1_parser_release(&ctx->parser);
6102 1319 : chttp1_parser_init(&ctx->parser, &client_http1_settings_bundler.settings);
6103 1319 : ctx->parser.data = &ctx->pctx;
6104 1319 : (void)chttp1_parser_enable_line_spill(&ctx->parser, ctx->mp);
6105 1318 : }
6106 :
6107 : static void async_race_detach(chttp_async_ctx *ctx);
6108 : static ccol_retval async_reg_modify(chttp_async_ctx *ctx, cselect_dir dir);
6109 : static void async_ctx_handle_if_abandoned(chttp_async_ctx *ctx);
6110 : static inline bool async_upload_may_resume(const chttp_async_ctx *ctx);
6111 : static void async_upload_resume(chttp_async_ctx *ctx);
6112 :
6113 : // Releases everything a ctx holds and frees it. It leaves the deadline registry
6114 : // first, strictly before the close(), since the sweep shuts fds down and would
6115 : // otherwise hit a reused fd number. The registration is removed before the
6116 : // close too. A short lock of idle_lock first makes sure async_connect_task's
6117 : // window after ceventloop_add is over.
6118 833 : static void async_ctx_destroy_now(chttp_async_ctx *ctx) {
6119 833 : ccol__mutex_lock(ctx->idle_lock);
6120 833 : ccol__mutex_unlock(ctx->idle_lock);
6121 833 : client_deadline_unregister(ctx);
6122 833 : if (atomic_load(&ctx->abandoned))
6123 8 : atomic_fetch_sub(&g_async_hops_abandoned, 1);
6124 833 : async_race_detach(ctx);
6125 833 : if (ctx->reg) ceventloop_remove(cli_engine_bundler.reactor, ctx->reg);
6126 833 : ceventloop_reg room = atomic_exchange(&ctx->room_reg, CEVENTLOOP_REG_NULL);
6127 833 : if (room) ceventloop_remove(cli_engine_bundler.reactor, room);
6128 833 : if (ctx->tls) ctls_conn_destroy(ctx->tls);
6129 833 : if (ctx->fd >= 0) close(ctx->fd);
6130 832 : chttp1_parser_release(&ctx->parser);
6131 833 : ccol__mutex_destroy(ctx->idle_lock);
6132 833 : ccol__mutex_destroy(ctx->deadline_lock);
6133 833 : ccol__mem_free(ctx->mp, ctx->wire);
6134 832 : ccol__mem_free(ctx->mp, ctx->continue_carry);
6135 831 : ccol__mem_free(ctx->mp, ctx->unix_socket_path);
6136 831 : ccol__mem_free(ctx->mp, ctx->host);
6137 833 : ccol__mem_free(ctx->mp, ctx->addrs);
6138 833 : ccol__mem_free(ctx->mp, ctx->path_and_query);
6139 833 : ccol__mem_free(ctx->mp, ctx->origin_key);
6140 833 : parse_ctx_free_fields(&ctx->pctx);
6141 833 : ccol__mem_free(ctx->mp, ctx->bb.buf);
6142 833 : ccol__mem_free(ctx->mp, ctx);
6143 833 : }
6144 :
6145 : // Frees a ctx; it's the one place that does. No application thread ever frees a
6146 : // registered ctx, so this runs either for a ctx that was never registered or
6147 : // inside a dispatch.
6148 833 : static void async_ctx_free(chttp_async_ctx *ctx) {
6149 833 : if (!ctx) return;
6150 484 : async_ctx_destroy_now(ctx);
6151 : }
6152 :
6153 : // Frees a hop's ctx and drops its chain reference. Every terminal path of a ctx
6154 : // ends here, so the pair can't get out of step.
6155 483 : static void async_ctx_teardown(chttp_async_ctx *ctx) {
6156 483 : chttp_async_chain *chain = ctx->chain;
6157 483 : async_ctx_free(ctx);
6158 483 : async_chain_release(chain);
6159 483 : }
6160 :
6161 : // Hands the terminal result to the future exactly once. Every exit path of a
6162 : // request may call it; chain->fulfilled under chain->lock decides, since two
6163 : // hops' callbacks can run at once. It also settles g_async_requests_pending
6164 : // before the future becomes ready.
6165 1808 : static void async_fulfill_chain(chttp_async_chain *chain, ccol_retval rv,
6166 : chttpcli_response *resp) {
6167 1808 : ccol__mutex_lock(chain->lock);
6168 1808 : bool already = chain->fulfilled;
6169 1808 : chain->fulfilled = true;
6170 1808 : chttpcli_async_result *result = chain->result;
6171 1808 : chain->result = NULL;
6172 1808 : ccol__mutex_unlock(chain->lock);
6173 1808 : if (already) {
6174 902 : chttpcli_resp_free(resp);
6175 902 : return;
6176 : }
6177 906 : client_async_request_settled();
6178 906 : result->rv = rv;
6179 906 : result->resp = resp;
6180 906 : cthrpool_future_fulfill(chain->future, result);
6181 : }
6182 :
6183 : // Marks the hop completed, so a later dispatch does nothing, and fulfils its
6184 : // chain with rv and resp.
6185 76 : static void async_fulfill(chttp_async_ctx *ctx, ccol_retval rv,
6186 : chttpcli_response *resp) {
6187 76 : ctx->hop_completed = true;
6188 76 : async_fulfill_chain(ctx->chain, rv, resp);
6189 76 : }
6190 :
6191 : // Builds the response from the finished parse. The header map, field lines and
6192 : // body move out of ctx, so call it before the idle-pool offer resets ctx.
6193 780 : static chttpcli_response *async_build_response(chttp_async_ctx *ctx) {
6194 780 : chttpcli_response *resp = resp_alloc(ctx->mp);
6195 2 : if (!resp) return NULL;
6196 778 : resp->status_code = ctx->pctx.status_code;
6197 778 : if (ctx->chain->write_fn) {
6198 11 : parse_ctx_free_fields(&ctx->pctx);
6199 : } else {
6200 767 : resp->body = ctx->bb.buf;
6201 767 : resp->body_len = ctx->bb.len;
6202 767 : resp->headers = ctx->pctx.headers;
6203 767 : ctx->pctx.headers = NULL;
6204 767 : resp->ccol__field_lines = ctx->pctx.field_lines;
6205 767 : ctx->pctx.field_lines = NULL;
6206 767 : ctx->bb.buf = NULL;
6207 : }
6208 : return resp;
6209 : }
6210 :
6211 : // Builds the response and fulfils the future, for the EOF-driven completion,
6212 : // which never pools its connection.
6213 3 : static void async_fulfill_success(chttp_async_ctx *ctx) {
6214 3 : chttpcli_response *resp = async_build_response(ctx);
6215 3 : async_fulfill(ctx, resp ? ccol_success : ccol_not_enough_memory, resp);
6216 3 : }
6217 :
6218 : #ifdef RUNNING_UNIT_TESTS
6219 : // Async idle pool
6220 : //
6221 : // Tier 2's pool, chmap(origin_key -> cvec of chttp_async_ctx *), with the same
6222 : // caps as Tier 1. A pooled connection stays registered with the reactor, so an
6223 : // IDLE dispatch notices a close or stray bytes and evicts it.
6224 : //
6225 : // Test hooks: Fail the push of an offer, fail the reactivation of a taken
6226 : // connection, and force a hard read error.
6227 : static _Atomic bool g_force_offer_push_fail_for_tests = false;
6228 : static _Atomic bool g_force_reactivate_fail_for_tests = false;
6229 : static _Atomic bool g_force_async_hard_read_error_for_tests = false;
6230 :
6231 : // Test hooks for the write-direction fall-through of async_on_writable_impl: A
6232 : // sweep flip that lands on a ctx that already moved on to reading. The first
6233 : // forces such a stray write arm, the second does it for an idle ctx, and the
6234 : // counter counts how often the stray arm was undone.
6235 : static _Atomic bool g_force_stray_write_arm_for_tests = false;
6236 : static _Atomic bool g_force_stray_idle_write_arm_for_tests = false;
6237 : static _Atomic unsigned long long g_stray_write_arm_restores_for_tests = 0;
6238 :
6239 : // Widens the window around the replay of the 100-continue carry in
6240 : // async_upload_pause, where a destroy may take the client's allocator away once
6241 : // the chain's last reference is gone.
6242 : static _Atomic long g_continue_carry_replay_delay_ms_for_tests = 0;
6243 : #ifdef RUNNING_UNIT_TESTS
6244 : // See chttpcli__arm_stray_write_at_take_for_tests.
6245 : static _Atomic bool g_stray_write_at_take_for_tests = false;
6246 : // See chttpcli__arm_stray_write_before_take_for_tests: 0 off, 1 armed, 2 the
6247 : // take armed the write direction, 3 the dispatch saw IDLE and waits, 4 the take
6248 : // moved the ctx to WRITING.
6249 : static _Atomic int g_stray_before_take_stage_for_tests = 0;
6250 :
6251 : // Waits at most 2 s until g_stray_before_take_stage_for_tests reaches stage, so
6252 : // the two sides of the stray-write test run in order.
6253 2 : static void stray_before_take_wait_for_tests(int stage) {
6254 4 : for (int i = 0; i < 2000; i++) {
6255 4 : if (atomic_load(&g_stray_before_take_stage_for_tests) >= stage) return;
6256 2 : struct timespec ts = {0, 1000000L};
6257 2 : nanosleep(&ts, NULL);
6258 : }
6259 : }
6260 : #endif
6261 :
6262 : // Sleeps the carry replay delay when a test set one, to widen the window around
6263 : // the replay.
6264 8 : static void chttp_test_continue_carry_replay_delay(void) {
6265 8 : long ms = atomic_load(&g_continue_carry_replay_delay_ms_for_tests);
6266 8 : if (ms <= 0) return;
6267 2 : struct timespec ts;
6268 2 : ts.tv_sec = ms / 1000;
6269 2 : ts.tv_nsec = (ms % 1000) * 1000000L;
6270 2 : nanosleep(&ts, NULL);
6271 : }
6272 :
6273 : // Holds the IDLE branch of async_on_readable_impl once, between deciding the
6274 : // ctx is idle and reading, so a take can win against the evicting dispatch.
6275 : // Only a dispatch that finds input waiting is held. 0 off, 1 armed, 2 holding,
6276 : // 3 released; it ends after 5 s.
6277 : static _Atomic int g_idle_probe_hold_for_tests = 0;
6278 :
6279 : // Runs the IDLE probe hold for fd, only when input is waiting, so the take can
6280 : // win against the dispatch.
6281 347 : static void chttp_test_idle_probe_hold(int fd) {
6282 347 : int pending = 0;
6283 347 : if (atomic_load(&g_idle_probe_hold_for_tests) != 1) return;
6284 2 : if (ioctl(fd, FIONREAD, &pending) != 0 || pending <= 0) return;
6285 2 : int armed = 1;
6286 2 : if (!atomic_compare_exchange_strong(&g_idle_probe_hold_for_tests, &armed, 2))
6287 : return;
6288 2 : struct timespec ts = {.tv_sec = 0, .tv_nsec = 1000000L};
6289 4 : for (int i = 0; i < 5000 && atomic_load(&g_idle_probe_hold_for_tests) == 2;
6290 2 : i++)
6291 2 : nanosleep(&ts, NULL);
6292 2 : atomic_store(&g_idle_probe_hold_for_tests, 0);
6293 : }
6294 : #endif
6295 :
6296 : // Takes one off cli->idle_total_count_async and, at zero, wakes the destroy
6297 : // that waits on idle_async_drained for the pool to empty. The caller holds
6298 : // cli->lock.
6299 538 : static void async_idle_count_dec_locked(struct chttpclient *cli) {
6300 538 : if (cli->idle_total_count_async > 0) cli->idle_total_count_async--;
6301 538 : if (cli->idle_total_count_async == 0)
6302 354 : ccol__cond_var_broadcast(cli->idle_async_drained);
6303 : }
6304 :
6305 : // Removes target from its origin's idle list by swapping with the last element,
6306 : // drops the origin's entry once its list is empty, and gives true. It gives
6307 : // false when target isn't there (another path removed it first), which lets two
6308 : // paths race for it safely. The caller holds cli->lock.
6309 346 : static bool async_idle_remove_locked(struct chttpclient *cli,
6310 : chttp_async_ctx *target) {
6311 346 : if (!cli->idle_pools_async || !target->origin_key) return false;
6312 346 : cmap_pair kp = {.ptr = target->origin_key,
6313 346 : .size = strlen(target->origin_key) + 1};
6314 346 : cmap_pair vp;
6315 346 : if (chashmap_get_elem_ref(cli->idle_pools_async, &kp, &vp) != ccol_success)
6316 : return false;
6317 344 : cvec list = read_cvec(vp.ptr);
6318 344 : if (!list) return false;
6319 344 : size_t n = cvector_size(list);
6320 401 : for (size_t i = 0; i < n; i++) {
6321 401 : chttp_async_ctx **slot = (chttp_async_ctx **)cvector_at(list, i);
6322 401 : if (*slot != target) continue;
6323 344 : chttp_async_ctx *last = NULL;
6324 344 : cvector_pop_back(list, &last);
6325 344 : if (i < cvector_size(list)) {
6326 99 : chttp_async_ctx **slot2 = (chttp_async_ctx **)cvector_at(list, i);
6327 99 : *slot2 = last;
6328 : }
6329 344 : if (cvector_size(list) == 0) {
6330 213 : cvector__destroy(list);
6331 213 : chashmap_remove_elem(cli->idle_pools_async, &kp);
6332 : }
6333 344 : return true;
6334 : }
6335 : return false;
6336 : }
6337 :
6338 : // Pops a usable idle connection for origin_key into *out, evicting stale,
6339 : // TLS-outdated and closed candidates. On a true return the ctx's idle_lock is
6340 : // held; the caller (async_submit_hop) unlocks it once the ctx is set up for the
6341 : // new hop and its write was tried.
6342 1002 : static bool async_idle_pool_take(struct chttpclient *cli,
6343 : const char *origin_key,
6344 : chttp_async_chain *chain,
6345 : chttp_async_ctx **out) {
6346 1002 : chttp_async_ctx *ctx = NULL;
6347 1002 : ccol__mutex_lock(cli->lock);
6348 1002 : if (cli->idle_pools_async) {
6349 1002 : cmap_pair kp = {.ptr = (void *)origin_key, .size = strlen(origin_key) + 1};
6350 1002 : cmap_pair vp;
6351 1002 : if (chashmap_get_elem_ref(cli->idle_pools_async, &kp, &vp) ==
6352 : ccol_success) {
6353 378 : cvec list = read_cvec(vp.ptr);
6354 378 : if (list) {
6355 378 : struct timespec now;
6356 378 : clock_gettime(CLOCK_MONOTONIC, &now);
6357 378 : size_t n = cvector_size(list);
6358 723 : for (size_t idx = n; idx-- > 0;) {
6359 539 : chttp_async_ctx **slot = (chttp_async_ctx **)cvector_at(list, idx);
6360 539 : chttp_async_ctx *cand = *slot;
6361 539 : int64_t age_ms = ms_elapsed_floor(&cand->last_used, &now);
6362 539 : if (age_ms > CHTTP_IDLE_MAX_AGE_MS ||
6363 195 : (cand->is_https && cand->tls_generation != cli->tls_generation)) {
6364 345 : int fd = cand->fd;
6365 345 : if (fd >= 0) shutdown(fd, SHUT_RDWR);
6366 345 : continue;
6367 : }
6368 194 : chttp_async_ctx *last = NULL;
6369 194 : cvector_pop_back(list, &last);
6370 194 : if (idx < cvector_size(list)) {
6371 0 : chttp_async_ctx **slot2 = (chttp_async_ctx **)cvector_at(list, idx);
6372 0 : *slot2 = last;
6373 : }
6374 194 : async_idle_count_dec_locked(cli);
6375 194 : ctx = cand;
6376 194 : if (cvector_size(list) == 0) {
6377 177 : cvector__destroy(list);
6378 177 : chashmap_remove_elem(cli->idle_pools_async, &kp);
6379 : }
6380 194 : break;
6381 : }
6382 : }
6383 : }
6384 : }
6385 1002 : ccol__mutex_unlock(cli->lock);
6386 1002 : if (!ctx) return false;
6387 :
6388 : #ifdef RUNNING_UNIT_TESTS
6389 194 : int stray_armed = 1;
6390 194 : bool stray_before_take = atomic_compare_exchange_strong(
6391 : &g_stray_before_take_stage_for_tests, &stray_armed, 2);
6392 194 : if (stray_before_take) {
6393 1 : (void)ceventloop_modify(cli_engine_bundler.reactor, ctx->reg,
6394 : cselect_write);
6395 1 : stray_before_take_wait_for_tests(3);
6396 : }
6397 : #endif
6398 194 : ccol__mutex_lock(ctx->idle_lock);
6399 : #ifdef RUNNING_UNIT_TESTS
6400 194 : ctx->idle_lock_held_for_tests = true;
6401 : #endif
6402 194 : ccol__mutex_lock(ctx->deadline_lock);
6403 194 : ctx->overall_deadline = chain->overall_deadline;
6404 194 : ctx->inactivity_us = chain->inactivity_timeout_us;
6405 194 : atomic_store(&ctx->last_io_ns, 0);
6406 194 : ctx->timed_out = false;
6407 194 : ctx->chain = chain;
6408 194 : ctx->state = CHTTP_ASYNC_WRITING;
6409 194 : ccol__mutex_unlock(ctx->deadline_lock);
6410 194 : client_deadline_note(&chain->overall_deadline);
6411 : #ifdef RUNNING_UNIT_TESTS
6412 194 : if (stray_before_take) {
6413 1 : atomic_store(&g_stray_before_take_stage_for_tests, 4);
6414 1 : struct timespec ts = {0, 200000000L};
6415 1 : nanosleep(&ts, NULL);
6416 : }
6417 : #endif
6418 194 : *out = ctx;
6419 194 : return true;
6420 : }
6421 :
6422 : // Offers a finished connection back to the idle pool. false means the ctx was
6423 : // left completely untouched and the caller closes it. true means the pool owns
6424 : // it: It's in state IDLE with no chain, holds its own engine reference, and is
6425 : // off the deadline registry. The state change happens under idle_lock and
6426 : // deadline_lock, so the sweep can never judge it half made.
6427 551 : static bool async_idle_pool_offer(chttp_async_ctx *ctx) {
6428 551 : struct chttpclient *cli = ctx->cli;
6429 :
6430 551 : if (client_engine_acquire() != ccol_success) return false;
6431 :
6432 551 : cvec list = NULL;
6433 551 : bool has_room = false;
6434 551 : ccol__mutex_lock(cli->lock);
6435 551 : if (!cli->destroying && cli->idle_pools_async &&
6436 551 : cli->idle_total_count_async < CHTTP_MAX_IDLE_TOTAL) {
6437 551 : cmap_pair kp = {.ptr = ctx->origin_key,
6438 551 : .size = strlen(ctx->origin_key) + 1};
6439 551 : cmap_pair vp;
6440 551 : if (chashmap_get_elem_ref(cli->idle_pools_async, &kp, &vp) ==
6441 : ccol_success) {
6442 156 : list = read_cvec(vp.ptr);
6443 : }
6444 946 : if (!list &&
6445 395 : chashmap_size(cli->idle_pools_async) < effective_max_idle_origins()) {
6446 394 : char *cverr = NULL;
6447 788 : list =
6448 394 : cvector_create_full(sizeof(chttp_async_ctx *), cli->m_procs, &cverr);
6449 394 : if (list) {
6450 392 : cmap_pair vp2 = {.ptr = &list, .size = sizeof(list)};
6451 392 : if (chashmap_insert_elem(cli->idle_pools_async, &kp, &vp2) !=
6452 : ccol_success) {
6453 1 : cvector__destroy(list);
6454 1 : list = NULL;
6455 : }
6456 : }
6457 : }
6458 551 : has_room = (list && cvector_size(list) < CHTTP_MAX_IDLE_PER_ORIGIN);
6459 : }
6460 12 : if (!has_room) {
6461 12 : ccol__mutex_unlock(cli->lock);
6462 12 : client_engine_release();
6463 12 : return false;
6464 : }
6465 :
6466 539 : chttp_async_chain *old_chain = ctx->chain;
6467 :
6468 539 : parse_ctx_free_fields(&ctx->pctx);
6469 539 : memset(&ctx->pctx, 0, sizeof(ctx->pctx));
6470 539 : chttp1_parser_release(&ctx->parser);
6471 539 : ccol__mem_free(ctx->mp, ctx->bb.buf);
6472 539 : ctx->bb.buf = NULL;
6473 539 : ctx->bb.len = ctx->bb.cap = 0;
6474 539 : ctx->bb.oom = false;
6475 539 : ctx->bb.too_large = false;
6476 539 : ccol__mem_free(ctx->mp, ctx->wire);
6477 539 : ctx->wire = NULL;
6478 539 : ctx->wire_len = ctx->wire_sent = 0;
6479 539 : ccol__mem_free(ctx->mp, ctx->continue_carry);
6480 539 : ctx->continue_carry = NULL;
6481 539 : ctx->continue_carry_len = 0;
6482 539 : ctx->want_100_continue = false;
6483 539 : ctx->header_len = 0;
6484 539 : ctx->retry_unsafe = false;
6485 539 : ctx->upload_paused = false;
6486 539 : ctx->resp_msg_started = false;
6487 539 : ctx->tls_read_blocked = false;
6488 539 : ctx->idle_tainted = false;
6489 539 : ctx->upload_check_at = 0;
6490 539 : ctx->answered_early = false;
6491 539 : ctx->duplex = false;
6492 539 : atomic_store(&ctx->flip_watch, CHTTP_FLIP_NONE);
6493 539 : atomic_store(&ctx->continue_decided, false);
6494 539 : atomic_store(&ctx->continue_msg_started, false);
6495 539 : ccol__mem_free(ctx->mp, ctx->path_and_query);
6496 539 : ctx->path_and_query = NULL;
6497 539 : ctx->hop_completed = false;
6498 539 : ctx->reused = false;
6499 539 : ctx->any_bytes_read = false;
6500 539 : ctx->interim_responses_seen = 0;
6501 : #ifdef RUNNING_UNIT_TESTS
6502 539 : atomic_fetch_add(&g_offer_entered_for_tests, 1);
6503 : #endif
6504 539 : ccol__mutex_lock(ctx->idle_lock);
6505 539 : ccol__mutex_lock(ctx->deadline_lock);
6506 539 : ctx->chain = NULL;
6507 539 : ctx->state = CHTTP_ASYNC_IDLE;
6508 539 : ctx->timed_out = false;
6509 539 : if (atomic_exchange(&ctx->abandoned, false))
6510 0 : atomic_fetch_sub(&g_async_hops_abandoned, 1);
6511 539 : ccol__mutex_unlock(ctx->deadline_lock);
6512 539 : ccol__mutex_unlock(ctx->idle_lock);
6513 : #ifdef RUNNING_UNIT_TESTS
6514 539 : atomic_fetch_add(&g_offer_done_for_tests, 1);
6515 : #endif
6516 :
6517 539 : clock_gettime(CLOCK_MONOTONIC, &ctx->last_used);
6518 539 : bool pushed;
6519 : #ifdef RUNNING_UNIT_TESTS
6520 539 : if (atomic_exchange(&g_force_offer_push_fail_for_tests, false)) {
6521 : pushed = false;
6522 : } else
6523 : #endif
6524 : {
6525 538 : pushed = (cvector_push_back(list, &ctx) == ccol_success);
6526 : }
6527 538 : if (pushed) cli->idle_total_count_async++;
6528 539 : ccol__mutex_unlock(cli->lock);
6529 :
6530 539 : if (!pushed) {
6531 1 : async_ctx_free(ctx);
6532 1 : client_engine_release();
6533 1 : async_chain_release(old_chain);
6534 1 : return true;
6535 : }
6536 :
6537 : #ifdef RUNNING_UNIT_TESTS
6538 538 : if (atomic_exchange(&g_force_stray_idle_write_arm_for_tests, false)) {
6539 1 : async_reg_modify(ctx, cselect_write);
6540 : }
6541 : #endif
6542 538 : async_chain_release(old_chain);
6543 538 : return true;
6544 : }
6545 :
6546 : static void async_retry_hop(chttp_async_ctx *ctx);
6547 :
6548 : // Ends a hop's ctx through its single teardown point. A reused connection that
6549 : // died before any response byte is retried once on a fresh connection, when the
6550 : // request didn't go out in full or is replayable and no body went out after a
6551 : // "100 Continue"; otherwise the failure is reported. A timeout reports
6552 : // ccol_timed_out and is never retried.
6553 465 : static void async_ctx_finish(chttp_async_ctx *ctx) {
6554 465 : if (!ctx->hop_completed) {
6555 44 : if (ctx->timed_out) {
6556 0 : async_fulfill(ctx, ccol_timed_out, NULL);
6557 44 : } else if (ctx->reused && !ctx->any_bytes_read && !ctx->retry_unsafe &&
6558 36 : (ctx->replayable || ctx->wire_sent < ctx->wire_len)) {
6559 32 : async_retry_hop(ctx);
6560 : }
6561 : }
6562 465 : async_ctx_teardown(ctx);
6563 465 : }
6564 :
6565 : // Tears down a ctx that sits in the idle pool, when its IDLE dispatch sees a
6566 : // close or an error. It acts only when this call is the one that removes the
6567 : // ctx from the pool (cli->lock decides), and then drops the ctx's own engine
6568 : // reference.
6569 346 : static void async_idle_ctx_finish(chttp_async_ctx *ctx) {
6570 346 : struct chttpclient *cli = ctx->cli;
6571 346 : ccol__mutex_lock(cli->lock);
6572 346 : bool removed = async_idle_remove_locked(cli, ctx);
6573 346 : ccol__mutex_unlock(cli->lock);
6574 346 : if (!removed) return;
6575 344 : async_ctx_free(ctx);
6576 344 : client_engine_release();
6577 344 : ccol__mutex_lock(cli->lock);
6578 344 : async_idle_count_dec_locked(cli);
6579 344 : ccol__mutex_unlock(cli->lock);
6580 : }
6581 :
6582 : // Ends a connecting ctx whose connect failed, reporting ccol_timed_out when the
6583 : // sweep caused the failure and ccol_http_connection_failed otherwise.
6584 4 : static void async_connect_failed(chttp_async_ctx *ctx) {
6585 4 : async_fulfill(
6586 4 : ctx, ctx->timed_out ? ccol_timed_out : ccol_http_connection_failed, NULL);
6587 4 : async_ctx_finish(ctx);
6588 4 : }
6589 :
6590 : // Ends a hop's connection once its response is consumed: Offers the connection
6591 : // to the idle pool when reusable and the request didn't ask for close,
6592 : // otherwise closes it.
6593 895 : static void async_finish_connection(chttp_async_ctx *ctx, bool reusable) {
6594 1446 : if (reusable && !ctx->request_close && ctx->origin_key &&
6595 551 : async_idle_pool_offer(ctx))
6596 : return;
6597 356 : async_ctx_finish(ctx);
6598 : }
6599 :
6600 : static void async_retry_hop(chttp_async_ctx *ctx);
6601 :
6602 : static void async_tls_try_write(chttp_async_ctx *ctx);
6603 :
6604 : static void async_process_reading_data(chttp_async_ctx *ctx, const char *data,
6605 : size_t data_len);
6606 :
6607 : // Drives the TLS handshake of ctx one step, from a readable or writable
6608 : // dispatch, because the reactor knows nothing about TLS. It turns the
6609 : // registration to whichever direction the handshake needs next, starts the
6610 : // write once the handshake ends, and fails the hop on a handshake error.
6611 201 : static void async_tls_advance(chttp_async_ctx *ctx) {
6612 201 : ctls_handshake_result r = ctls_conn_handshake_step(ctx->tls);
6613 201 : if (r == CTLS_HANDSHAKE_DONE) {
6614 88 : ctx->state = CHTTP_ASYNC_WRITING;
6615 88 : if (async_reg_modify(ctx, cselect_write) != ccol_success) {
6616 0 : async_ctx_finish(ctx);
6617 0 : return;
6618 : }
6619 88 : async_tls_try_write(ctx);
6620 88 : return;
6621 : }
6622 113 : if (r == CTLS_HANDSHAKE_ERROR) {
6623 13 : long vr = ctls_conn_verify_result(ctx->tls);
6624 13 : async_fulfill(ctx,
6625 : ctx->timed_out
6626 13 : ? ccol_timed_out
6627 12 : : (vr != 0 ? ccol_http_tls_cert_verification_failed
6628 : : ccol_http_tls_handshake_failed),
6629 : NULL);
6630 13 : async_ctx_finish(ctx);
6631 13 : return;
6632 : }
6633 100 : cselect_dir want =
6634 100 : (r == CTLS_HANDSHAKE_WANT_WRITE) ? cselect_write : cselect_read;
6635 100 : if (async_reg_modify(ctx, want) != ccol_success) {
6636 0 : async_ctx_finish(ctx);
6637 : }
6638 : }
6639 :
6640 : static void async_plain_try_write(chttp_async_ctx *ctx);
6641 :
6642 : // Tells whether every request byte went out before a response started, so the
6643 : // pooling decision never reuses a connection with request bytes left behind.
6644 565 : static inline bool async_request_sent(const chttp_async_ctx *ctx) {
6645 565 : return ctx->wire_sent >= ctx->wire_len && !ctx->answered_early;
6646 : }
6647 :
6648 : // Tells whether the socket or the TLS layer holds input a read would take
6649 : // without waiting. After a read that blocked only the socket counts, since the
6650 : // TLS layer also reports a partial record as pending input.
6651 1313 : static bool async_input_pending(chttp_async_ctx *ctx) {
6652 1327 : if (ctx->tls && !ctx->tls_read_blocked &&
6653 14 : ctls_conn_has_pending_input(ctx->tls))
6654 : return true;
6655 1313 : struct pollfd p = {.fd = ctx->fd, .events = POLLIN, .revents = 0};
6656 1313 : int rc;
6657 1313 : do {
6658 1313 : rc = poll(&p, 1, 0);
6659 1313 : } while (rc < 0 && errno == EINTR);
6660 1434 : return rc > 0 && (p.revents & POLLIN) != 0;
6661 : }
6662 :
6663 : // Stops the room watch of ctx if it has one (see ctx->room_reg), before reg
6664 : // turns to writing and before a teardown.
6665 3656 : static void async_room_watch_stop(chttp_async_ctx *ctx) {
6666 3656 : ceventloop_reg room = atomic_exchange(&ctx->room_reg, CEVENTLOOP_REG_NULL);
6667 3656 : if (room) ceventloop_remove(cli_engine_bundler.reactor, room);
6668 3656 : }
6669 :
6670 : #ifdef RUNNING_UNIT_TESTS
6671 : // While armed, the next hop that turns to reading gets no dispatch: Its
6672 : // registration is paused right away, as if the dispatch pool could never run
6673 : // it, so a test can check that the request timeout still holds.
6674 : static _Atomic bool g_stall_next_read_for_tests = false;
6675 : static _Atomic ceventloop_reg g_stalled_reg_for_tests = CEVENTLOOP_REG_NULL;
6676 :
6677 : // Arms g_stall_next_read_for_tests, so a test can check that a hop with no
6678 : // dispatch still ends at its request timeout.
6679 2 : void chttp__stall_next_read_for_tests(void) {
6680 2 : atomic_store(&g_stalled_reg_for_tests, CEVENTLOOP_REG_NULL);
6681 2 : atomic_store(&g_stall_next_read_for_tests, true);
6682 2 : }
6683 :
6684 : // Resumes the registration the stall hook paused, so the test can let the hop
6685 : // finish. Gives true when there was one.
6686 2 : bool chttp__stalled_read_resume_for_tests(void) {
6687 2 : ceventloop_reg reg =
6688 2 : atomic_exchange(&g_stalled_reg_for_tests, CEVENTLOOP_REG_NULL);
6689 2 : if (!reg) return false;
6690 2 : return ceventloop_resume(cli_engine_bundler.reactor, reg) == ccol_success;
6691 : }
6692 : #endif
6693 :
6694 : // Turns ctx->reg to direction dir. A room watch holds the fd's write direction,
6695 : // so turning reg to writing ends the room watch first (one registration per
6696 : // direction of an fd).
6697 4746 : static ccol_retval async_reg_modify(chttp_async_ctx *ctx, cselect_dir dir) {
6698 4746 : if (dir == cselect_write) async_room_watch_stop(ctx);
6699 : #ifdef RUNNING_UNIT_TESTS
6700 4746 : if (dir == cselect_read && ctx->state == CHTTP_ASYNC_READING &&
6701 4519 : atomic_exchange(&g_stall_next_read_for_tests, false)) {
6702 2 : ccol_retval mrv =
6703 2 : ceventloop_modify(cli_engine_bundler.reactor, ctx->reg, dir);
6704 4 : if (mrv == ccol_success &&
6705 2 : ceventloop_pause(cli_engine_bundler.reactor, ctx->reg) == ccol_success)
6706 2 : atomic_store(&g_stalled_reg_for_tests, ctx->reg);
6707 2 : return mrv;
6708 : }
6709 : #endif
6710 4744 : return ceventloop_modify(cli_engine_bundler.reactor, ctx->reg, dir);
6711 : }
6712 :
6713 : static void async_on_room(ceventloop loop, ceventloop_reg reg, cselectable *sel,
6714 : void *arg);
6715 :
6716 : // Starts the room watch of a duplex send that a full send buffer paused, so the
6717 : // send continues when there is room while a response is read at once. Gives
6718 : // false when the registration can't be added. The caller holds the fd's
6719 : // dispatch lock or owns the ctx alone.
6720 3545 : static bool async_room_watch_start(chttp_async_ctx *ctx) {
6721 3545 : if (atomic_load(&ctx->room_reg)) return true;
6722 3545 : char *err = NULL;
6723 3545 : ceventloop_handlers handlers = {.on_writable = async_on_room};
6724 7090 : ceventloop_reg room = ceventloop_add(cli_engine_bundler.reactor,
6725 3545 : cselectable_fd(ctx->fd, cselect_write),
6726 : handlers, ctx, &err);
6727 3545 : if (!room) return false;
6728 3545 : atomic_store(&ctx->room_reg, room);
6729 3545 : return true;
6730 : }
6731 :
6732 : // Resumes the paused duplex send of ctx when its room watch fires. It runs
6733 : // under the fd's dispatch lock, so it never races a dispatch of ctx->reg; an
6734 : // error on the fd lands here too, and the write reports it.
6735 30 : static void async_on_room(ceventloop loop, ceventloop_reg reg, cselectable *sel,
6736 : void *arg) {
6737 30 : (void)loop;
6738 30 : (void)sel;
6739 30 : chttp_async_ctx *ctx = (chttp_async_ctx *)arg;
6740 30 : atomic_store(&ctx->last_io_ns, monotonic_now_ns());
6741 30 : ceventloop_reg expected = reg;
6742 30 : if (!atomic_compare_exchange_strong(&ctx->room_reg, &expected,
6743 : CEVENTLOOP_REG_NULL))
6744 30 : return;
6745 30 : ceventloop_remove(cli_engine_bundler.reactor, reg);
6746 30 : if (ctx->hop_completed) {
6747 0 : async_ctx_handle_if_abandoned(ctx);
6748 0 : return;
6749 : }
6750 30 : if (ctx->state == CHTTP_ASYNC_READING && ctx->upload_paused &&
6751 30 : (ctx->duplex || async_upload_may_resume(ctx)))
6752 30 : async_upload_resume(ctx);
6753 : }
6754 :
6755 : // Feeds the bytes that came with the "100 Continue" to the parser before
6756 : // anything a later read takes. It can end the hop and free ctx, so it's the
6757 : // caller's last action; mp is read into a local first.
6758 3572 : static void async_replay_continue_carry(chttp_async_ctx *ctx) {
6759 3572 : if (!ctx->continue_carry) return;
6760 4 : ccol_memmgmt_procs *mp = ctx->mp;
6761 4 : char *carry = ctx->continue_carry;
6762 4 : size_t carry_len = ctx->continue_carry_len;
6763 4 : ctx->continue_carry = NULL;
6764 4 : ctx->continue_carry_len = 0;
6765 4 : chttp_async_chain *carry_chain = ctx->chain;
6766 4 : async_chain_retain(carry_chain);
6767 : #ifdef RUNNING_UNIT_TESTS
6768 4 : chttp_test_continue_carry_replay_delay();
6769 : #endif
6770 4 : async_process_reading_data(ctx, carry, carry_len);
6771 : #ifdef RUNNING_UNIT_TESTS
6772 4 : chttp_test_continue_carry_replay_delay();
6773 : #endif
6774 4 : ccol__mem_free(mp, carry);
6775 4 : async_chain_release(carry_chain);
6776 : }
6777 :
6778 : // Stops sending the request, for a while (paused) or for good, and hands the
6779 : // ctx to the read path. A duplex send that can't start its room watch falls
6780 : // back to the sweep flipping the direction (flip_watch). It can free ctx, so
6781 : // the caller does nothing after it.
6782 3572 : static void async_upload_pause(chttp_async_ctx *ctx, bool paused) {
6783 3572 : ctx->upload_paused = paused;
6784 3572 : atomic_store(&ctx->flip_watch, CHTTP_FLIP_NONE);
6785 3572 : ctx->state = CHTTP_ASYNC_READING;
6786 3572 : if (async_reg_modify(ctx, cselect_read) != ccol_success) {
6787 0 : async_ctx_finish(ctx);
6788 0 : return;
6789 : }
6790 3572 : if (paused && ctx->duplex && !async_room_watch_start(ctx))
6791 0 : atomic_store(&ctx->flip_watch, CHTTP_FLIP_ON_ROOM);
6792 3572 : async_replay_continue_carry(ctx);
6793 : }
6794 :
6795 : // Continues a paused send. It can free ctx, so the caller does nothing after
6796 : // it.
6797 3555 : static void async_upload_resume(chttp_async_ctx *ctx) {
6798 3555 : async_room_watch_stop(ctx);
6799 3555 : if (ctx->resp_msg_started && ctx->pctx.status_code >= 200 &&
6800 : ctx->pctx.status_code < 300)
6801 3551 : ctx->duplex = true;
6802 3555 : ctx->upload_paused = false;
6803 3555 : ctx->state = CHTTP_ASYNC_WRITING;
6804 3555 : if (ctx->tls) {
6805 4 : async_tls_try_write(ctx);
6806 : } else {
6807 3551 : async_plain_try_write(ctx);
6808 : }
6809 3555 : }
6810 :
6811 : // After this many request bytes since the last check, a successful write looks
6812 : // for a response. A server that answers early and closes resets the connection,
6813 : // and on Linux that reset drops an answer the client hasn't read.
6814 : #define CHTTP_UPLOAD_INPUT_CHECK_BYTES (32u * 1024u)
6815 :
6816 : // True when a write leaves request bytes to send and a response has started to
6817 : // arrive, which pauses the send. It polls only every
6818 : // CHTTP_UPLOAD_INPUT_CHECK_BYTES.
6819 2834 : static bool async_upload_should_pause(chttp_async_ctx *ctx,
6820 : bool awaiting_continue,
6821 : size_t target_len) {
6822 2810 : if (awaiting_continue || ctx->wire_sent >= target_len ||
6823 1862 : ctx->wire_sent < ctx->upload_check_at)
6824 : return false;
6825 1300 : ctx->upload_check_at = ctx->wire_sent + CHTTP_UPLOAD_INPUT_CHECK_BYTES;
6826 1300 : return async_input_pending(ctx);
6827 : }
6828 :
6829 : // True when a paused send may continue: No message started since the last
6830 : // discarded one, or the one that did is a 2xx final response with its header
6831 : // block in.
6832 84 : static inline bool async_upload_may_resume(const chttp_async_ctx *ctx) {
6833 84 : return ctx->upload_paused &&
6834 4 : (!ctx->resp_msg_started ||
6835 0 : (ctx->pctx.status_code >= 200 && ctx->pctx.status_code < 300));
6836 : }
6837 :
6838 : // Writes as much of ctx->wire as ctls_conn_write takes now and keeps track of
6839 : // partial progress. With "Expect: 100-continue" it stops at the end of the
6840 : // header block and waits for the answer. A response that arrives while sending
6841 : // pauses the upload (see async_upload_pause), and EPIPE or ECONNRESET turns the
6842 : // hop to reading so the answer isn't lost. It can free ctx.
6843 151 : static void async_tls_try_write(chttp_async_ctx *ctx) {
6844 151 : if (atomic_load_explicit(&ctx->flip_watch, memory_order_relaxed))
6845 0 : atomic_store_explicit(&ctx->flip_watch, CHTTP_FLIP_NONE,
6846 : memory_order_relaxed);
6847 302 : bool awaiting_continue =
6848 151 : ctx->want_100_continue && !atomic_load(&ctx->continue_decided);
6849 151 : size_t target_len = awaiting_continue ? ctx->header_len : ctx->wire_len;
6850 429 : while (ctx->wire_sent < target_len) {
6851 287 : ssize_t n;
6852 : #ifdef RUNNING_UNIT_TESTS
6853 287 : if (tls_dir_inject_blocks(true)) {
6854 1 : errno = EWOULDBLOCK;
6855 1 : n = -1;
6856 : } else
6857 : #endif
6858 : {
6859 286 : n = ctls_conn_write(ctx->tls, ctx->wire + ctx->wire_sent,
6860 286 : target_len - ctx->wire_sent);
6861 : }
6862 287 : if (n > 0) {
6863 286 : ctx->wire_sent += (size_t)n;
6864 572 : if (async_upload_should_pause(ctx, awaiting_continue, target_len)) {
6865 8 : async_upload_pause(ctx, true);
6866 8 : return;
6867 : }
6868 278 : continue;
6869 : }
6870 1 : if (n < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
6871 1 : if (!awaiting_continue && (ctx->duplex || async_input_pending(ctx))) {
6872 0 : async_upload_pause(ctx, true);
6873 0 : return;
6874 : }
6875 2 : cselect_dir want =
6876 1 : conn_tls_wants_write(ctx->tls) ? cselect_write : cselect_read;
6877 1 : if (want == cselect_write && !awaiting_continue)
6878 0 : atomic_store(&ctx->flip_watch, CHTTP_FLIP_ON_INPUT);
6879 : #ifdef RUNNING_UNIT_TESTS
6880 1 : if (want == cselect_read) {
6881 1 : atomic_fetch_add(&g_tls_dir_read_interest_while_writing, 1u);
6882 1 : tls_dir_note_wait(false);
6883 : }
6884 : #endif
6885 1 : if (async_reg_modify(ctx, want) != ccol_success) {
6886 0 : async_ctx_finish(ctx);
6887 : }
6888 1 : return;
6889 : }
6890 0 : if (n == 0 || errno == ECONNRESET || errno == EPIPE || errno == ENOTCONN) {
6891 0 : async_upload_pause(ctx, false);
6892 0 : return;
6893 : }
6894 0 : async_ctx_finish(ctx);
6895 0 : return;
6896 : }
6897 142 : if (awaiting_continue) {
6898 0 : ccol__mutex_lock(ctx->deadline_lock);
6899 0 : ctx->continue_deadline = deadline_earlier(
6900 : deadline_make(CHTTP_100_CONTINUE_WAIT_US), ctx->overall_deadline);
6901 0 : chttp_deadline continue_dl = ctx->continue_deadline;
6902 0 : ccol__mutex_unlock(ctx->deadline_lock);
6903 0 : client_deadline_note(&continue_dl);
6904 : #ifdef RUNNING_UNIT_TESTS
6905 0 : continue_deadline_stored_for_tests();
6906 : #endif
6907 0 : ctx->state = CHTTP_ASYNC_AWAITING_CONTINUE;
6908 0 : if (async_reg_modify(ctx, cselect_read) != ccol_success) {
6909 0 : async_ctx_finish(ctx);
6910 : }
6911 0 : return;
6912 : }
6913 142 : if (!ctx->reused) {
6914 84 : ccol__mem_free(ctx->mp, ctx->wire);
6915 84 : ctx->wire = NULL;
6916 84 : ctx->wire_len = ctx->wire_sent = 0;
6917 : }
6918 142 : ctx->state = CHTTP_ASYNC_READING;
6919 142 : if (async_reg_modify(ctx, cselect_read) != ccol_success) {
6920 0 : async_ctx_finish(ctx);
6921 : }
6922 : }
6923 :
6924 : // Writes as much of ctx->wire as send() takes now, the plain-HTTP counterpart
6925 : // of async_tls_try_write, with the same 100-continue stop, early response pause
6926 : // and switch to reading on EPIPE or ECONNRESET. It can free ctx.
6927 4400 : static void async_plain_try_write(chttp_async_ctx *ctx) {
6928 4400 : if (atomic_load_explicit(&ctx->flip_watch, memory_order_relaxed))
6929 10 : atomic_store_explicit(&ctx->flip_watch, CHTTP_FLIP_NONE,
6930 : memory_order_relaxed);
6931 8800 : bool awaiting_continue =
6932 4400 : ctx->want_100_continue && !atomic_load(&ctx->continue_decided);
6933 4400 : size_t target_len = awaiting_continue ? ctx->header_len : ctx->wire_len;
6934 5766 : while (ctx->wire_sent < target_len) {
6935 4936 : ssize_t n = send(ctx->fd, ctx->wire + ctx->wire_sent,
6936 : target_len - ctx->wire_sent, CCOL_MSG_NOSIGNAL);
6937 4936 : if (n > 0) {
6938 2548 : ctx->wire_sent += (size_t)n;
6939 5072 : if (async_upload_should_pause(ctx, awaiting_continue, target_len)) {
6940 1182 : async_upload_pause(ctx, true);
6941 1182 : return;
6942 : }
6943 1366 : continue;
6944 : }
6945 2388 : if (n < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
6946 2387 : if (!awaiting_continue && (ctx->duplex || async_input_pending(ctx))) {
6947 2377 : async_upload_pause(ctx, true);
6948 2377 : return;
6949 : }
6950 10 : if (!awaiting_continue)
6951 10 : atomic_store(&ctx->flip_watch, CHTTP_FLIP_ON_INPUT);
6952 10 : if (async_reg_modify(ctx, cselect_write) != ccol_success) {
6953 0 : async_ctx_finish(ctx);
6954 : }
6955 10 : return;
6956 : }
6957 1 : if (n < 0 && (errno == ECONNRESET || errno == EPIPE || errno == ENOTCONN)) {
6958 1 : async_upload_pause(ctx, false);
6959 1 : return;
6960 : }
6961 0 : async_ctx_finish(ctx);
6962 0 : return;
6963 : }
6964 830 : if (awaiting_continue) {
6965 24 : ccol__mutex_lock(ctx->deadline_lock);
6966 24 : ctx->continue_deadline = deadline_earlier(
6967 : deadline_make(CHTTP_100_CONTINUE_WAIT_US), ctx->overall_deadline);
6968 24 : chttp_deadline continue_dl = ctx->continue_deadline;
6969 24 : ccol__mutex_unlock(ctx->deadline_lock);
6970 24 : client_deadline_note(&continue_dl);
6971 : #ifdef RUNNING_UNIT_TESTS
6972 24 : continue_deadline_stored_for_tests();
6973 : #endif
6974 24 : ctx->state = CHTTP_ASYNC_AWAITING_CONTINUE;
6975 24 : if (async_reg_modify(ctx, cselect_read) != ccol_success) {
6976 0 : async_ctx_finish(ctx);
6977 : }
6978 24 : return;
6979 : }
6980 806 : if (!ctx->reused) {
6981 697 : ccol__mem_free(ctx->mp, ctx->wire);
6982 695 : ctx->wire = NULL;
6983 695 : ctx->wire_len = ctx->wire_sent = 0;
6984 : }
6985 804 : ctx->state = CHTTP_ASYNC_READING;
6986 804 : if (async_reg_modify(ctx, cselect_read) != ccol_success) {
6987 0 : async_ctx_finish(ctx);
6988 0 : return;
6989 : }
6990 : #ifdef RUNNING_UNIT_TESTS
6991 806 : if (atomic_exchange(&g_force_stray_write_arm_for_tests, false)) {
6992 1 : async_reg_modify(ctx, cselect_write);
6993 : }
6994 : #endif
6995 : }
6996 :
6997 : static void async_handle_redirect(chttp_async_ctx *ctx, bool reusable);
6998 :
6999 : // What async_dispatch_kind found: An active hop, an idle pooled connection, or
7000 : // a hop already completed.
7001 : typedef enum {
7002 : CHTTP_ASYNC_DISPATCH_ACTIVE,
7003 : CHTTP_ASYNC_DISPATCH_IDLE,
7004 : CHTTP_ASYNC_DISPATCH_ABANDONED,
7005 : } chttp_async_dispatch_kind;
7006 :
7007 : // Classifies a dispatch of ctx, for every dispatch callback: It reads
7008 : // ctx->state and checks hop_completed again, both under idle_lock, because an
7009 : // unlocked read can see a take half done. ABANDONED covers a hop that completed
7010 : // between the caller's unlocked check and this one.
7011 6888 : static chttp_async_dispatch_kind async_dispatch_kind(chttp_async_ctx *ctx) {
7012 6888 : ccol__mutex_lock(ctx->idle_lock);
7013 6888 : bool completed = ctx->hop_completed;
7014 6888 : bool idle = (ctx->state == CHTTP_ASYNC_IDLE);
7015 6888 : ccol__mutex_unlock(ctx->idle_lock);
7016 6888 : if (completed) return CHTTP_ASYNC_DISPATCH_ABANDONED;
7017 6888 : return idle ? CHTTP_ASYNC_DISPATCH_IDLE : CHTTP_ASYNC_DISPATCH_ACTIVE;
7018 : }
7019 :
7020 : // Handles a dispatch that finds hop_completed already true: It runs a teardown
7021 : // that an application-thread path left for the dispatch (pending_app_teardown),
7022 : // and does nothing for a stray dispatch.
7023 5 : static void async_ctx_handle_if_abandoned(chttp_async_ctx *ctx) {
7024 5 : if (ctx->pending_app_teardown) async_ctx_teardown(ctx);
7025 5 : }
7026 :
7027 : // Publishes reg into ctx->reg while it's still CEVENTLOOP_REG_NULL, with a
7028 : // compare-and-exchange, because a dispatch can run before async_connect_task
7029 : // has stored what ceventloop_add returned. Both are the same handle.
7030 6888 : static inline void async_adopt_reg(chttp_async_ctx *ctx, ceventloop_reg reg) {
7031 6888 : ceventloop_reg expected = CEVENTLOOP_REG_NULL;
7032 6888 : atomic_compare_exchange_strong(&ctx->reg, &expected, reg);
7033 : }
7034 :
7035 : static void async_on_readable_impl(ceventloop loop, ceventloop_reg reg,
7036 : cselectable *sel, chttp_async_ctx *ctx);
7037 :
7038 : // Tells, once per hop on a connection from the idle pool, whether it's really
7039 : // empty before the first request byte goes out: A MSG_PEEK (or a TLS read) must
7040 : // find no input and no EOF, and the IDLE dispatch must not have taken input
7041 : // (idle_tainted). A take can beat the dispatch that would evict it, so the hop
7042 : // checks for itself. false sends the hop to the retry path.
7043 189 : static bool async_reused_conn_is_clean(chttp_async_ctx *ctx) {
7044 189 : ctx->reuse_checked = true;
7045 189 : if (ctx->idle_tainted) return false;
7046 187 : char probe;
7047 187 : ssize_t pn;
7048 187 : if (ctx->tls) {
7049 58 : pn = ctls_conn_read(ctx->tls, &probe, 1);
7050 : } else {
7051 129 : do {
7052 129 : pn = recv(ctx->fd, &probe, 1, MSG_PEEK | MSG_DONTWAIT);
7053 129 : } while (pn < 0 && errno == EINTR);
7054 : }
7055 205 : return pn < 0 && (errno == EAGAIN || errno == EWOULDBLOCK);
7056 : }
7057 :
7058 : // Starts or continues the send of a ctx in CHTTP_ASYNC_WRITING (TLS or plain).
7059 : // It can free ctx, so it's the caller's last action.
7060 916 : static void async_drive_write(chttp_async_ctx *ctx) {
7061 1105 : if (ctx->reused && !ctx->reuse_checked && ctx->wire_sent == 0 &&
7062 189 : !async_reused_conn_is_clean(ctx)) {
7063 20 : async_ctx_finish(ctx);
7064 20 : return;
7065 : }
7066 896 : if (ctx->tls) {
7067 59 : async_tls_try_write(ctx);
7068 : } else {
7069 837 : async_plain_try_write(ctx);
7070 : }
7071 : }
7072 :
7073 : // Finishes a write-direction dispatch for a ctx with nothing of ours to flush
7074 : // there: It turns the registration back to reading (or leaves an idle ctx
7075 : // alone), reading the state again under idle_lock so a take that moved the ctx
7076 : // to WRITING is never driven half-built.
7077 3 : static void async_writable_rest(chttp_async_ctx *ctx) {
7078 3 : ccol__mutex_lock(ctx->idle_lock);
7079 3 : chttp_async_state resting_state = ctx->state;
7080 3 : bool restore = (resting_state == CHTTP_ASYNC_READING ||
7081 : resting_state == CHTTP_ASYNC_IDLE);
7082 8 : ccol_retval mrv = restore ? ceventloop_modify(cli_engine_bundler.reactor,
7083 2 : ctx->reg, cselect_read)
7084 3 : : ccol_success;
7085 3 : ccol__mutex_unlock(ctx->idle_lock);
7086 : #ifdef RUNNING_UNIT_TESTS
7087 3 : if (restore)
7088 2 : atomic_fetch_add_explicit(&g_stray_write_arm_restores_for_tests, 1,
7089 : memory_order_relaxed);
7090 : #endif
7091 3 : if (mrv != ccol_success && resting_state == CHTTP_ASYNC_READING)
7092 0 : async_ctx_finish(ctx);
7093 3 : }
7094 :
7095 : // Handles a write-direction dispatch: The connect result, the TLS handshake,
7096 : // the request send, a stray flip from the sweep, and a TLS read that asked for
7097 : // the write direction. It returns at once for a completed hop and adopts reg
7098 : // first, since this can be the very first dispatch.
7099 1020 : static void async_on_writable_impl(ceventloop loop, ceventloop_reg reg,
7100 : cselectable *sel, chttp_async_ctx *ctx) {
7101 1020 : (void)loop;
7102 1020 : (void)sel;
7103 1020 : atomic_store(&ctx->last_io_ns, monotonic_now_ns());
7104 1021 : if (ctx->hop_completed) {
7105 0 : async_ctx_handle_if_abandoned(ctx);
7106 0 : return;
7107 : }
7108 1021 : async_adopt_reg(ctx, reg);
7109 :
7110 1021 : chttp_async_dispatch_kind kind = async_dispatch_kind(ctx);
7111 1022 : if (kind == CHTTP_ASYNC_DISPATCH_ABANDONED) {
7112 0 : async_ctx_handle_if_abandoned(ctx);
7113 0 : return;
7114 : }
7115 : #ifdef RUNNING_UNIT_TESTS
7116 1022 : if (kind == CHTTP_ASYNC_DISPATCH_IDLE) {
7117 2 : int stray_stage = 2;
7118 2 : if (atomic_compare_exchange_strong(&g_stray_before_take_stage_for_tests,
7119 : &stray_stage, 3))
7120 1 : stray_before_take_wait_for_tests(4);
7121 : }
7122 : #endif
7123 1022 : if (kind == CHTTP_ASYNC_DISPATCH_IDLE) {
7124 2 : async_writable_rest(ctx);
7125 2 : return;
7126 : }
7127 :
7128 1020 : if (ctx->state == CHTTP_ASYNC_CONNECTING) {
7129 820 : int soerr = 0;
7130 820 : socklen_t slen = sizeof(soerr);
7131 820 : if (getsockopt(ctx->fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) != 0 ||
7132 819 : soerr != 0) {
7133 3 : async_connect_failed(ctx);
7134 107 : return;
7135 : }
7136 816 : ccol__mem_free(ctx->mp, ctx->addrs);
7137 819 : ctx->addrs = NULL;
7138 819 : if (!ctx->is_unix) apply_tcp_nodelay(ctx->fd);
7139 :
7140 816 : if (ctx->is_https) {
7141 : #ifdef RUNNING_UNIT_TESTS
7142 101 : if (ctx->tls_generation != ctx->chain->tls_generation) {
7143 0 : ccol__fatal_err(
7144 : "chttpclient: a fresh TLS connection carries a tls_generation "
7145 : "other than its own chain's");
7146 : }
7147 : #endif
7148 101 : ccol_retval crv;
7149 202 : ctx->tls = tls_client_create(ctx->chain->tls_ctx, ctx->fd, ctx->host,
7150 101 : ctx->verify_host, &crv);
7151 101 : if (!ctx->tls) {
7152 0 : async_fulfill(ctx, crv, NULL);
7153 0 : async_ctx_finish(ctx);
7154 0 : return;
7155 : }
7156 101 : ctx->state = CHTTP_ASYNC_TLS_HANDSHAKING;
7157 101 : async_tls_advance(ctx);
7158 101 : return;
7159 : }
7160 :
7161 715 : ctx->state = CHTTP_ASYNC_WRITING;
7162 : }
7163 :
7164 915 : if (ctx->state == CHTTP_ASYNC_TLS_HANDSHAKING) {
7165 0 : async_tls_advance(ctx);
7166 0 : return;
7167 : }
7168 :
7169 915 : if (ctx->state == CHTTP_ASYNC_WRITING) {
7170 909 : async_drive_write(ctx);
7171 909 : return;
7172 : }
7173 6 : if (ctx->state == CHTTP_ASYNC_AWAITING_CONTINUE) {
7174 4 : if (atomic_load(&ctx->continue_msg_started)) {
7175 0 : if (async_reg_modify(ctx, cselect_read) != ccol_success)
7176 0 : async_ctx_finish(ctx);
7177 0 : return;
7178 : }
7179 : {
7180 4 : ccol__mutex_lock(ctx->deadline_lock);
7181 4 : chttp_deadline own_dl = ctx->continue_deadline;
7182 4 : ccol__mutex_unlock(ctx->deadline_lock);
7183 4 : int own_ms;
7184 4 : if (deadline_remaining_ms(&own_dl, &own_ms)) {
7185 1 : if (async_reg_modify(ctx, cselect_read) != ccol_success)
7186 0 : async_ctx_finish(ctx);
7187 1 : return;
7188 : }
7189 : }
7190 3 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7191 3 : ctx->interim_responses_seen = 0;
7192 3 : ctx->state = CHTTP_ASYNC_WRITING;
7193 3 : if (ctx->tls) {
7194 0 : async_tls_try_write(ctx);
7195 : } else {
7196 3 : async_plain_try_write(ctx);
7197 : }
7198 3 : return;
7199 : }
7200 2 : if (ctx->state == CHTTP_ASYNC_READING && ctx->upload_paused &&
7201 0 : (ctx->duplex || async_upload_may_resume(ctx))) {
7202 0 : async_upload_resume(ctx);
7203 0 : return;
7204 : }
7205 2 : if (ctx->state == CHTTP_ASYNC_READING && ctx->tls) {
7206 1 : if (async_reg_modify(ctx, cselect_read) != ccol_success) {
7207 0 : async_ctx_finish(ctx);
7208 0 : return;
7209 : }
7210 1 : async_on_readable_impl(loop, reg, sel, ctx);
7211 1 : return;
7212 : }
7213 :
7214 1 : async_writable_rest(ctx);
7215 : }
7216 :
7217 : // Thin ceventloop callbacks that cast arg back to the ctx and call the _impl
7218 : // function. They take no reference: The reactor's dispatch lock and the single
7219 : // teardown point keep the ctx alive during a dispatch.
7220 1020 : static void async_on_writable(ceventloop loop, ceventloop_reg reg,
7221 : cselectable *sel, void *arg) {
7222 1020 : async_on_writable_impl(loop, reg, sel, (chttp_async_ctx *)arg);
7223 1021 : }
7224 :
7225 : // Parses response bytes in the READING state, from a socket read or from the
7226 : // replay of the 100-continue carry. It skips interim responses, refuses a
7227 : // response that broke a cap, and on a complete message offers or closes the
7228 : // connection and then follows a redirect or fulfils the future. It can free
7229 : // ctx.
7230 5258 : static void async_process_reading_data(chttp_async_ctx *ctx, const char *data,
7231 : size_t data_len) {
7232 5688 : for (;;) {
7233 5473 : if (data_len > 0) {
7234 5473 : ctx->resp_msg_started = true;
7235 5473 : if (ctx->upload_paused) ctx->answered_early = true;
7236 : }
7237 5473 : chttp1_errno err = chttp1_parser_execute(&ctx->parser, data, data_len);
7238 5468 : if (err == CHTTP1_PAUSED) {
7239 1133 : size_t consumed = chttp1_parser_consumed(&ctx->parser);
7240 1133 : bool trailing_this_msg = consumed < data_len;
7241 :
7242 1133 : if (ctx->pctx.status_code >= 100 && ctx->pctx.status_code < 200) {
7243 243 : if (++ctx->interim_responses_seen > CHTTP_MAX_INTERIM_RESPONSES) {
7244 2 : ctx->hop_completed = true;
7245 2 : async_fulfill(ctx, ccol_http_transfer_aborted, NULL);
7246 2 : async_ctx_finish(ctx);
7247 2 : return;
7248 : }
7249 241 : ccol_retval rrv = parse_ctx_reset_for_continue(&ctx->pctx);
7250 241 : if (rrv != ccol_success) {
7251 0 : ctx->hop_completed = true;
7252 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
7253 0 : async_ctx_finish(ctx);
7254 0 : return;
7255 : }
7256 241 : async_parser_start(ctx);
7257 241 : ctx->resp_msg_started = false;
7258 241 : ctx->answered_early = false;
7259 241 : if (!trailing_this_msg) {
7260 26 : if (ctx->upload_paused) async_upload_resume(ctx);
7261 26 : return;
7262 : }
7263 215 : data += consumed;
7264 215 : data_len -= consumed;
7265 215 : continue;
7266 : }
7267 :
7268 890 : ctx->hop_completed = true;
7269 890 : if (trailing_this_msg) ctx->pctx.trailing_garbage = true;
7270 890 : bool keep_alive = chttp1_should_keep_alive(&ctx->parser) &&
7271 890 : !ctx->pctx.trailing_garbage && async_request_sent(ctx);
7272 :
7273 890 : if (ctx->pctx.will_redirect) {
7274 119 : async_handle_redirect(ctx, keep_alive);
7275 : } else {
7276 771 : chttp_async_chain *chain = ctx->chain;
7277 771 : async_chain_retain(chain);
7278 771 : chttpcli_response *resp = async_build_response(ctx);
7279 770 : async_finish_connection(ctx, keep_alive);
7280 773 : async_fulfill_chain(chain, resp ? ccol_success : ccol_not_enough_memory,
7281 : resp);
7282 771 : async_chain_release(chain);
7283 : }
7284 890 : return;
7285 : }
7286 4335 : if (err == CHTTP1_USER) {
7287 18 : ctx->hop_completed = true;
7288 18 : async_fulfill(ctx,
7289 18 : ctx->pctx.too_large
7290 : ? ccol_msg_too_large
7291 16 : : (ctx->pctx.error ? ccol_not_enough_memory
7292 : : ccol_http_transfer_aborted),
7293 : NULL);
7294 18 : async_ctx_finish(ctx);
7295 18 : return;
7296 : }
7297 4317 : if (err != CHTTP1_OK) {
7298 4 : ctx->hop_completed = true;
7299 4 : async_fulfill(ctx, ccol_http_transfer_aborted, NULL);
7300 4 : async_ctx_finish(ctx);
7301 4 : return;
7302 : }
7303 4313 : if (ctx->upload_paused && ctx->pctx.status_code >= 200) {
7304 3521 : if (ctx->pctx.status_code < 300) {
7305 3521 : async_upload_resume(ctx);
7306 3521 : return;
7307 : }
7308 0 : ctx->upload_paused = false;
7309 : }
7310 : return;
7311 : }
7312 : }
7313 :
7314 : // Handles bytes that arrive while the body waits for a "100 Continue", the
7315 : // event-driven form of Tier 1's chttp_send_and_read wait. A "100 Continue"
7316 : // sends the body (after claiming continue_decided against the timeout path);
7317 : // any other message is the response, and the body is never sent. It can free
7318 : // ctx.
7319 29 : static void async_awaiting_continue_on_data(chttp_async_ctx *ctx,
7320 : const char *data, size_t data_len) {
7321 103 : for (;;) {
7322 66 : if (data_len > 0) atomic_store(&ctx->continue_msg_started, true);
7323 66 : chttp1_errno err = chttp1_parser_execute(&ctx->parser, data, data_len);
7324 66 : if (err == CHTTP1_PAUSED) {
7325 60 : size_t consumed = chttp1_parser_consumed(&ctx->parser);
7326 60 : bool trailing_this_msg = consumed < data_len;
7327 :
7328 60 : if (ctx->pctx.status_code == 100) {
7329 13 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7330 :
7331 13 : ccol_retval rrv = parse_ctx_reset_for_continue(&ctx->pctx);
7332 13 : if (rrv != ccol_success) {
7333 0 : ctx->hop_completed = true;
7334 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
7335 0 : async_ctx_finish(ctx);
7336 0 : return;
7337 : }
7338 13 : async_parser_start(ctx);
7339 13 : ctx->retry_unsafe = true;
7340 13 : ctx->interim_responses_seen = 0;
7341 :
7342 13 : if (trailing_this_msg) {
7343 8 : ctx->continue_carry =
7344 4 : (char *)ccol__mem_alloc(ctx->mp, data_len - consumed);
7345 4 : if (!ctx->continue_carry) {
7346 0 : ctx->hop_completed = true;
7347 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
7348 0 : async_ctx_finish(ctx);
7349 0 : return;
7350 : }
7351 4 : memcpy(ctx->continue_carry, data + consumed, data_len - consumed);
7352 4 : ctx->continue_carry_len = data_len - consumed;
7353 4 : async_upload_pause(ctx, true);
7354 4 : return;
7355 : }
7356 :
7357 9 : ctx->state = CHTTP_ASYNC_WRITING;
7358 9 : if (ctx->tls) {
7359 0 : async_tls_try_write(ctx);
7360 : } else {
7361 9 : async_plain_try_write(ctx);
7362 : }
7363 9 : return;
7364 : }
7365 :
7366 47 : if (ctx->pctx.status_code >= 100 && ctx->pctx.status_code < 200) {
7367 41 : if (++ctx->interim_responses_seen > CHTTP_MAX_INTERIM_RESPONSES) {
7368 0 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7369 0 : ctx->hop_completed = true;
7370 0 : async_fulfill(ctx, ccol_http_transfer_aborted, NULL);
7371 0 : async_ctx_finish(ctx);
7372 0 : return;
7373 : }
7374 41 : ccol_retval rrv = parse_ctx_reset_for_continue(&ctx->pctx);
7375 41 : if (rrv != ccol_success) {
7376 0 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7377 0 : ctx->hop_completed = true;
7378 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
7379 0 : async_ctx_finish(ctx);
7380 0 : return;
7381 : }
7382 41 : async_parser_start(ctx);
7383 41 : if (!trailing_this_msg) {
7384 4 : atomic_store(&ctx->continue_msg_started, false);
7385 4 : return;
7386 : }
7387 37 : data += consumed;
7388 37 : data_len -= consumed;
7389 37 : continue;
7390 : }
7391 :
7392 6 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7393 6 : ctx->hop_completed = true;
7394 6 : if (trailing_this_msg) ctx->pctx.trailing_garbage = true;
7395 6 : if (ctx->pctx.will_redirect) {
7396 0 : async_handle_redirect(ctx, false);
7397 : } else {
7398 6 : chttp_async_chain *chain = ctx->chain;
7399 6 : async_chain_retain(chain);
7400 6 : chttpcli_response *resp = async_build_response(ctx);
7401 6 : async_finish_connection(ctx, false);
7402 6 : async_fulfill_chain(chain, resp ? ccol_success : ccol_not_enough_memory,
7403 : resp);
7404 6 : async_chain_release(chain);
7405 : }
7406 6 : return;
7407 : }
7408 6 : if (err == CHTTP1_USER) {
7409 2 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7410 2 : ctx->hop_completed = true;
7411 2 : async_fulfill(ctx,
7412 2 : ctx->pctx.too_large
7413 : ? ccol_msg_too_large
7414 2 : : (ctx->pctx.error ? ccol_not_enough_memory
7415 : : ccol_http_transfer_aborted),
7416 : NULL);
7417 2 : async_ctx_finish(ctx);
7418 2 : return;
7419 : }
7420 4 : if (err != CHTTP1_OK) {
7421 0 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7422 0 : ctx->hop_completed = true;
7423 0 : async_fulfill(ctx, ccol_http_transfer_aborted, NULL);
7424 0 : async_ctx_finish(ctx);
7425 0 : return;
7426 : }
7427 : return;
7428 : }
7429 : }
7430 :
7431 : // Handles a read-direction dispatch: An idle pooled connection (evicted on any
7432 : // input or EOF), the TLS handshake, the 100-continue wait and the response
7433 : // read, with the TLS layer drained before a wait. It reaps a teardown left for
7434 : // the dispatch, and checks the request deadline before each read.
7435 5871 : static void async_on_readable_impl(ceventloop loop, ceventloop_reg reg,
7436 : cselectable *sel, chttp_async_ctx *ctx) {
7437 5871 : (void)loop;
7438 5871 : (void)sel;
7439 5871 : atomic_store(&ctx->last_io_ns, monotonic_now_ns());
7440 :
7441 5871 : if (ctx->hop_completed) {
7442 5 : async_ctx_handle_if_abandoned(ctx);
7443 593 : return;
7444 : }
7445 5866 : async_adopt_reg(ctx, reg);
7446 :
7447 5866 : chttp_async_dispatch_kind kind = async_dispatch_kind(ctx);
7448 5865 : if (kind == CHTTP_ASYNC_DISPATCH_ABANDONED) {
7449 0 : async_ctx_handle_if_abandoned(ctx);
7450 0 : return;
7451 : }
7452 5865 : if (kind == CHTTP_ASYNC_DISPATCH_IDLE) {
7453 : #ifdef RUNNING_UNIT_TESTS
7454 347 : chttp_test_idle_probe_hold(ctx->fd);
7455 : #endif
7456 347 : char peek_buf[1];
7457 347 : ssize_t pn;
7458 347 : if (ctx->tls) {
7459 67 : pn = ctls_conn_read(ctx->tls, peek_buf, sizeof(peek_buf));
7460 : } else {
7461 280 : do {
7462 280 : pn = recv(ctx->fd, peek_buf, sizeof(peek_buf), 0);
7463 279 : } while (pn < 0 && errno == EINTR);
7464 : }
7465 346 : if (pn < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
7466 : return;
7467 : }
7468 345 : ctx->idle_tainted = true;
7469 345 : async_idle_ctx_finish(ctx);
7470 345 : return;
7471 : }
7472 :
7473 5518 : if (ctx->state == CHTTP_ASYNC_TLS_HANDSHAKING) {
7474 100 : async_tls_advance(ctx);
7475 100 : return;
7476 : }
7477 :
7478 5418 : if (ctx->state == CHTTP_ASYNC_WRITING) {
7479 7 : async_drive_write(ctx);
7480 7 : return;
7481 : }
7482 :
7483 10807 : if (ctx->timed_out ||
7484 5396 : read_deadline_passed(&ctx->chain->overall_deadline, ctx->fd)) {
7485 18 : if (ctx->state == CHTTP_ASYNC_AWAITING_CONTINUE &&
7486 0 : atomic_exchange(&ctx->continue_decided, true))
7487 : return;
7488 18 : ctx->timed_out = true;
7489 18 : ctx->hop_completed = true;
7490 18 : async_fulfill(ctx, ccol_timed_out, NULL);
7491 18 : async_ctx_finish(ctx);
7492 18 : return;
7493 : }
7494 :
7495 5393 : char buf[16384];
7496 5393 : char *data = buf;
7497 5393 : char *heap_data = NULL;
7498 5393 : bool drain_oom = false;
7499 5393 : bool drain_timed_out = false;
7500 5393 : ssize_t n = 0;
7501 5393 : bool eof = false;
7502 5393 : bool hard_error = false;
7503 5393 : bool injected = false;
7504 :
7505 : #ifdef RUNNING_UNIT_TESTS
7506 5393 : if (ctx->any_bytes_read &&
7507 4354 : atomic_exchange(&g_force_async_hard_read_error_for_tests, false)) {
7508 5393 : hard_error = true;
7509 5393 : injected = true;
7510 : }
7511 : #endif
7512 :
7513 5393 : if (!injected) {
7514 5392 : if (ctx->tls) {
7515 : #ifdef RUNNING_UNIT_TESTS
7516 249 : if (tls_dir_inject_blocks(false)) {
7517 1 : errno = EWOULDBLOCK;
7518 1 : n = -1;
7519 : } else
7520 : #endif
7521 : {
7522 248 : size_t first_len = sizeof(buf);
7523 : #ifdef RUNNING_UNIT_TESTS
7524 248 : size_t cap = atomic_load(&g_async_tls_first_read_cap_for_tests);
7525 248 : if (cap > 0 && cap < first_len) first_len = cap;
7526 : #endif
7527 248 : n = ctls_conn_read(ctx->tls, buf, first_len);
7528 : }
7529 1 : ctx->tls_read_blocked =
7530 250 : n < 0 && (errno == EWOULDBLOCK || errno == EAGAIN);
7531 250 : if (n < 0) {
7532 86 : if (errno == EWOULDBLOCK || errno == EAGAIN) {
7533 84 : if (ctx->state == CHTTP_ASYNC_READING &&
7534 84 : async_upload_may_resume(ctx)) {
7535 4 : async_upload_resume(ctx);
7536 4 : return;
7537 : }
7538 160 : if (ctx->state == CHTTP_ASYNC_READING &&
7539 80 : conn_tls_wants_write(ctx->tls)) {
7540 : #ifdef RUNNING_UNIT_TESTS
7541 1 : atomic_fetch_add(&g_tls_dir_write_interest_while_reading, 1u);
7542 1 : tls_dir_note_wait(true);
7543 : #endif
7544 1 : if (async_reg_modify(ctx, cselect_write) != ccol_success) {
7545 0 : async_ctx_finish(ctx);
7546 : }
7547 : }
7548 80 : return;
7549 : }
7550 : hard_error = true;
7551 : } else {
7552 164 : eof = (n == 0);
7553 : }
7554 166 : if (n > 0) {
7555 162 : size_t total = (size_t)n;
7556 162 : size_t cap = sizeof(buf);
7557 164 : while (ctls_conn_has_pending_input(ctx->tls)) {
7558 2 : if (total == cap) {
7559 0 : size_t ncap = cap * 2;
7560 162 : char *nb =
7561 0 : (ncap > cap) ? (char *)ccol__mem_alloc(ctx->mp, ncap) : NULL;
7562 0 : if (!nb) {
7563 : drain_oom = true;
7564 : break;
7565 : }
7566 0 : memcpy(nb, data, total);
7567 0 : ccol__mem_free(ctx->mp, heap_data);
7568 : heap_data = nb;
7569 : data = nb;
7570 : cap = ncap;
7571 : }
7572 2 : if (read_deadline_passed(&ctx->chain->overall_deadline, ctx->fd)) {
7573 : drain_timed_out = true;
7574 : break;
7575 : }
7576 2 : ssize_t m = ctls_conn_read(ctx->tls, data + total, cap - total);
7577 2 : if (m <= 0) {
7578 0 : ctx->tls_read_blocked =
7579 0 : m < 0 && (errno == EWOULDBLOCK || errno == EAGAIN);
7580 0 : break;
7581 : }
7582 2 : total += (size_t)m;
7583 : }
7584 162 : n = (ssize_t)total;
7585 : }
7586 : } else {
7587 5143 : do {
7588 5143 : n = recv(ctx->fd, buf, sizeof(buf), 0);
7589 5143 : } while (n < 0 && errno == EINTR);
7590 5143 : if (n < 0) {
7591 4 : if (errno == EWOULDBLOCK || errno == EAGAIN) {
7592 0 : if (ctx->state == CHTTP_ASYNC_READING && async_upload_may_resume(ctx))
7593 0 : async_upload_resume(ctx);
7594 0 : return;
7595 : }
7596 : hard_error = true;
7597 : } else {
7598 5139 : eof = (n == 0);
7599 : }
7600 : }
7601 : }
7602 5310 : if (n > 0) ctx->any_bytes_read = true;
7603 :
7604 5310 : if (hard_error) {
7605 7 : async_ctx_finish(ctx);
7606 7 : return;
7607 : }
7608 :
7609 5303 : if (eof) {
7610 20 : chttp1_errno fe = chttp1_parser_finish(&ctx->parser);
7611 20 : bool ok = ((fe == CHTTP1_OK || fe == CHTTP1_PAUSED) &&
7612 3 : ctx->pctx.message_complete);
7613 20 : if (!ok) {
7614 17 : async_ctx_finish(ctx);
7615 17 : return;
7616 : }
7617 3 : if (ctx->state == CHTTP_ASYNC_AWAITING_CONTINUE) {
7618 0 : if (atomic_exchange(&ctx->continue_decided, true)) return;
7619 : }
7620 3 : ctx->hop_completed = true;
7621 3 : if (ctx->pctx.will_redirect) {
7622 0 : async_handle_redirect(ctx, false);
7623 : } else {
7624 3 : async_fulfill_success(ctx);
7625 3 : async_ctx_finish(ctx);
7626 : }
7627 3 : return;
7628 : }
7629 :
7630 5283 : if (drain_timed_out) {
7631 0 : ccol__mem_free(ctx->mp, heap_data);
7632 0 : if (ctx->state == CHTTP_ASYNC_AWAITING_CONTINUE &&
7633 0 : atomic_exchange(&ctx->continue_decided, true))
7634 : return;
7635 0 : ctx->timed_out = true;
7636 0 : ctx->hop_completed = true;
7637 0 : async_fulfill(ctx, ccol_timed_out, NULL);
7638 0 : async_ctx_finish(ctx);
7639 0 : return;
7640 : }
7641 :
7642 5283 : if (drain_oom) {
7643 0 : ccol__mem_free(ctx->mp, heap_data);
7644 0 : if (ctx->state == CHTTP_ASYNC_AWAITING_CONTINUE &&
7645 0 : atomic_exchange(&ctx->continue_decided, true))
7646 : return;
7647 0 : ctx->hop_completed = true;
7648 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
7649 0 : async_ctx_finish(ctx);
7650 0 : return;
7651 : }
7652 :
7653 5283 : ccol_memmgmt_procs data_procs;
7654 5283 : ccol_memmgmt_procs *data_mp = NULL;
7655 5283 : if (heap_data && ctx->mp) {
7656 0 : data_procs = *ctx->mp;
7657 0 : data_mp = &data_procs;
7658 : }
7659 5283 : if (ctx->state == CHTTP_ASYNC_AWAITING_CONTINUE) {
7660 29 : async_awaiting_continue_on_data(ctx, data, (size_t)n);
7661 : } else {
7662 5254 : async_process_reading_data(ctx, data, (size_t)n);
7663 : }
7664 5278 : ccol__mem_free(data_mp, heap_data);
7665 : }
7666 :
7667 : // The read callback of a hop's registration; see async_on_writable.
7668 5870 : static void async_on_readable(ceventloop loop, ceventloop_reg reg,
7669 : cselectable *sel, void *arg) {
7670 5870 : async_on_readable_impl(loop, reg, sel, (chttp_async_ctx *)arg);
7671 5865 : }
7672 :
7673 : // Handles an error or hang-up dispatch: Evicts an idle connection, ends a
7674 : // failed connect, and otherwise ends the hop with a transfer or connect error
7675 : // (a timeout when the sweep marked it), retrying a reused connection once.
7676 1 : static void async_on_error_impl(ceventloop loop, ceventloop_reg reg,
7677 : cselectable *sel, chttp_async_ctx *ctx) {
7678 1 : (void)loop;
7679 1 : (void)sel;
7680 1 : atomic_store(&ctx->last_io_ns, monotonic_now_ns());
7681 1 : if (ctx->hop_completed) {
7682 0 : async_ctx_handle_if_abandoned(ctx);
7683 0 : return;
7684 : }
7685 1 : async_adopt_reg(ctx, reg);
7686 1 : chttp_async_dispatch_kind kind = async_dispatch_kind(ctx);
7687 1 : if (kind == CHTTP_ASYNC_DISPATCH_ABANDONED) {
7688 0 : async_ctx_handle_if_abandoned(ctx);
7689 0 : return;
7690 : }
7691 1 : if (kind == CHTTP_ASYNC_DISPATCH_IDLE) {
7692 0 : async_idle_ctx_finish(ctx);
7693 0 : return;
7694 : }
7695 1 : if (ctx->state == CHTTP_ASYNC_CONNECTING) {
7696 1 : async_connect_failed(ctx);
7697 1 : return;
7698 : }
7699 0 : if (ctx->state == CHTTP_ASYNC_TLS_HANDSHAKING) {
7700 0 : long vr = ctx->tls ? ctls_conn_verify_result(ctx->tls) : 0;
7701 0 : async_fulfill(ctx,
7702 : ctx->timed_out
7703 0 : ? ccol_timed_out
7704 0 : : (vr != 0 ? ccol_http_tls_cert_verification_failed
7705 : : ccol_http_tls_handshake_failed),
7706 : NULL);
7707 0 : async_ctx_finish(ctx);
7708 0 : return;
7709 : }
7710 0 : async_ctx_finish(ctx);
7711 : }
7712 :
7713 : // The error callback of a hop's registration; see async_on_writable.
7714 1 : static void async_on_error(ceventloop loop, ceventloop_reg reg,
7715 : cselectable *sel, void *arg) {
7716 1 : async_on_error_impl(loop, reg, sel, (chttp_async_ctx *)arg);
7717 1 : }
7718 :
7719 : // Async Happy Eyeballs
7720 : //
7721 : // A TCP target with several addresses connects through a race of attempts, each
7722 : // a socket with its own registration whose arg is the attempt. The first to
7723 : // connect hands its fd to the ctx, which registers it; the losers are closed.
7724 : // The race is refcounted (the ctx and each registration), and lock guards it.
7725 : typedef struct chttp_connect_race_s chttp_connect_race;
7726 :
7727 : // One attempt of a race.
7728 : typedef struct {
7729 : chttp_connect_race *race;
7730 : int fd;
7731 : ceventloop_reg reg;
7732 : } chttp_connect_attempt;
7733 :
7734 : // The race of one hop.
7735 : struct chttp_connect_race_s {
7736 : ccol__mutex lock;
7737 : ccol_memmgmt_procs procs;
7738 : bool has_procs;
7739 : int refs;
7740 : chttp_async_ctx *ctx;
7741 : bool decided;
7742 : size_t pending;
7743 : size_t next;
7744 : struct timespec next_start;
7745 : chttp_addr_list *addrs;
7746 : chttp_connect_attempt attempts[];
7747 : };
7748 :
7749 : static void async_connect_register(chttp_async_ctx *ctx, int fd);
7750 :
7751 : // Drops one race reference, and frees the race with the last one, so neither
7752 : // the ctx nor a late attempt dispatch frees it early.
7753 78 : static void async_race_release(chttp_connect_race *r) {
7754 78 : ccol__mutex_lock(r->lock);
7755 78 : bool last = (--r->refs == 0);
7756 78 : ccol__mutex_unlock(r->lock);
7757 78 : if (!last) return;
7758 26 : ccol_memmgmt_procs procs = r->procs;
7759 26 : ccol_memmgmt_procs *mp = r->has_procs ? &procs : NULL;
7760 26 : ccol__mutex_destroy(r->lock);
7761 26 : ccol__mem_free(mp, r->addrs);
7762 26 : ccol__mem_free(mp, r);
7763 : }
7764 :
7765 : // Drops the race reference of an attempt's registration once the reactor has
7766 : // removed it (its on_removed callback).
7767 52 : static void async_race_on_removed(void *arg) {
7768 52 : async_race_release(((chttp_connect_attempt *)arg)->race);
7769 52 : }
7770 :
7771 : // Closes one attempt, removing the registration before the close so the fd
7772 : // number can't reach another socket while the reactor watches it. The caller
7773 : // holds r->lock.
7774 52 : static void async_race_close_attempt_locked(chttp_connect_race *r,
7775 : chttp_connect_attempt *a) {
7776 52 : if (a->reg) {
7777 30 : ceventloop_remove(cli_engine_bundler.reactor, a->reg);
7778 30 : a->reg = CEVENTLOOP_REG_NULL;
7779 : }
7780 52 : if (a->fd >= 0) {
7781 30 : close(a->fd);
7782 30 : a->fd = -1;
7783 30 : r->pending--;
7784 : }
7785 52 : }
7786 :
7787 : static void async_race_on_event(ceventloop loop, ceventloop_reg reg,
7788 : cselectable *sel, void *arg);
7789 :
7790 : // Starts the next candidate that accepts a connect and registers it; one that
7791 : // fails on the spot makes way for the next. The caller holds r->lock.
7792 54 : static void async_race_launch_locked(chttp_connect_race *r) {
7793 54 : while (r->next < r->addrs->count) {
7794 52 : size_t idx = r->next++;
7795 52 : bool in_progress = false;
7796 52 : int fd = addr_connect_start(&r->addrs->addrs[idx], &in_progress);
7797 52 : if (fd < 0) continue;
7798 52 : chttp_connect_attempt *a = &r->attempts[idx];
7799 52 : ceventloop_handlers handlers = {
7800 : .on_writable = async_race_on_event,
7801 : .on_error = async_race_on_event,
7802 : .on_removed = async_race_on_removed,
7803 : };
7804 52 : char *err = NULL;
7805 52 : ceventloop_reg reg =
7806 104 : ceventloop_add(cli_engine_bundler.reactor,
7807 52 : cselectable_fd(fd, cselect_write), handlers, a, &err);
7808 52 : if (!reg) {
7809 0 : close(fd);
7810 0 : continue;
7811 : }
7812 52 : a->fd = fd;
7813 52 : a->reg = reg;
7814 52 : r->refs++;
7815 52 : r->pending++;
7816 52 : struct timespec now;
7817 52 : clock_gettime(CLOCK_MONOTONIC, &now);
7818 52 : r->next_start = timespec_add_ms(now, connect_attempt_delay_ms());
7819 52 : if (r->next < r->addrs->count)
7820 52 : client_deadline_note_ns(timespec_to_ns(&r->next_start));
7821 52 : return;
7822 : }
7823 : }
7824 :
7825 : // Decides the race for winner (NULL for nobody) and closes the other attempts,
7826 : // so exactly one fd reaches the ctx. Gives the ctx to act on; the caller holds
7827 : // r->lock, releases it, and then acts.
7828 22 : static chttp_async_ctx *async_race_decide_locked(
7829 : chttp_connect_race *r, chttp_connect_attempt *winner) {
7830 78 : for (size_t i = 0; i < r->addrs->count; i++) {
7831 52 : chttp_connect_attempt *a = &r->attempts[i];
7832 52 : if (a != winner) async_race_close_attempt_locked(r, a);
7833 : }
7834 26 : r->decided = true;
7835 26 : chttp_async_ctx *ctx = r->ctx;
7836 26 : r->ctx = NULL;
7837 26 : return ctx;
7838 : }
7839 :
7840 : // An attempt's dispatch: A connected attempt wins and hands its fd to the ctx;
7841 : // a failed one makes way for the next candidate, and the last failure ends the
7842 : // hop.
7843 44 : static void async_race_on_event(ceventloop loop, ceventloop_reg reg,
7844 : cselectable *sel, void *arg) {
7845 44 : (void)loop;
7846 44 : (void)reg;
7847 44 : (void)sel;
7848 44 : chttp_connect_attempt *a = (chttp_connect_attempt *)arg;
7849 44 : chttp_connect_race *r = a->race;
7850 44 : ccol__mutex_lock(r->lock);
7851 44 : if (r->decided || a->fd < 0) {
7852 0 : ccol__mutex_unlock(r->lock);
7853 40 : return;
7854 : }
7855 44 : int soerr = 0;
7856 44 : socklen_t slen = sizeof(soerr);
7857 44 : if (getsockopt(a->fd, SOL_SOCKET, SO_ERROR, &soerr, &slen) == 0 &&
7858 44 : soerr == 0) {
7859 22 : int fd = a->fd;
7860 22 : ceventloop_remove(cli_engine_bundler.reactor, a->reg);
7861 22 : a->reg = CEVENTLOOP_REG_NULL;
7862 22 : a->fd = -1;
7863 22 : r->pending--;
7864 22 : chttp_async_ctx *ctx = async_race_decide_locked(r, a);
7865 22 : ccol__mutex_unlock(r->lock);
7866 22 : async_connect_register(ctx, fd);
7867 22 : return;
7868 : }
7869 22 : async_race_close_attempt_locked(r, a);
7870 22 : chttp_async_ctx *ctx = r->ctx;
7871 22 : if (!ctx->timed_out) async_race_launch_locked(r);
7872 22 : if (r->pending > 0) {
7873 18 : ccol__mutex_unlock(r->lock);
7874 18 : return;
7875 : }
7876 4 : ctx = async_race_decide_locked(r, NULL);
7877 4 : ccol__mutex_unlock(r->lock);
7878 4 : async_fulfill(
7879 4 : ctx, ctx->timed_out ? ccol_timed_out : ccol_http_connection_failed, NULL);
7880 4 : async_ctx_teardown(ctx);
7881 : }
7882 :
7883 : // Called by the sweep, under the ctx's stripe lock, for a ctx with a running
7884 : // race. An expired connect deadline shuts every attempt down (they fail through
7885 : // their own dispatch); otherwise the next candidate starts once its delay is
7886 : // over. Gives the next instant the race needs the sweep.
7887 40 : static uint64_t async_race_tick(chttp_connect_race *r, bool expired) {
7888 40 : uint64_t next_ns = UINT64_MAX;
7889 40 : ccol__mutex_lock(r->lock);
7890 40 : if (!r->decided) {
7891 40 : if (expired || (r->ctx && r->ctx->timed_out)) {
7892 6 : for (size_t i = 0; i < r->addrs->count; i++)
7893 4 : if (r->attempts[i].fd >= 0) shutdown(r->attempts[i].fd, SHUT_RDWR);
7894 38 : } else if (r->next < r->addrs->count) {
7895 30 : struct timespec now;
7896 30 : clock_gettime(CLOCK_MONOTONIC, &now);
7897 60 : if (ms_until(&r->next_start, &now) == 0) {
7898 : #ifdef RUNNING_UNIT_TESTS
7899 20 : sweep_note_due_for_tests(1, timespec_to_ns(&r->next_start));
7900 : #endif
7901 10 : async_race_launch_locked(r);
7902 : }
7903 50 : if (r->next < r->addrs->count) next_ns = timespec_to_ns(&r->next_start);
7904 : }
7905 : }
7906 40 : ccol__mutex_unlock(r->lock);
7907 40 : return next_ns;
7908 : }
7909 :
7910 : // Starts the race for ctx over ctx->addrs, which it takes over. Gives false
7911 : // when the race can't be built.
7912 26 : static bool async_race_start(chttp_async_ctx *ctx) {
7913 26 : size_t n = ctx->addrs->count;
7914 26 : chttp_connect_race *r = (chttp_connect_race *)ccol__mem_calloc(
7915 : ctx->mp, 1, sizeof(*r) + n * sizeof(r->attempts[0]));
7916 26 : if (!r) return false;
7917 26 : if (ccol__mutex_init(r->lock) != 0) {
7918 0 : ccol__mem_free(ctx->mp, r);
7919 0 : return false;
7920 : }
7921 26 : if (ctx->mp) {
7922 0 : r->procs = *ctx->mp;
7923 0 : r->has_procs = true;
7924 : }
7925 26 : r->refs = 1;
7926 26 : r->ctx = ctx;
7927 26 : r->addrs = ctx->addrs;
7928 26 : ctx->addrs = NULL;
7929 78 : for (size_t i = 0; i < n; i++) {
7930 52 : r->attempts[i].race = r;
7931 52 : r->attempts[i].fd = -1;
7932 : }
7933 26 : ctx->state = CHTTP_ASYNC_CONNECTING;
7934 26 : atomic_store(&ctx->race, r);
7935 :
7936 26 : ccol__mutex_lock(r->lock);
7937 26 : async_race_launch_locked(r);
7938 26 : bool failed = (r->pending == 0);
7939 26 : if (failed) (void)async_race_decide_locked(r, NULL);
7940 26 : ccol__mutex_unlock(r->lock);
7941 26 : if (failed) {
7942 0 : async_fulfill(ctx, ccol_http_connection_failed, NULL);
7943 0 : async_ctx_teardown(ctx);
7944 : }
7945 : return true;
7946 : }
7947 :
7948 : // Lets go of ctx's race when ctx is freed, deciding it if it isn't yet, so no
7949 : // attempt outlives its ctx.
7950 833 : static void async_race_detach(chttp_async_ctx *ctx) {
7951 833 : chttp_connect_race *r = atomic_load(&ctx->race);
7952 833 : if (!r) return;
7953 26 : atomic_store(&ctx->race, NULL);
7954 26 : ccol__mutex_lock(r->lock);
7955 26 : if (!r->decided) (void)async_race_decide_locked(r, NULL);
7956 26 : ccol__mutex_unlock(r->lock);
7957 26 : async_race_release(r);
7958 : }
7959 :
7960 : // Connects a fresh hop: Resolves a TCP target or builds the unix address, then
7961 : // makes one non-blocking connect (or starts the race) and registers the fd. It
7962 : // runs on a DNS pool worker for a named target, inline for a literal or a unix
7963 : // target. It checks timed_out before and after the lookup, so a hop the sweep
7964 : // already answered makes no lookup and no connect.
7965 834 : static void async_connect_task(void *arg) {
7966 834 : chttp_async_ctx *ctx = (chttp_async_ctx *)arg;
7967 834 : int fd = -1;
7968 :
7969 834 : if (ctx->is_unix) {
7970 8 : struct sockaddr_un addr;
7971 8 : memset(&addr, 0, sizeof(addr));
7972 8 : addr.sun_family = AF_UNIX;
7973 8 : size_t path_len = strlen(ctx->unix_socket_path);
7974 8 : if (path_len >= sizeof(addr.sun_path)) {
7975 0 : async_fulfill(ctx, ccol_http_invalid_url, NULL);
7976 0 : async_ctx_teardown(ctx);
7977 0 : return;
7978 : }
7979 8 : memcpy(addr.sun_path, ctx->unix_socket_path, path_len + 1);
7980 8 : fd = ccol_socket_nb(AF_UNIX, SOCK_STREAM, 0);
7981 8 : if (fd < 0) {
7982 0 : async_fulfill(ctx, ccol_http_connection_failed, NULL);
7983 0 : async_ctx_teardown(ctx);
7984 0 : return;
7985 : }
7986 8 : if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 &&
7987 0 : errno != EINPROGRESS) {
7988 0 : close(fd);
7989 0 : async_fulfill(ctx, ccol_http_connection_failed, NULL);
7990 0 : async_ctx_teardown(ctx);
7991 0 : return;
7992 : }
7993 : } else {
7994 826 : if (ctx->timed_out) {
7995 2 : async_fulfill(ctx, ccol_timed_out, NULL);
7996 2 : async_ctx_teardown(ctx);
7997 36 : return;
7998 : }
7999 1647 : ccol_retval rrv = addr_list_resolve_for_target(ctx->mp, ctx->host,
8000 824 : ctx->port, &ctx->addrs);
8001 823 : if (rrv != ccol_success) {
8002 6 : async_fulfill(ctx, rrv, NULL);
8003 6 : async_ctx_teardown(ctx);
8004 6 : return;
8005 : }
8006 817 : if (ctx->timed_out) {
8007 0 : async_fulfill(ctx, ccol_timed_out, NULL);
8008 0 : async_ctx_teardown(ctx);
8009 0 : return;
8010 : }
8011 817 : addr_list_interleave(ctx->addrs);
8012 817 : if (ctx->addrs->count > 1) {
8013 26 : if (!async_race_start(ctx)) {
8014 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
8015 0 : async_ctx_teardown(ctx);
8016 : }
8017 26 : return;
8018 : }
8019 791 : bool in_progress = false;
8020 791 : fd = addr_connect_start(&ctx->addrs->addrs[0], &in_progress);
8021 790 : if (fd < 0) {
8022 0 : async_fulfill(ctx, ccol_http_connection_failed, NULL);
8023 0 : async_ctx_teardown(ctx);
8024 0 : return;
8025 : }
8026 790 : int remaining_ms;
8027 1581 : if (in_progress &&
8028 791 : !deadline_remaining_ms(&ctx->connect_deadline, &remaining_ms))
8029 0 : ctx->timed_out = true;
8030 : }
8031 798 : async_connect_register(ctx, fd);
8032 : }
8033 :
8034 : // Starts the connect of a fresh hop: A name lookup goes to the DNS pool, since
8035 : // getaddrinfo() blocks, and anything else runs async_connect_task inline.
8036 834 : static ccol_retval async_connect_begin(chttp_async_ctx *ctx) {
8037 834 : if (ctx->is_unix || host_is_ip_literal(ctx->host)) {
8038 799 : async_connect_task(ctx);
8039 799 : return ccol_success;
8040 : }
8041 35 : return cthrpool_submit(cli_engine_bundler.dns_pool, async_connect_task, ctx,
8042 : NULL);
8043 : }
8044 :
8045 : // Hands the socket fd to ctx and registers it for write readiness. It stores
8046 : // the fd before it reads timed_out (both sequentially consistent), so the sweep
8047 : // either shuts this fd down or the task ends the hop itself.
8048 820 : static void async_connect_register(chttp_async_ctx *ctx, int fd) {
8049 820 : ctx->fd = fd;
8050 820 : ctx->state = CHTTP_ASYNC_CONNECTING;
8051 :
8052 820 : if (ctx->timed_out) {
8053 0 : async_fulfill(ctx, ccol_timed_out, NULL);
8054 0 : async_ctx_teardown(ctx);
8055 0 : return;
8056 : }
8057 :
8058 820 : char *err = NULL;
8059 820 : ceventloop_handlers handlers = {
8060 : .on_readable = async_on_readable,
8061 : .on_writable = async_on_writable,
8062 : .on_error = async_on_error,
8063 : };
8064 820 : ccol__mutex_lock(ctx->idle_lock);
8065 1642 : ctx->reg =
8066 821 : ceventloop_add(cli_engine_bundler.reactor,
8067 821 : cselectable_fd(fd, cselect_write), handlers, ctx, &err);
8068 821 : bool reg_failed = !ctx->reg;
8069 821 : ccol__mutex_unlock(ctx->idle_lock);
8070 821 : if (reg_failed) {
8071 0 : async_fulfill(ctx, ccol_not_enough_memory, NULL);
8072 0 : async_ctx_teardown(ctx);
8073 : }
8074 : }
8075 :
8076 : // Retries a reused connection that died before any response byte on a fresh ctx
8077 : // and connection, as Tier 1 does. The old ctx is torn down by its own dispatch,
8078 : // so nothing has to neutralise its callbacks.
8079 33 : static void async_retry_hop(chttp_async_ctx *old_ctx) {
8080 33 : old_ctx->hop_completed = true;
8081 33 : chttp_async_chain *chain = old_ctx->chain;
8082 :
8083 33 : async_chain_retain(chain);
8084 :
8085 33 : chttp_async_ctx *ctx = async_ctx_create(chain->mp);
8086 33 : if (!ctx) {
8087 0 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8088 0 : async_chain_release(chain);
8089 0 : return;
8090 : }
8091 :
8092 33 : ccol__mutex_lock(ctx->deadline_lock);
8093 33 : ctx->overall_deadline = chain->overall_deadline;
8094 33 : ctx->inactivity_us = chain->inactivity_timeout_us;
8095 33 : atomic_store(&ctx->last_io_ns, 0);
8096 33 : ccol__mutex_unlock(ctx->deadline_lock);
8097 33 : ctx->chain = chain;
8098 33 : ctx->cli = old_ctx->cli;
8099 33 : ctx->hop = old_ctx->hop;
8100 33 : ctx->cur_method = old_ctx->cur_method;
8101 33 : ctx->is_https = old_ctx->is_https;
8102 33 : ctx->verify_host = old_ctx->verify_host;
8103 33 : ctx->tls_generation = chain->tls_generation;
8104 :
8105 33 : ctx->is_unix = old_ctx->is_unix;
8106 33 : ctx->unix_socket_path = old_ctx->unix_socket_path;
8107 33 : old_ctx->unix_socket_path = NULL;
8108 33 : ctx->host = old_ctx->host;
8109 33 : old_ctx->host = NULL;
8110 33 : ctx->port = old_ctx->port;
8111 33 : ctx->is_ipv6 = old_ctx->is_ipv6;
8112 33 : ctx->path_and_query = old_ctx->path_and_query;
8113 33 : old_ctx->path_and_query = NULL;
8114 33 : ctx->wire = old_ctx->wire;
8115 33 : old_ctx->wire = NULL;
8116 33 : ctx->wire_len = old_ctx->wire_len;
8117 33 : ctx->origin_key = old_ctx->origin_key;
8118 33 : old_ctx->origin_key = NULL;
8119 33 : ctx->want_100_continue = old_ctx->want_100_continue;
8120 33 : ctx->header_len = old_ctx->header_len;
8121 33 : ctx->replayable = old_ctx->replayable;
8122 33 : ctx->request_close = old_ctx->request_close;
8123 33 : atomic_store(&ctx->continue_decided, false);
8124 33 : atomic_store(&ctx->continue_msg_started, false);
8125 :
8126 33 : ctx->pctx.mp = chain->mp;
8127 33 : ctx->pctx.is_head_request = old_ctx->pctx.is_head_request;
8128 66 : ctx->pctx.requested_sink_fn =
8129 33 : chain->write_fn ? sink_async_user : sink_buffered;
8130 33 : ctx->pctx.requested_sink_ctx = chain->write_fn ? (void *)chain : &ctx->bb;
8131 33 : ctx->pctx.headers = old_ctx->pctx.headers;
8132 33 : old_ctx->pctx.headers = NULL;
8133 33 : ctx->bb.mp = chain->mp;
8134 33 : ctx->bb.max_size = chain->max_response_body_size;
8135 :
8136 33 : ctx->reused = false;
8137 33 : ctx->any_bytes_read = false;
8138 33 : ctx->connect_deadline = deadline_make(chain->connect_timeout_us);
8139 :
8140 33 : async_parser_start(ctx);
8141 :
8142 33 : client_deadline_register(ctx);
8143 33 : client_deadline_note(&ctx->connect_deadline);
8144 33 : client_deadline_note(&chain->overall_deadline);
8145 :
8146 33 : ccol_retval sr = async_connect_begin(ctx);
8147 33 : if (sr != ccol_success) {
8148 0 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8149 0 : async_ctx_free(ctx);
8150 0 : async_chain_release(chain);
8151 : }
8152 : }
8153 :
8154 : // Fails a hop that couldn't be submitted, for async_submit_hop's error paths:
8155 : // fulfils the chain with rv and tears ctx down.
8156 9 : static void async_submit_hop_fail(chttp_async_ctx *ctx, ccol_retval rv) {
8157 9 : chttp_async_chain *chain = ctx->chain;
8158 9 : async_fulfill_chain(chain, rv, NULL);
8159 9 : if (ctx->reused) {
8160 4 : ctx->pending_app_teardown = true;
8161 4 : ctx->hop_completed = true;
8162 : #ifdef RUNNING_UNIT_TESTS
8163 4 : atomic_store(&g_abandon_shutdown_under_lock_for_tests,
8164 : ctx->idle_lock_held_for_tests ? 1 : 0);
8165 : #endif
8166 4 : if (ctx->fd >= 0) shutdown(ctx->fd, SHUT_RDWR);
8167 : #ifdef RUNNING_UNIT_TESTS
8168 4 : ctx->idle_lock_held_for_tests = false;
8169 : #endif
8170 4 : ccol__mutex_unlock(ctx->idle_lock);
8171 4 : client_engine_release();
8172 : } else {
8173 5 : async_ctx_free(ctx);
8174 5 : async_chain_release(chain);
8175 : }
8176 9 : }
8177 :
8178 : // Prepares one hop of a chain and submits it, for the first hop and every
8179 : // redirect hop. It parses the URL, applies the transport and TLS checks, builds
8180 : // the hop's view of the request (redirect header drops, carried userinfo
8181 : // Authorization, method and body after a downgrade), serializes it, and then
8182 : // either takes a pooled connection (writing under its idle_lock) or starts a
8183 : // fresh connect. On success the hop holds a chain reference; on failure it
8184 : // fulfils the future with the error, keeps the refcount as it was, and gives
8185 : // false.
8186 1016 : static bool async_submit_hop(chttp_async_chain *chain, const char *url_str,
8187 : chttp_method method, const void *body_data,
8188 : size_t body_len, const char *body_content_type,
8189 : int hop) {
8190 1016 : async_chain_retain(chain);
8191 :
8192 1016 : chttp_url url;
8193 1016 : ccol_retval prv = parse_chttp_url(chain->mp, url_str, &url);
8194 1016 : if (prv != ccol_success) {
8195 14 : async_fulfill_chain(chain, prv, NULL);
8196 14 : async_chain_release(chain);
8197 14 : return false;
8198 : }
8199 1002 : if (url.is_https && !chain->tls_ctx_usable) {
8200 0 : url_free(chain->mp, &url);
8201 0 : async_fulfill_chain(chain, tls_ctx_unusable_code(chain->tls_ctx_oom), NULL);
8202 0 : async_chain_release(chain);
8203 0 : return false;
8204 : }
8205 :
8206 2004 : chain->redirect_drops =
8207 1002 : redirect_header_drops(chain->initial_origin_key, url.origin_key);
8208 :
8209 1002 : const char *effective_auth = NULL;
8210 1002 : if (url.userinfo_authorization) {
8211 : effective_auth = url.userinfo_authorization;
8212 1002 : } else if (chain->carried_auth &&
8213 4 : origin_keys_same(chain->carried_auth_origin, url.origin_key)) {
8214 1002 : effective_auth = chain->carried_auth;
8215 : }
8216 1002 : if (url.userinfo_authorization) {
8217 4 : char *na = ccol_strdup(chain->mp, url.userinfo_authorization);
8218 4 : char *no = ccol_strdup(chain->mp, url.origin_key);
8219 4 : if (!na || !no) {
8220 0 : ccol__mem_free(chain->mp, na);
8221 0 : ccol__mem_free(chain->mp, no);
8222 0 : url_free(chain->mp, &url);
8223 0 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8224 0 : async_chain_release(chain);
8225 0 : return false;
8226 : }
8227 4 : ccol__mem_free(chain->mp, chain->carried_auth);
8228 4 : ccol__mem_free(chain->mp, chain->carried_auth_origin);
8229 4 : chain->carried_auth = na;
8230 4 : chain->carried_auth_origin = no;
8231 1002 : } else if (chain->carried_auth &&
8232 4 : !origin_keys_same(chain->carried_auth_origin, url.origin_key)) {
8233 1 : ccol__mem_free(chain->mp, chain->carried_auth);
8234 1 : ccol__mem_free(chain->mp, chain->carried_auth_origin);
8235 1 : chain->carried_auth = NULL;
8236 1 : chain->carried_auth_origin = NULL;
8237 : }
8238 :
8239 1002 : chttp_async_ctx *ctx = NULL;
8240 1002 : bool reused = async_idle_pool_take(chain->cli, url.origin_key, chain, &ctx);
8241 : #ifdef RUNNING_UNIT_TESTS
8242 1002 : if (reused && atomic_exchange(&g_stray_write_at_take_for_tests, false)) {
8243 1 : (void)ceventloop_modify(cli_engine_bundler.reactor, ctx->reg,
8244 : cselect_write);
8245 1 : struct timespec pause_ts = {0, 200000000L};
8246 1 : nanosleep(&pause_ts, NULL);
8247 : }
8248 : #endif
8249 808 : if (!reused) {
8250 808 : ctx = async_ctx_create(chain->mp);
8251 808 : if (!ctx) {
8252 1 : url_free(chain->mp, &url);
8253 1 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8254 1 : async_chain_release(chain);
8255 1 : return false;
8256 : }
8257 807 : ctx->cli = chain->cli;
8258 807 : ctx->connect_deadline = deadline_make(chain->connect_timeout_us);
8259 : }
8260 1001 : ccol__mutex_lock(ctx->deadline_lock);
8261 1001 : ctx->overall_deadline = chain->overall_deadline;
8262 1001 : ctx->inactivity_us = chain->inactivity_timeout_us;
8263 1001 : atomic_store(&ctx->last_io_ns, 0);
8264 1001 : ccol__mutex_unlock(ctx->deadline_lock);
8265 1001 : ctx->chain = chain;
8266 1001 : ctx->hop = hop;
8267 1001 : ctx->cur_method = method;
8268 1001 : ctx->is_https = url.is_https;
8269 1001 : ctx->is_ipv6 = url.is_ipv6;
8270 1001 : ctx->verify_host = chain->verify_host;
8271 1001 : if (!reused) ctx->tls_generation = chain->tls_generation;
8272 1001 : ctx->reused = reused;
8273 1001 : ctx->reuse_checked = false;
8274 1001 : ctx->any_bytes_read = false;
8275 1001 : ctx->hop_completed = false;
8276 1001 : ctx->interim_responses_seen = 0;
8277 :
8278 1001 : ccol__mem_free(chain->mp, ctx->path_and_query);
8279 1001 : ctx->path_and_query = ccol_strdup(chain->mp, url.path_and_query);
8280 1001 : if (!ctx->path_and_query) {
8281 3 : url_free(chain->mp, &url);
8282 3 : async_submit_hop_fail(ctx, ccol_not_enough_memory);
8283 3 : return false;
8284 : }
8285 :
8286 998 : ctx->pctx.mp = chain->mp;
8287 998 : ctx->pctx.is_head_request = (method == CHTTP_HEAD);
8288 1996 : ctx->pctx.requested_sink_fn =
8289 998 : chain->write_fn ? sink_async_user : sink_buffered;
8290 998 : ctx->pctx.requested_sink_ctx = chain->write_fn ? (void *)chain : &ctx->bb;
8291 998 : ctx->bb.mp = chain->mp;
8292 998 : ctx->bb.max_size = chain->max_response_body_size;
8293 :
8294 998 : char *herr = NULL;
8295 1996 : ctx->pctx.headers =
8296 998 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_string,
8297 : ccol_string, chain->mp, NULL, NULL, &herr);
8298 998 : if (!ctx->pctx.headers) {
8299 2 : url_free(chain->mp, &url);
8300 2 : async_submit_hop_fail(ctx, ccol_not_enough_memory);
8301 2 : return false;
8302 : }
8303 :
8304 996 : chttp_request hop_req;
8305 996 : memset(&hop_req, 0, sizeof(hop_req));
8306 996 : hop_req.method = method;
8307 996 : hop_req.headers = chain->req_headers;
8308 996 : hop_req.body.data = body_data;
8309 996 : hop_req.body.len = body_len;
8310 996 : hop_req.body.content_type = body_content_type;
8311 996 : hop_req.expect_continue = chain->expect_continue;
8312 :
8313 996 : chttp_header_presence hop_hp;
8314 996 : prv = serialize_request(chain->mp, &hop_req, &url, effective_auth,
8315 : chain->redirect_drops, &ctx->wire, &ctx->wire_len,
8316 : &hop_hp);
8317 996 : if (prv != ccol_success) {
8318 3 : url_free(chain->mp, &url);
8319 3 : async_submit_hop_fail(ctx, prv);
8320 3 : return false;
8321 : }
8322 993 : bool body_carrying_method_ac =
8323 993 : (method == CHTTP_POST || method == CHTTP_PUT || method == CHTTP_PATCH);
8324 26 : ctx->want_100_continue = chain->expect_continue && !hop_hp.has_expect &&
8325 1018 : body_carrying_method_ac && body_data && body_len > 0;
8326 993 : ctx->replayable = request_is_replayable(method, &hop_hp);
8327 993 : ctx->request_close = hop_hp.request_close;
8328 993 : ctx->header_len = ctx->want_100_continue ? ctx->wire_len - body_len : 0;
8329 993 : atomic_store(&ctx->continue_decided, false);
8330 993 : atomic_store(&ctx->continue_msg_started, false);
8331 :
8332 993 : if (!ctx->origin_key) {
8333 803 : ctx->origin_key = ccol_strdup(chain->mp, url.origin_key);
8334 803 : if (!ctx->origin_key) {
8335 1 : url_free(chain->mp, &url);
8336 1 : async_submit_hop_fail(ctx, ccol_not_enough_memory);
8337 1 : return false;
8338 : }
8339 : }
8340 :
8341 992 : if (!reused) {
8342 802 : ctx->is_unix = url.is_unix;
8343 802 : if (url.is_unix) {
8344 8 : ctx->unix_socket_path = ccol_strdup(chain->mp, url.unix_socket_path);
8345 8 : if (!ctx->unix_socket_path) {
8346 0 : url_free(chain->mp, &url);
8347 0 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8348 0 : async_ctx_teardown(ctx);
8349 0 : return false;
8350 : }
8351 : } else {
8352 794 : ctx->host = ccol_strdup(chain->mp, url.host);
8353 793 : ctx->port = url.port;
8354 793 : if (!ctx->host) {
8355 1 : url_free(chain->mp, &url);
8356 1 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8357 1 : async_ctx_teardown(ctx);
8358 1 : return false;
8359 : }
8360 : }
8361 : }
8362 990 : url_free(chain->mp, &url);
8363 :
8364 991 : async_parser_start(ctx);
8365 :
8366 991 : if (reused) {
8367 190 : ccol_retval reactivate_rv;
8368 : #ifdef RUNNING_UNIT_TESTS
8369 190 : if (atomic_exchange(&g_force_reactivate_fail_for_tests, false)) {
8370 : reactivate_rv = ccol_unexpected_failure;
8371 : } else
8372 : #endif
8373 : {
8374 189 : reactivate_rv = ceventloop_modify(cli_engine_bundler.reactor, ctx->reg,
8375 : cselect_write);
8376 : }
8377 189 : if (reactivate_rv != ccol_success) {
8378 1 : ctx->pending_app_teardown = true;
8379 1 : async_retry_hop(ctx);
8380 : #ifdef RUNNING_UNIT_TESTS
8381 1 : atomic_store(&g_abandon_shutdown_under_lock_for_tests,
8382 : ctx->idle_lock_held_for_tests ? 1 : 0);
8383 : #endif
8384 1 : if (ctx->fd >= 0) shutdown(ctx->fd, SHUT_RDWR);
8385 : #ifdef RUNNING_UNIT_TESTS
8386 1 : ctx->idle_lock_held_for_tests = false;
8387 : #endif
8388 1 : ccol__mutex_unlock(ctx->idle_lock);
8389 1 : client_engine_release();
8390 1 : return true;
8391 : }
8392 : #ifdef RUNNING_UNIT_TESTS
8393 189 : ctx->idle_lock_held_for_tests = false;
8394 : #endif
8395 189 : ccol__mutex_unlock(ctx->idle_lock);
8396 189 : client_engine_release();
8397 189 : return true;
8398 : }
8399 :
8400 801 : client_deadline_register(ctx);
8401 800 : client_deadline_note(&ctx->connect_deadline);
8402 801 : client_deadline_note(&chain->overall_deadline);
8403 :
8404 801 : ccol_retval sr = async_connect_begin(ctx);
8405 801 : if (sr != ccol_success) {
8406 0 : async_fulfill_chain(chain, ccol_not_enough_memory, NULL);
8407 0 : async_ctx_teardown(ctx);
8408 0 : return false;
8409 : }
8410 : return true;
8411 : }
8412 :
8413 : // Follows a redirect once a hop's response is fully parsed as one. It resolves
8414 : // Location against this hop's URL, applies the method and body rules (307 and
8415 : // 308 keep them, other statuses turn into a bodiless GET unless HEAD), finishes
8416 : // this hop's connection, and submits the next hop. A temporary chain reference
8417 : // keeps the chain alive across the hand-off. Past the redirect limit, or when
8418 : // Location can't be resolved, it fulfils the future instead.
8419 119 : static void async_handle_redirect(chttp_async_ctx *ctx, bool reusable) {
8420 119 : chttp_async_chain *chain = ctx->chain;
8421 119 : async_chain_retain(chain);
8422 :
8423 119 : if (ctx->hop >= CHTTP_MAX_REDIRECTS) {
8424 1 : async_finish_connection(ctx, reusable);
8425 1 : async_fulfill_chain(chain, ccol_http_too_many_redirects, NULL);
8426 1 : async_chain_release(chain);
8427 1 : return;
8428 : }
8429 :
8430 118 : chttp_url base;
8431 118 : memset(&base, 0, sizeof(base));
8432 118 : base.is_https = ctx->is_https;
8433 118 : base.is_ipv6 = ctx->is_ipv6;
8434 118 : base.is_unix = ctx->is_unix;
8435 118 : base.unix_socket_path = ctx->unix_socket_path;
8436 118 : base.host = ctx->host;
8437 118 : base.port = ctx->port;
8438 118 : base.path_and_query = ctx->path_and_query;
8439 :
8440 118 : ccol_retval resolve_rv = ccol_success;
8441 118 : char *next_url =
8442 118 : resolve_redirect_url(chain->mp, &base, ctx->pctx.location, &resolve_rv);
8443 118 : bool transport_refused = false;
8444 342 : ccol_retval transport_rv =
8445 : next_url
8446 106 : ? redirect_transport_allowed(chain->mp, &base, next_url,
8447 106 : chain->prevent_tls_downgrade_on_redirect)
8448 118 : : ccol_success;
8449 106 : if (transport_rv != ccol_success) {
8450 2 : ccol__mem_free(chain->mp, next_url);
8451 : next_url = NULL;
8452 : transport_refused = true;
8453 : }
8454 118 : bool preserve =
8455 118 : (ctx->pctx.status_code == 307 || ctx->pctx.status_code == 308);
8456 118 : chttp_method next_method = ctx->cur_method;
8457 118 : const void *next_body_data = chain->body_dropped ? NULL : chain->body_data;
8458 118 : size_t next_body_len = chain->body_dropped ? 0 : chain->body_len;
8459 236 : const char *next_body_ct =
8460 118 : chain->body_dropped ? NULL : chain->body_content_type;
8461 118 : if (!preserve && ctx->cur_method != CHTTP_HEAD) {
8462 116 : next_method = CHTTP_GET;
8463 116 : next_body_data = NULL;
8464 116 : next_body_len = 0;
8465 116 : next_body_ct = NULL;
8466 116 : chain->body_dropped = true;
8467 : }
8468 118 : int next_hop = ctx->hop + 1;
8469 :
8470 118 : async_finish_connection(ctx, reusable);
8471 :
8472 118 : if (next_url) {
8473 104 : async_submit_hop(chain, next_url, next_method, next_body_data,
8474 : next_body_len, next_body_ct, next_hop);
8475 104 : ccol__mem_free(chain->mp, next_url);
8476 14 : } else if (transport_refused) {
8477 2 : async_fulfill_chain(chain, transport_rv, NULL);
8478 : } else {
8479 12 : async_fulfill_chain(chain, resolve_rv, NULL);
8480 : }
8481 118 : async_chain_release(chain);
8482 : }
8483 :
8484 : // Runs the Tier 2 and Tier 3 checks before anything is queued, so a bad request
8485 : // fails at once with the same code as in Tier 1: Valid cli and req, a URL that
8486 : // parses into *url_out (freed by the caller after success), and usable TLS for
8487 : // https.
8488 944 : static ccol_retval chttp_async_preflight_check(struct chttpclient *cli,
8489 : const chttp_request *req,
8490 : chttp_url *url_out) {
8491 944 : if (!cli || !req) return ccol_invalid_args;
8492 :
8493 942 : ccol_retval prv = parse_chttp_url(cli->m_procs, req->url, url_out);
8494 942 : if (prv != ccol_success) return prv;
8495 :
8496 927 : ccol__mutex_lock(cli->lock);
8497 927 : if (url_out->is_https) tls_ctx_retry_if_oom_locked(cli);
8498 927 : bool tls_ctx_usable = cli->tls_ctx_usable;
8499 927 : bool tls_ctx_oom = cli->tls_ctx_oom;
8500 927 : ccol__mutex_unlock(cli->lock);
8501 :
8502 927 : if (url_out->is_https && !tls_ctx_usable) {
8503 1 : url_free(cli->m_procs, url_out);
8504 2 : return tls_ctx_unusable_code(tls_ctx_oom);
8505 : }
8506 : return ccol_success;
8507 : }
8508 :
8509 : // Submits req to run asynchronously on cli and gives its future, which the
8510 : // caller frees once with cthrpool_future_free. It gives NULL with *rv_out set
8511 : // when the request can't be queued (bad arguments, a bad URL, unusable TLS, a
8512 : // failed allocation, an engine that won't start). It snapshots the client's TLS
8513 : // context and settings under cli->lock and allocates the result before the
8514 : // future exists, so the fulfilment never allocates.
8515 944 : static cthrpool_future *chttp_do_async_internal(struct chttpclient *cli,
8516 : const chttp_request *req,
8517 : chttpcli_write_fn write_fn,
8518 : void *write_ctx,
8519 : ccol_retval *rv_out) {
8520 944 : chttp_url url;
8521 944 : ccol_retval prv = chttp_async_preflight_check(cli, req, &url);
8522 944 : if (prv != ccol_success) {
8523 18 : *rv_out = prv;
8524 18 : return NULL;
8525 : }
8526 926 : *rv_out = ccol_not_enough_memory;
8527 926 : ccol_memmgmt_procs *mp = cli->m_procs;
8528 926 : char *initial_origin_key = ccol_strdup(mp, url.origin_key);
8529 926 : url_free(mp, &url);
8530 926 : if (!initial_origin_key) return NULL;
8531 :
8532 923 : ctls_ctx *tls_ctx;
8533 923 : bool tls_ctx_usable;
8534 923 : bool verify_host;
8535 923 : uint64_t tls_generation;
8536 923 : uint64_t connect_timeout_us;
8537 923 : uint64_t request_timeout_us;
8538 923 : uint64_t inactivity_timeout_us;
8539 923 : size_t max_response_body_size;
8540 923 : ccol__mutex_lock(cli->lock);
8541 923 : tls_ctx_retry_if_oom_locked(cli);
8542 923 : tls_ctx = cli->tls_ctx;
8543 923 : tls_ctx_usable = cli->tls_ctx_usable;
8544 923 : bool tls_ctx_oom = cli->tls_ctx_oom;
8545 1846 : verify_host =
8546 923 : !cli->tls.insecure_skip_verify && !cli->tls.insecure_skip_hostname_check;
8547 923 : tls_generation = cli->tls_generation;
8548 923 : connect_timeout_us = cli->connect_timeout_us;
8549 923 : request_timeout_us = cli->request_timeout_us;
8550 923 : inactivity_timeout_us = cli->inactivity_timeout_us;
8551 923 : max_response_body_size = cli->max_response_body_size;
8552 923 : if (tls_ctx) ctls_ctx_retain(tls_ctx);
8553 923 : ccol__mutex_unlock(cli->lock);
8554 :
8555 923 : ccol_retval arv = client_engine_acquire_chain();
8556 923 : if (arv != ccol_success) {
8557 0 : if (tls_ctx) ctls_ctx_release(tls_ctx);
8558 0 : ccol__mem_free(mp, initial_origin_key);
8559 0 : *rv_out = arv;
8560 0 : return NULL;
8561 : }
8562 :
8563 923 : chttpcli_async_result *result = async_result_alloc(mp);
8564 923 : char *ferr = NULL;
8565 3 : cthrpool_future *future =
8566 920 : result ? cthrpool_future_create_detached(&ferr) : NULL;
8567 923 : if (!future) {
8568 3 : if (result) chttpcli_async_result_free(result);
8569 3 : if (tls_ctx) ctls_ctx_release(tls_ctx);
8570 3 : client_async_request_settled();
8571 3 : client_engine_release_chain();
8572 3 : ccol__mem_free(mp, initial_origin_key);
8573 3 : return NULL;
8574 : }
8575 920 : *rv_out = ccol_success;
8576 920 : cthrpool_future *f = future;
8577 :
8578 1840 : chttp_async_chain *chain = async_chain_create(
8579 920 : mp, cli, future, (chmap)req->headers, req->body.data, req->body.len,
8580 920 : req->body.content_type, initial_origin_key, tls_ctx, tls_ctx_usable,
8581 : verify_host, tls_generation, connect_timeout_us, request_timeout_us,
8582 920 : max_response_body_size, write_fn, write_ctx, req->expect_continue,
8583 920 : req->prevent_tls_downgrade_on_redirect);
8584 920 : if (chain) {
8585 912 : chain->inactivity_timeout_us = inactivity_timeout_us;
8586 912 : chain->tls_ctx_oom = tls_ctx_oom;
8587 : }
8588 920 : ccol__mem_free(mp, initial_origin_key);
8589 920 : if (!chain) {
8590 8 : if (tls_ctx) ctls_ctx_release(tls_ctx);
8591 8 : client_async_request_settled();
8592 8 : result->rv = ccol_not_enough_memory;
8593 8 : result->resp = NULL;
8594 8 : cthrpool_future_fulfill(future, result);
8595 8 : client_engine_release_chain();
8596 8 : return f;
8597 : }
8598 912 : chain->result = result;
8599 912 : async_submit_hop(chain, req->url, req->method, req->body.data, req->body.len,
8600 912 : req->body.content_type, 0);
8601 912 : return f;
8602 : }
8603 :
8604 : #ifdef RUNNING_UNIT_TESTS
8605 : // Engine test hooks
8606 : //
8607 : // Give a test sizeof(chttp_async_chain), the engine's reference count and
8608 : // logger, and let it clear the installed logger, see whether the engine runs,
8609 : // take and drop a reference, wait for a teardown and see whether the globals
8610 : // were ever initialized.
8611 1 : size_t chttp__async_chain_struct_size_for_tests(void) {
8612 1 : return sizeof(chttp_async_chain);
8613 : }
8614 :
8615 8155 : int chttpcli__engine_ref_count_for_tests(void) {
8616 8155 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8617 8155 : ccol__mutex_lock(cli_engine_bundler.mutex);
8618 8155 : int n = (int)cli_engine_bundler.reactor_refs;
8619 8155 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8620 8155 : return n;
8621 : }
8622 :
8623 2 : clog chttpcli__engine_logger_for_tests(void) {
8624 2 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8625 2 : ccol__mutex_lock(cli_engine_bundler.mutex);
8626 2 : clog l = cli_engine_bundler.logger;
8627 2 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8628 2 : return l;
8629 : }
8630 :
8631 1 : void chttpcli__clear_engine_user_logger_for_tests(void) {
8632 1 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8633 1 : ccol__mutex_lock(cli_engine_bundler.mutex);
8634 1 : clog user = cli_engine_bundler.user_logger;
8635 1 : cli_engine_bundler.user_logger = CLOG_NULL;
8636 1 : if (cli_engine_bundler.logger == user) cli_engine_bundler.logger = CLOG_NULL;
8637 1 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8638 1 : if (user) clog_close(user);
8639 1 : }
8640 :
8641 57 : bool chttpcli__engine_running_for_tests(void) {
8642 57 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8643 57 : ccol__mutex_lock(cli_engine_bundler.mutex);
8644 57 : bool running = (cli_engine_bundler.reactor != CEVENTLOOP_NULL);
8645 57 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8646 57 : return running;
8647 : }
8648 :
8649 31 : ccol_retval chttpcli__engine_acquire_for_tests(void) {
8650 31 : return client_engine_acquire();
8651 : }
8652 :
8653 30 : void chttpcli__engine_release_for_tests(void) { client_engine_release(); }
8654 :
8655 340 : void chttpcli__engine_wait_for_quiescence_for_tests(void) {
8656 340 : client_engine_wait_for_quiescence();
8657 340 : }
8658 :
8659 1 : bool chttpcli__engine_globals_entered_for_tests(void) {
8660 1 : return atomic_load(&g_engine_globals_entered);
8661 : }
8662 :
8663 : // Gives the running engine's DNS pool (CTHRPOOL_NULL with no engine), so a test
8664 : // can check what the engine built.
8665 1 : cthrpool chttpcli__engine_dns_pool_for_tests(void) {
8666 1 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8667 1 : ccol__mutex_lock(cli_engine_bundler.mutex);
8668 1 : cthrpool h = cli_engine_bundler.dns_pool;
8669 1 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8670 1 : return h;
8671 : }
8672 :
8673 : // Arm the reaper holds (see g_reaper_final_hold_ms_for_tests and
8674 : // g_reaper_tail_hold_ms_for_tests) and tell whether each was reached, so a test
8675 : // can race the reaper's last steps.
8676 4 : void chttpcli__hold_next_reaper_final_section_for_tests(int ms) {
8677 4 : atomic_store(&g_reaper_final_hold_entered_for_tests, false);
8678 4 : atomic_store(&g_reaper_final_hold_ms_for_tests, ms);
8679 4 : }
8680 :
8681 8 : bool chttpcli__reaper_final_section_was_entered_for_tests(void) {
8682 8 : return atomic_load(&g_reaper_final_hold_entered_for_tests);
8683 : }
8684 :
8685 1 : void chttpcli__hold_next_reaper_tail_for_tests(int ms) {
8686 1 : atomic_store(&g_reaper_tail_hold_entered_for_tests, false);
8687 1 : atomic_store(&g_reaper_tail_hold_left_for_tests, false);
8688 1 : atomic_store(&g_reaper_tail_hold_ms_for_tests, ms);
8689 1 : }
8690 :
8691 2 : bool chttpcli__reaper_tail_was_entered_for_tests(void) {
8692 2 : return atomic_load(&g_reaper_tail_hold_entered_for_tests);
8693 : }
8694 :
8695 1 : bool chttpcli__reaper_tail_was_left_for_tests(void) {
8696 1 : return atomic_load(&g_reaper_tail_hold_left_for_tests);
8697 : }
8698 :
8699 : // Waits until no teardown is in flight and leaves the finished reaper unjoined,
8700 : // so a test can fork in the state between an engine stop and the next acquire.
8701 1 : void chttpcli__engine_wait_stopped_unjoined_for_tests(void) {
8702 1 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8703 1 : ccol__mutex_lock(cli_engine_bundler.mutex);
8704 2 : while (cli_engine_bundler.stopping)
8705 1 : ccol__cond_var_wait(cli_engine_bundler.stopped_cv,
8706 : cli_engine_bundler.mutex);
8707 1 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8708 1 : }
8709 :
8710 : // Copies the handle of the unjoined reaper into *out, so a test can compare it
8711 : // after a fork. Gives false when there's none.
8712 1 : bool chttpcli__engine_unjoined_reaper_for_tests(ccol__thread_id *out) {
8713 1 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8714 1 : ccol__mutex_lock(cli_engine_bundler.mutex);
8715 1 : bool joinable = cli_engine_bundler.reaper_joinable;
8716 1 : if (joinable) *out = cli_engine_bundler.reaper_thread;
8717 1 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8718 1 : return joinable;
8719 : }
8720 :
8721 : // Read and reset the probe of g_abandon_shutdown_under_lock_for_tests, so a
8722 : // test can check the shutdown order of an abandoned ctx.
8723 1201 : int chttpcli__abandon_shutdown_under_lock_for_tests(void) {
8724 1201 : return atomic_load(&g_abandon_shutdown_under_lock_for_tests);
8725 : }
8726 :
8727 1 : void chttpcli__reset_abandon_shutdown_probe_for_tests(void) {
8728 1 : atomic_store(&g_abandon_shutdown_under_lock_for_tests, -1);
8729 1 : }
8730 :
8731 : // Arms the TLS direction injection (0 off, 1 a write needs readable, 2 a read
8732 : // needs writable) and clears its counters. A test disarms it before returning,
8733 : // since the engine threads keep running.
8734 8 : void chttpcli__tls_dir_inject_for_tests(int mode) {
8735 8 : atomic_store(&g_tls_dir_blocked, false);
8736 8 : atomic_store(&g_tls_dir_released, false);
8737 8 : atomic_store(&g_tls_dir_block_attempts, 0);
8738 8 : atomic_store(&g_tls_dir_read_interest_while_writing, 0);
8739 8 : atomic_store(&g_tls_dir_write_interest_while_reading, 0);
8740 8 : atomic_store(&g_tls_dir_inject_mode, mode);
8741 8 : }
8742 :
8743 : // Read the state of the TLS direction injection, so a test can see that the
8744 : // code waited in the right direction: Whether the block was released, the
8745 : // interest in the other direction seen while it was pending, and how many
8746 : // attempts it refused (a caller that ignores the reported direction spins and
8747 : // drives that count up).
8748 4 : bool chttpcli__tls_dir_released_for_tests(void) {
8749 4 : return atomic_load(&g_tls_dir_released);
8750 : }
8751 :
8752 1 : unsigned chttpcli__tls_dir_read_interest_while_writing_for_tests(void) {
8753 1 : return atomic_load(&g_tls_dir_read_interest_while_writing);
8754 : }
8755 :
8756 1 : unsigned chttpcli__tls_dir_write_interest_while_reading_for_tests(void) {
8757 1 : return atomic_load(&g_tls_dir_write_interest_while_reading);
8758 : }
8759 :
8760 1 : unsigned chttpcli__tls_dir_block_attempts_for_tests(void) {
8761 1 : return atomic_load(&g_tls_dir_block_attempts);
8762 : }
8763 :
8764 : // Hold, query and release the next reaper spawn (see
8765 : // g_reaper_spawn_hold_for_tests) and read the created and joined counts, so a
8766 : // test can check that no reaper handle is lost.
8767 1 : void chttpcli__hold_next_reaper_spawn_for_tests(void) {
8768 1 : atomic_store(&g_reaper_spawn_gate_for_tests, false);
8769 1 : atomic_store(&g_reaper_spawn_held_for_tests, false);
8770 1 : atomic_store(&g_reaper_spawn_hold_for_tests, true);
8771 1 : }
8772 :
8773 2 : bool chttpcli__reaper_spawn_is_held_for_tests(void) {
8774 2 : return atomic_load(&g_reaper_spawn_held_for_tests);
8775 : }
8776 :
8777 1 : void chttpcli__release_reaper_spawn_for_tests(void) {
8778 1 : atomic_store(&g_reaper_spawn_gate_for_tests, true);
8779 1 : }
8780 :
8781 28 : unsigned chttpcli__reaper_created_count_for_tests(void) {
8782 28 : return atomic_load(&g_reaper_created_for_tests);
8783 : }
8784 :
8785 28 : unsigned chttpcli__reaper_joined_count_for_tests(void) {
8786 28 : return atomic_load(&g_reaper_joined_for_tests);
8787 : }
8788 :
8789 : // Make every reaper spawn fail and read how often the spawn gave up, so a test
8790 : // reaches the abandoned-reap path without a real thread limit.
8791 4 : void chttpcli__force_reaper_spawn_fail_for_tests(bool on) {
8792 4 : atomic_store(&g_force_reaper_spawn_fail_for_tests, on);
8793 4 : }
8794 :
8795 18 : unsigned chttpcli__engine_reaper_abandoned_count_for_tests(void) {
8796 18 : return atomic_load(&g_reaper_abandoned_count_for_tests);
8797 : }
8798 :
8799 : // Gives the reactor thread count the engine was last built with, so a test can
8800 : // check chttpcli_set_engine_num_reactor_threads.
8801 2 : size_t chttpcli__engine_num_reactor_threads_for_tests(void) {
8802 2 : ccol__call_once(cli_engine_bundler.once, client_engine_globals_init);
8803 2 : ccol__mutex_lock(cli_engine_bundler.mutex);
8804 2 : size_t n = cli_engine_bundler.last_resolved_num_reactor_threads;
8805 2 : ccol__mutex_unlock(cli_engine_bundler.mutex);
8806 2 : return n;
8807 : }
8808 :
8809 : // Ages every connection in cli's async idle pool past CHTTP_IDLE_MAX_AGE_MS, so
8810 : // the next take evicts it without waiting 60 s.
8811 241 : void chttpcli__force_async_idle_stale_for_tests(struct chttpclient *cli) {
8812 241 : ccol__mutex_lock(cli->lock);
8813 241 : if (cli->idle_pools_async) {
8814 241 : cmap_iterator *it = chashmap_begin_iter(cli->idle_pools_async, NULL);
8815 689 : for (; it; it = it->ccol__next_fn(it)) {
8816 207 : cvec list = read_cvec(it->val_pair->ptr);
8817 207 : if (!list) continue;
8818 207 : size_t n = cvector_size(list);
8819 599 : for (size_t i = 0; i < n; i++) {
8820 392 : chttp_async_ctx *actx = *(chttp_async_ctx **)cvector_at(list, i);
8821 392 : actx->last_used.tv_sec -= (CHTTP_IDLE_MAX_AGE_MS / 1000L) + 5;
8822 : }
8823 : }
8824 : }
8825 241 : ccol__mutex_unlock(cli->lock);
8826 241 : }
8827 :
8828 : // Shuts down every fd in cli's async idle pool, so a test can drive the IDLE
8829 : // dispatch that removes and frees each connection.
8830 2 : void chttpcli__shutdown_async_idle_connections_for_tests(
8831 : struct chttpclient *cli) {
8832 2 : ccol__mutex_lock(cli->lock);
8833 2 : if (cli->idle_pools_async) {
8834 2 : cmap_iterator *it = chashmap_begin_iter(cli->idle_pools_async, NULL);
8835 6 : for (; it; it = it->ccol__next_fn(it)) {
8836 2 : cvec list = read_cvec(it->val_pair->ptr);
8837 2 : if (!list) continue;
8838 2 : size_t n = cvector_size(list);
8839 4 : for (size_t i = 0; i < n; i++) {
8840 2 : chttp_async_ctx *actx = *(chttp_async_ctx **)cvector_at(list, i);
8841 2 : int afd = actx->fd;
8842 2 : if (afd >= 0) shutdown(afd, SHUT_RDWR);
8843 : }
8844 : }
8845 : }
8846 2 : ccol__mutex_unlock(cli->lock);
8847 2 : }
8848 :
8849 : // Count the connections of cli's async idle pool and those that carry a
8850 : // timed_out mark (always 0 when correct), so a test can check pool membership
8851 : // directly.
8852 43 : size_t chttpcli__async_idle_total_count_for_tests(struct chttpclient *cli) {
8853 43 : ccol__mutex_lock(cli->lock);
8854 43 : size_t n = cli->idle_total_count_async;
8855 43 : ccol__mutex_unlock(cli->lock);
8856 43 : return n;
8857 : }
8858 :
8859 1 : size_t chttpcli__async_idle_timed_out_count_for_tests(struct chttpclient *cli) {
8860 1 : size_t n = 0;
8861 1 : ccol__mutex_lock(cli->lock);
8862 1 : if (cli->idle_pools_async) {
8863 1 : cmap_iterator *it = chashmap_begin_iter(cli->idle_pools_async, NULL);
8864 3 : for (; it; it = it->ccol__next_fn(it)) {
8865 1 : cvec list = read_cvec(it->val_pair->ptr);
8866 1 : size_t count = list ? cvector_size(list) : 0;
8867 2 : for (size_t i = 0; i < count; i++) {
8868 1 : chttp_async_ctx **slot = (chttp_async_ctx **)cvector_at(list, i);
8869 1 : if ((*slot)->timed_out) n++;
8870 : }
8871 : }
8872 : }
8873 1 : ccol__mutex_unlock(cli->lock);
8874 1 : return n;
8875 : }
8876 :
8877 : // Count the origin keys of the Tier 1 and the async idle pools, so a test can
8878 : // see that an emptied origin loses its entry.
8879 4 : size_t chttpcli__idle_pools_key_count_for_tests(struct chttpclient *cli) {
8880 4 : ccol__mutex_lock(cli->lock);
8881 4 : size_t n = cli->idle_pools ? chashmap_size(cli->idle_pools) : 0;
8882 4 : ccol__mutex_unlock(cli->lock);
8883 4 : return n;
8884 : }
8885 :
8886 4 : size_t chttpcli__idle_pools_async_key_count_for_tests(struct chttpclient *cli) {
8887 4 : ccol__mutex_lock(cli->lock);
8888 4 : size_t n = cli->idle_pools_async ? chashmap_size(cli->idle_pools_async) : 0;
8889 4 : ccol__mutex_unlock(cli->lock);
8890 4 : return n;
8891 : }
8892 :
8893 : // Overrides CHTTP_MAX_IDLE_ORIGINS for the whole process; 0 restores it.
8894 4 : void chttpcli__set_max_idle_origins_for_tests(size_t n) {
8895 4 : atomic_store(&g_max_idle_origins_override_for_tests, n);
8896 4 : }
8897 :
8898 : // Gives the client behind h without pinning it, for single-threaded tests that
8899 : // can't race a destroy.
8900 289 : struct chttpclient *chttpcli__resolve_for_tests(chttpcli h) {
8901 289 : ccol__call_once(chttpcli_slot_table.once, chttpcli_slot_table_init_globals);
8902 289 : if (h == 0) return NULL;
8903 289 : uint32_t idx = (uint32_t)(h >> 32);
8904 289 : uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
8905 289 : ccol__rw_lock_rdlock(chttpcli_slot_table.rwlock);
8906 289 : struct chttpclient *raw = NULL;
8907 289 : if (idx < cvector_size(chttpcli_slot_table.slots)) {
8908 289 : chttpcli_slot *slot =
8909 289 : (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, idx);
8910 289 : if (slot->in_use && slot->generation == gen) raw = slot->ptr;
8911 : }
8912 289 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
8913 289 : return raw;
8914 : }
8915 :
8916 : // Give the slot table's capacity and its free-list length, so a test can see
8917 : // that freed slots are reused.
8918 3 : size_t chttpcli__free_index_count_for_tests(void) {
8919 3 : ccol__call_once(chttpcli_slot_table.once, chttpcli_slot_table_init_globals);
8920 3 : ccol__rw_lock_rdlock(chttpcli_slot_table.rwlock);
8921 3 : size_t n = cvector_size(chttpcli_slot_table.free_indices);
8922 3 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
8923 3 : return n;
8924 : }
8925 :
8926 6 : size_t chttpcli__slot_table_capacity_for_tests(void) {
8927 6 : ccol__call_once(chttpcli_slot_table.once, chttpcli_slot_table_init_globals);
8928 6 : ccol__rw_lock_rdlock(chttpcli_slot_table.rwlock);
8929 6 : size_t n = cvector_size(chttpcli_slot_table.slots);
8930 6 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
8931 6 : return n;
8932 : }
8933 :
8934 : // Gives the number of pins held on h's slot, so a test can check that resolves
8935 : // and unpins stay balanced.
8936 5 : size_t chttpcli__pin_count_for_tests(chttpcli h) {
8937 5 : return ccol_pintable_pins_for(&chttpcli_pintable, h);
8938 : }
8939 :
8940 : // Make the next push of async_idle_pool_offer fail, or arm a stray write flip
8941 : // on the next plain hop that finishes writing or the next connection that goes
8942 : // idle, so a test reaches paths that allocator failures can't (see the hook
8943 : // variables above the async idle pool section).
8944 1 : void chttpcli__force_offer_push_fail_once_for_tests(void) {
8945 1 : atomic_store(&g_force_offer_push_fail_for_tests, true);
8946 1 : }
8947 :
8948 1 : void chttpcli__force_stray_write_arm_once_for_tests(void) {
8949 1 : atomic_store(&g_force_stray_write_arm_for_tests, true);
8950 1 : }
8951 :
8952 1 : void chttpcli__force_stray_idle_write_arm_once_for_tests(void) {
8953 1 : atomic_store(&g_force_stray_idle_write_arm_for_tests, true);
8954 1 : }
8955 :
8956 : // Arm, wait for and release the IDLE probe hold (see
8957 : // g_idle_probe_hold_for_tests), so a test can make a take beat the evicting
8958 : // dispatch.
8959 2 : void chttpcli__arm_idle_probe_hold_for_tests(void) {
8960 2 : atomic_store(&g_idle_probe_hold_for_tests, 1);
8961 2 : }
8962 :
8963 2 : bool chttpcli__wait_idle_probe_held_for_tests(long timeout_ms) {
8964 2 : struct timespec ts = {.tv_sec = 0, .tv_nsec = 1000000L};
8965 12 : for (long i = 0; i < timeout_ms; i++) {
8966 12 : if (atomic_load(&g_idle_probe_hold_for_tests) == 2) return true;
8967 10 : nanosleep(&ts, NULL);
8968 : }
8969 0 : return atomic_load(&g_idle_probe_hold_for_tests) == 2;
8970 : }
8971 :
8972 2 : void chttpcli__release_idle_probe_hold_for_tests(void) {
8973 2 : int holding = 2;
8974 2 : if (!atomic_compare_exchange_strong(&g_idle_probe_hold_for_tests, &holding,
8975 : 3))
8976 0 : atomic_store(&g_idle_probe_hold_for_tests, 0);
8977 2 : }
8978 :
8979 : // Sets the delay around the 100-continue carry replay (0 turns it off), so a
8980 : // test can widen the window where a destroy may race the replay.
8981 2 : void chttpcli__set_continue_carry_replay_delay_ms_for_tests(long ms) {
8982 2 : atomic_store(&g_continue_carry_replay_delay_ms_for_tests, ms);
8983 2 : }
8984 :
8985 : // Arm the stray write dispatch at a take: Either the take arms the write
8986 : // direction under idle_lock and waits 200 ms, or it arms it before taking
8987 : // idle_lock, waits for the dispatch to classify the ctx as IDLE, then moves it
8988 : // to WRITING. The last one tells whether that hold happened.
8989 1 : void chttpcli__arm_stray_write_at_take_for_tests(void) {
8990 1 : atomic_store(&g_stray_write_at_take_for_tests, true);
8991 1 : }
8992 :
8993 1 : void chttpcli__arm_stray_write_before_take_for_tests(void) {
8994 1 : atomic_store(&g_stray_before_take_stage_for_tests, 1);
8995 1 : }
8996 :
8997 1 : bool chttpcli__stray_write_before_take_held_for_tests(void) {
8998 1 : bool held = atomic_load(&g_stray_before_take_stage_for_tests) >= 3;
8999 1 : atomic_store(&g_stray_before_take_stage_for_tests, 0);
9000 1 : return held;
9001 : }
9002 :
9003 : // Gives how often the write-direction fall-through put a registration back to
9004 : // reading, so the stray-write tests can see it happened.
9005 5 : unsigned long long chttpcli__stray_write_arm_restores_for_tests(void) {
9006 5 : return atomic_load_explicit(&g_stray_write_arm_restores_for_tests,
9007 : memory_order_relaxed);
9008 : }
9009 :
9010 : // Make the next reactivation of a reused connection fail, or the next read of a
9011 : // ctx that has already read once act as ECONNRESET, without touching the real
9012 : // registration or socket.
9013 1 : void chttpcli__force_reactivate_fail_once_for_tests(void) {
9014 1 : atomic_store(&g_force_reactivate_fail_for_tests, true);
9015 1 : }
9016 :
9017 1 : void chttpcli__force_async_hard_read_error_once_for_tests(void) {
9018 1 : atomic_store(&g_force_async_hard_read_error_for_tests, true);
9019 1 : }
9020 : #endif
9021 :
9022 : // Submits a buffered request to the async engine (Tier 2), for callers that
9023 : // don't want to block. Gives the future, whose result holds the response, or
9024 : // NULL on failure.
9025 739 : cthrpool_future *chttpcli_do_async(chttpcli h, const chttp_request *req) {
9026 739 : struct chttpclient *raw = chttpcli_resolve(h);
9027 739 : if (!raw) return NULL;
9028 738 : ccol_retval rv;
9029 738 : cthrpool_future *f = chttp_do_async_internal(raw, req, NULL, NULL, &rv);
9030 738 : chttpcli_resolve_unpin(raw);
9031 738 : return f;
9032 : }
9033 :
9034 : // Submits a streaming request to the async engine (Tier 2): The body goes to
9035 : // write_fn on an engine thread, so a large body needs no buffer. Gives the
9036 : // future, or NULL on failure.
9037 13 : cthrpool_future *chttpcli_do_async_streaming(chttpcli h,
9038 : const chttp_request *req,
9039 : chttpcli_write_fn write_fn,
9040 : void *write_ctx) {
9041 13 : if (!write_fn) return NULL;
9042 12 : struct chttpclient *raw = chttpcli_resolve(h);
9043 12 : if (!raw) return NULL;
9044 12 : ccol_retval rv;
9045 12 : cthrpool_future *f =
9046 12 : chttp_do_async_internal(raw, req, write_fn, write_ctx, &rv);
9047 12 : chttpcli_resolve_unpin(raw);
9048 12 : return f;
9049 : }
9050 :
9051 : // Gives the result a fulfilled future holds, so a caller of chttpcli_do_async
9052 : // can read its outcome.
9053 919 : chttpcli_async_result *chttpcli_async_result_get(cthrpool_future *f) {
9054 736 : return (chttpcli_async_result *)cthrpool_future_get(f);
9055 : }
9056 :
9057 : // Frees an async result and its response, through the procs copy the result
9058 : // carries (read into a local, since it lives in the freed block).
9059 913 : void chttpcli_async_result_free(chttpcli_async_result *result) {
9060 913 : if (!result) return;
9061 913 : ccol_memmgmt_procs procs;
9062 913 : ccol_memmgmt_procs *mp = NULL;
9063 913 : if (result->ccol__m_procs) {
9064 139 : procs = *result->ccol__m_procs;
9065 139 : mp = &procs;
9066 : }
9067 913 : ccol__mem_free(mp, result);
9068 : }
9069 :
9070 : // Pooled sync API (Tier 3)
9071 : //
9072 : // Runs req through the async engine and blocks on its future, so many threads
9073 : // can share the engine's connections with a synchronous call. Hands back the
9074 : // result as chttpcli_do does; the submit's failure code is returned as it is.
9075 191 : ccol_retval chttpcli_do_pooled(chttpcli h, const chttp_request *req,
9076 : chttpcli_response **resp_out) {
9077 191 : if (!resp_out) return ccol_invalid_args;
9078 190 : *resp_out = NULL;
9079 :
9080 190 : struct chttpclient *raw = chttpcli_resolve(h);
9081 190 : if (!raw) return ccol_invalid_args;
9082 186 : ccol_retval qrv;
9083 186 : cthrpool_future *f = chttp_do_async_internal(raw, req, NULL, NULL, &qrv);
9084 186 : chttpcli_resolve_unpin(raw);
9085 186 : if (!f) return qrv;
9086 :
9087 176 : chttpcli_async_result *result = chttpcli_async_result_get(f);
9088 176 : if (!result) {
9089 0 : cthrpool_future_free(f);
9090 0 : return ccol_unexpected_failure;
9091 : }
9092 :
9093 176 : ccol_retval rv = result->rv;
9094 176 : *resp_out = result->resp;
9095 176 : chttpcli_async_result_free(result);
9096 176 : cthrpool_future_free(f);
9097 176 : return rv;
9098 : }
9099 :
9100 : // Runs a streaming request through the async engine and blocks on it, the
9101 : // streaming form of chttpcli_do_pooled: The body goes to write_fn on an engine
9102 : // thread, and *status_code_out gets the final status.
9103 9 : ccol_retval chttpcli_do_pooled_streaming(chttpcli h, const chttp_request *req,
9104 : chttpcli_write_fn write_fn,
9105 : void *write_ctx,
9106 : int *status_code_out) {
9107 9 : if (!write_fn) return ccol_invalid_args;
9108 :
9109 8 : struct chttpclient *raw = chttpcli_resolve(h);
9110 8 : if (!raw) return ccol_invalid_args;
9111 8 : ccol_retval qrv;
9112 8 : cthrpool_future *f =
9113 8 : chttp_do_async_internal(raw, req, write_fn, write_ctx, &qrv);
9114 8 : chttpcli_resolve_unpin(raw);
9115 8 : if (!f) return qrv;
9116 :
9117 7 : chttpcli_async_result *result = chttpcli_async_result_get(f);
9118 5 : if (!result) {
9119 0 : cthrpool_future_free(f);
9120 0 : return ccol_unexpected_failure;
9121 : }
9122 :
9123 5 : ccol_retval rv = result->rv;
9124 5 : if (result->resp) {
9125 4 : if (rv == ccol_success && status_code_out) {
9126 4 : *status_code_out = result->resp->status_code;
9127 : }
9128 4 : chttpcli_resp_free(result->resp);
9129 : }
9130 5 : chttpcli_async_result_free(result);
9131 5 : cthrpool_future_free(f);
9132 5 : return rv;
9133 : }
9134 :
9135 : #ifdef RUNNING_UNIT_TESTS
9136 : // Client constructors
9137 : //
9138 : // The create step that chttpcli__arm_create_fault_for_tests armed, or
9139 : // CHTTPCLI__FAULT_NONE.
9140 : static atomic_int g_chttpcli_create_fault;
9141 :
9142 : // Arms one create step to fail, so a test can sweep every failure path of
9143 : // chttpcli_create_mp.
9144 10 : void chttpcli__arm_create_fault_for_tests(chttpcli__fault step) {
9145 10 : atomic_store(&g_chttpcli_create_fault, (int)step);
9146 10 : }
9147 :
9148 : // True once for the armed step, on the first create that reaches it.
9149 14200 : static bool chttpcli_create_fault_fires(chttpcli__fault step) {
9150 14200 : int expected = (int)step;
9151 14200 : return atomic_compare_exchange_strong(&g_chttpcli_create_fault, &expected,
9152 : (int)CHTTPCLI__FAULT_NONE);
9153 : }
9154 : // Evaluates to true when the armed create fault fires at step, so
9155 : // chttpcli_create_mp can fail one step on demand in a test build; without the
9156 : // test hooks it's false and a create never fails a step on its own.
9157 : #define CHTTPCLI_CREATE_FAULT(step) chttpcli_create_fault_fires(step)
9158 : #else
9159 : #define CHTTPCLI_CREATE_FAULT(step) false
9160 : #endif
9161 :
9162 : // Creates a client that allocates through mprocs (NULL for malloc); it's the
9163 : // constructor behind chttpcli_create and every tier's client. It builds the
9164 : // locks (the limiter's condition variable on CLOCK_MONOTONIC, the clock of the
9165 : // deadlines), the idle pools and the default TLS context, and acquires a handle
9166 : // slot last, so nothing can resolve a half-built client. Gives the handle, or
9167 : // CHTTPCLI_NULL with *err_str set.
9168 2845 : chttpcli chttpcli_create_mp(ccol_memmgmt_procs *mprocs, char **err_str) {
9169 2845 : if (mprocs && !ccol__verify_memmgmt_procs(mprocs, err_str))
9170 1 : return CHTTPCLI_NULL;
9171 :
9172 2844 : ccol_memmgmt_procs *mp = NULL;
9173 2844 : if (mprocs) {
9174 106 : mp = (ccol_memmgmt_procs *)mprocs->malloc(sizeof(ccol_memmgmt_procs));
9175 106 : if (!mp) {
9176 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to allocate mprocs");
9177 1 : return CHTTPCLI_NULL;
9178 : }
9179 105 : memcpy(mp, mprocs, sizeof(ccol_memmgmt_procs));
9180 : }
9181 :
9182 5686 : struct chttpclient *cli =
9183 2843 : (struct chttpclient *)ccol__mem_calloc(mp, 1, sizeof(struct chttpclient));
9184 2843 : if (!cli) {
9185 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to allocate client");
9186 1 : if (mp) mp->free(mp);
9187 1 : return CHTTPCLI_NULL;
9188 : }
9189 :
9190 2842 : cli->m_procs = mp;
9191 2842 : cli->tls = CHTTP_TLS_DEFAULT;
9192 2842 : cli->connect_timeout_us = CHTTPCLI_DEFAULT_CONNECT_TIMEOUT_US;
9193 2842 : cli->inactivity_timeout_us = CHTTPCLI_DEFAULT_INACTIVITY_TIMEOUT_US;
9194 5683 : if (CHTTPCLI_CREATE_FAULT(CHTTPCLI__FAULT_LOCK) ||
9195 2841 : ccol__mutex_init(cli->lock) != 0) {
9196 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to initialize mutex");
9197 1 : ccol__mem_free(mp, cli);
9198 1 : if (mp) mp->free(mp);
9199 1 : return CHTTPCLI_NULL;
9200 : }
9201 5681 : if (CHTTPCLI_CREATE_FAULT(CHTTPCLI__FAULT_AVAILABLE_CV) ||
9202 2840 : ccol_cond_var_init_monotonic(&cli->available) != 0) {
9203 1 : if (err_str)
9204 1 : *err_str = CCOL__ERR_STR("failed to initialize condition variable");
9205 1 : ccol__mutex_destroy(cli->lock);
9206 1 : ccol__mem_free(mp, cli);
9207 1 : if (mp) mp->free(mp);
9208 1 : return CHTTPCLI_NULL;
9209 : }
9210 5679 : if (CHTTPCLI_CREATE_FAULT(CHTTPCLI__FAULT_IDLE_ASYNC_DRAINED_CV) ||
9211 2839 : ccol__cond_var_init(cli->idle_async_drained) != 0) {
9212 1 : if (err_str)
9213 1 : *err_str = CCOL__ERR_STR("failed to initialize condition variable");
9214 1 : ccol__mutex_destroy(cli->lock);
9215 1 : ccol__cond_var_destroy(cli->available);
9216 1 : ccol__mem_free(mp, cli);
9217 1 : if (mp) mp->free(mp);
9218 1 : return CHTTPCLI_NULL;
9219 : }
9220 5677 : if (CHTTPCLI_CREATE_FAULT(CHTTPCLI__FAULT_ASYNC_COUNT_LOCK) ||
9221 2838 : ccol__mutex_init(cli->async_count_lock) != 0) {
9222 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to initialize mutex");
9223 1 : ccol__mutex_destroy(cli->lock);
9224 1 : ccol__cond_var_destroy(cli->available);
9225 1 : ccol__cond_var_destroy(cli->idle_async_drained);
9226 1 : ccol__mem_free(mp, cli);
9227 1 : if (mp) mp->free(mp);
9228 1 : return CHTTPCLI_NULL;
9229 : }
9230 5675 : if (CHTTPCLI_CREATE_FAULT(CHTTPCLI__FAULT_ASYNC_COUNT_DRAINED_CV) ||
9231 2837 : ccol__cond_var_init(cli->async_count_drained) != 0) {
9232 1 : if (err_str)
9233 1 : *err_str = CCOL__ERR_STR("failed to initialize condition variable");
9234 1 : ccol__mutex_destroy(cli->lock);
9235 1 : ccol__cond_var_destroy(cli->available);
9236 1 : ccol__cond_var_destroy(cli->idle_async_drained);
9237 1 : ccol__mutex_destroy(cli->async_count_lock);
9238 1 : ccol__mem_free(mp, cli);
9239 1 : if (mp) mp->free(mp);
9240 1 : return CHTTPCLI_NULL;
9241 : }
9242 :
9243 2837 : char *herr = NULL;
9244 5674 : cli->idle_pools =
9245 2837 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_string,
9246 : ccol_pointer, mp, NULL, NULL, &herr);
9247 2837 : if (!cli->idle_pools) {
9248 1 : if (err_str) *err_str = CCOL__ERR_STR("failed to allocate idle pool map");
9249 1 : ccol__mutex_destroy(cli->lock);
9250 1 : ccol__cond_var_destroy(cli->available);
9251 1 : ccol__cond_var_destroy(cli->idle_async_drained);
9252 1 : ccol__mutex_destroy(cli->async_count_lock);
9253 1 : ccol__cond_var_destroy(cli->async_count_drained);
9254 1 : ccol__mem_free(mp, cli);
9255 1 : if (mp) mp->free(mp);
9256 1 : return CHTTPCLI_NULL;
9257 : }
9258 :
9259 5672 : cli->idle_pools_async =
9260 2836 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_string,
9261 : ccol_pointer, mp, NULL, NULL, &herr);
9262 2836 : if (!cli->idle_pools_async) {
9263 1 : if (err_str)
9264 1 : *err_str = CCOL__ERR_STR("failed to allocate async idle pool map");
9265 1 : chashmap__destroy(cli->idle_pools);
9266 1 : ccol__mutex_destroy(cli->lock);
9267 1 : ccol__cond_var_destroy(cli->available);
9268 1 : ccol__cond_var_destroy(cli->idle_async_drained);
9269 1 : ccol__mutex_destroy(cli->async_count_lock);
9270 1 : ccol__cond_var_destroy(cli->async_count_drained);
9271 1 : ccol__mem_free(mp, cli);
9272 1 : if (mp) mp->free(mp);
9273 1 : return CHTTPCLI_NULL;
9274 : }
9275 :
9276 2835 : if (rebuild_tls_ctx_locked(cli) != ccol_success) {
9277 3 : if (err_str)
9278 3 : *err_str = CCOL__ERR_STR("failed to build default TLS context");
9279 3 : chashmap__destroy(cli->idle_pools);
9280 3 : chashmap__destroy(cli->idle_pools_async);
9281 3 : ccol__mutex_destroy(cli->lock);
9282 3 : ccol__cond_var_destroy(cli->available);
9283 3 : ccol__cond_var_destroy(cli->idle_async_drained);
9284 3 : ccol__mutex_destroy(cli->async_count_lock);
9285 3 : ccol__cond_var_destroy(cli->async_count_drained);
9286 3 : ccol__mem_free(mp, cli);
9287 3 : if (mp) mp->free(mp);
9288 3 : return CHTTPCLI_NULL;
9289 : }
9290 :
9291 2832 : chttpcli h = chttpcli_handle_slot_acquire(cli);
9292 2832 : if (h == 0) {
9293 9 : if (err_str) *err_str = CCOL__ERR_STR("failed to allocate client slot");
9294 9 : if (cli->tls_ctx) ctls_ctx_release(cli->tls_ctx);
9295 9 : chashmap__destroy(cli->idle_pools);
9296 9 : chashmap__destroy(cli->idle_pools_async);
9297 9 : ccol__mutex_destroy(cli->lock);
9298 9 : ccol__cond_var_destroy(cli->available);
9299 9 : ccol__cond_var_destroy(cli->idle_async_drained);
9300 9 : ccol__mutex_destroy(cli->async_count_lock);
9301 9 : ccol__cond_var_destroy(cli->async_count_drained);
9302 9 : ccol__mem_free(mp, cli);
9303 9 : if (mp) mp->free(mp);
9304 9 : return CHTTPCLI_NULL;
9305 : }
9306 : return h;
9307 : }
9308 :
9309 : // Client configuration
9310 : //
9311 : // Sets the size of h's concurrency limiter (0 picks the default), so an
9312 : // application bounds its parallel requests. Takes cli->lock.
9313 50 : ccol_retval chttpcli_set_pool_size(chttpcli h, size_t n) {
9314 50 : struct chttpclient *cli = chttpcli_resolve(h);
9315 50 : if (!cli) return ccol_invalid_args;
9316 48 : ccol__mutex_lock(cli->lock);
9317 48 : cli->configured_pool_size = n;
9318 48 : cli->pool_cap = resolve_pool_cap(n);
9319 48 : cli->pool_initialized = true;
9320 48 : ccol__cond_var_broadcast(cli->available);
9321 48 : ccol__mutex_unlock(cli->lock);
9322 48 : chttpcli_resolve_unpin(cli);
9323 48 : return ccol_success;
9324 : }
9325 :
9326 : // Set h's connect, request and inactivity timeouts in microseconds (0 for no
9327 : // limit), so no request waits for ever on a silent peer. Each takes cli->lock
9328 : // and affects requests that start later.
9329 19 : ccol_retval chttpcli_set_connect_timeout(chttpcli h, uint64_t us) {
9330 19 : struct chttpclient *cli = chttpcli_resolve(h);
9331 19 : if (!cli) return ccol_invalid_args;
9332 18 : ccol__mutex_lock(cli->lock);
9333 18 : cli->connect_timeout_us = us;
9334 18 : ccol__mutex_unlock(cli->lock);
9335 18 : chttpcli_resolve_unpin(cli);
9336 18 : return ccol_success;
9337 : }
9338 :
9339 175 : ccol_retval chttpcli_set_request_timeout(chttpcli h, uint64_t us) {
9340 175 : struct chttpclient *cli = chttpcli_resolve(h);
9341 175 : if (!cli) return ccol_invalid_args;
9342 174 : ccol__mutex_lock(cli->lock);
9343 174 : cli->request_timeout_us = us;
9344 174 : ccol__mutex_unlock(cli->lock);
9345 174 : chttpcli_resolve_unpin(cli);
9346 174 : return ccol_success;
9347 : }
9348 :
9349 16 : ccol_retval chttpcli_set_inactivity_timeout(chttpcli h, uint64_t us) {
9350 16 : struct chttpclient *cli = chttpcli_resolve(h);
9351 16 : if (!cli) return ccol_invalid_args;
9352 15 : ccol__mutex_lock(cli->lock);
9353 15 : cli->inactivity_timeout_us = us;
9354 15 : ccol__mutex_unlock(cli->lock);
9355 15 : chttpcli_resolve_unpin(cli);
9356 15 : return ccol_success;
9357 : }
9358 :
9359 : #ifdef RUNNING_UNIT_TESTS
9360 : // Reads the three timeouts of h for a test.
9361 2 : bool chttpcli__timeouts_for_tests(chttpcli h, uint64_t *connect_us,
9362 : uint64_t *request_us,
9363 : uint64_t *inactivity_us) {
9364 2 : struct chttpclient *cli = chttpcli_resolve(h);
9365 2 : if (!cli) return false;
9366 2 : ccol__mutex_lock(cli->lock);
9367 2 : *connect_us = cli->connect_timeout_us;
9368 2 : *request_us = cli->request_timeout_us;
9369 2 : *inactivity_us = cli->inactivity_timeout_us;
9370 2 : ccol__mutex_unlock(cli->lock);
9371 2 : chttpcli_resolve_unpin(cli);
9372 2 : return true;
9373 : }
9374 : #endif
9375 :
9376 : // Sets the cap on a buffered response body of h (0 for none), so a bad server
9377 : // can't make the client hold an unbounded body. Takes cli->lock.
9378 17 : ccol_retval chttpcli_set_max_response_body_size(chttpcli h, size_t max_bytes) {
9379 17 : struct chttpclient *cli = chttpcli_resolve(h);
9380 17 : if (!cli) return ccol_invalid_args;
9381 17 : ccol__mutex_lock(cli->lock);
9382 17 : cli->max_response_body_size = max_bytes;
9383 17 : ccol__mutex_unlock(cli->lock);
9384 17 : chttpcli_resolve_unpin(cli);
9385 17 : return ccol_success;
9386 : }
9387 :
9388 : // Replaces the client's TLS configuration and rebuilds its context. It refuses
9389 : // a certificate without its key (and the reverse), a CA bundle without a cert
9390 : // pair to go with mutual TLS settings, and insecure_skip_verify beside a CA
9391 : // bundle. A rebuild that runs out of memory puts the defaults back and gives
9392 : // ccol_not_enough_memory. Takes cli->lock.
9393 147 : ccol_retval chttpcli_set_tls(chttpcli h, const chttp_tls_config *tls) {
9394 147 : if (!h) return ccol_invalid_args;
9395 146 : if (tls && ((tls->cert_path && !tls->key_path) ||
9396 112 : (!tls->cert_path && tls->key_path)))
9397 : return ccol_invalid_args;
9398 129 : if (tls && tls->insecure_skip_verify && tls->ca_bundle_path)
9399 : return ccol_invalid_args;
9400 :
9401 143 : struct chttpclient *cli = chttpcli_resolve(h);
9402 143 : if (!cli) return ccol_invalid_args;
9403 :
9404 143 : ccol__mutex_lock(cli->lock);
9405 :
9406 143 : ccol__mem_free(cli->m_procs, cli->owned_cert_path);
9407 143 : ccol__mem_free(cli->m_procs, cli->owned_key_path);
9408 143 : ccol__mem_free(cli->m_procs, cli->owned_ca_bundle_path);
9409 143 : cli->owned_cert_path = cli->owned_key_path = cli->owned_ca_bundle_path = NULL;
9410 :
9411 143 : if (!tls) {
9412 15 : cli->tls = CHTTP_TLS_DEFAULT;
9413 15 : ccol_retval rv = rebuild_tls_ctx_locked(cli);
9414 15 : ccol__mutex_unlock(cli->lock);
9415 15 : chttpcli_resolve_unpin(cli);
9416 15 : return rv;
9417 : }
9418 :
9419 128 : if (tls->cert_path) {
9420 18 : cli->owned_cert_path = ccol_strdup(cli->m_procs, tls->cert_path);
9421 18 : if (!cli->owned_cert_path) goto oom;
9422 : }
9423 127 : if (tls->key_path) {
9424 17 : cli->owned_key_path = ccol_strdup(cli->m_procs, tls->key_path);
9425 17 : if (!cli->owned_key_path) goto oom;
9426 : }
9427 127 : if (tls->ca_bundle_path) {
9428 120 : cli->owned_ca_bundle_path = ccol_strdup(cli->m_procs, tls->ca_bundle_path);
9429 120 : if (!cli->owned_ca_bundle_path) goto oom;
9430 : }
9431 :
9432 126 : cli->tls = *tls;
9433 126 : cli->tls.cert_path = cli->owned_cert_path;
9434 126 : cli->tls.key_path = cli->owned_key_path;
9435 126 : cli->tls.ca_bundle_path = cli->owned_ca_bundle_path;
9436 :
9437 : {
9438 126 : if (rebuild_tls_ctx_locked(cli) != ccol_success) goto oom;
9439 120 : ccol__mutex_unlock(cli->lock);
9440 120 : chttpcli_resolve_unpin(cli);
9441 120 : return ccol_success;
9442 : }
9443 :
9444 8 : oom:
9445 8 : ccol__mem_free(cli->m_procs, cli->owned_cert_path);
9446 8 : ccol__mem_free(cli->m_procs, cli->owned_key_path);
9447 8 : ccol__mem_free(cli->m_procs, cli->owned_ca_bundle_path);
9448 8 : cli->owned_cert_path = cli->owned_key_path = cli->owned_ca_bundle_path = NULL;
9449 8 : cli->tls = CHTTP_TLS_DEFAULT;
9450 8 : rebuild_tls_ctx_locked(cli);
9451 8 : ccol__mutex_unlock(cli->lock);
9452 8 : chttpcli_resolve_unpin(cli);
9453 8 : return ccol_not_enough_memory;
9454 : }
9455 :
9456 : // Client destruction
9457 : //
9458 : // Destroys a client. It resolves the handle and marks the slot unused in one
9459 : // critical section, so a second destroy is fatal. It is fatal too from a
9460 : // request of this client on the calling thread and on an engine thread. It
9461 : // waits for Tier 1 calls (pins and in-flight count) and for the client's async
9462 : // chains, closes the idle connections of both pools, frees the client, and
9463 : // releases the slot last. Destroying the default client clears the singleton
9464 : // first.
9465 2817 : void chttpcli__destroy(chttpcli cli) {
9466 2817 : if (!cli) return;
9467 :
9468 2817 : chttpcli expected = cli;
9469 2817 : atomic_compare_exchange_strong(&default_client_bundler.client, &expected, 0);
9470 :
9471 2817 : ccol__call_once(chttpcli_slot_table.once, chttpcli_slot_table_init_globals);
9472 2817 : uint32_t idx = (uint32_t)(cli >> 32);
9473 2817 : uint32_t gen = (uint32_t)(cli & 0xFFFFFFFFu);
9474 2817 : ccol__rw_lock_wrlock(chttpcli_slot_table.rwlock);
9475 2817 : chttpcli_slot *slot = NULL;
9476 2817 : struct chttpclient *raw = NULL;
9477 2817 : if (idx < cvector_size(chttpcli_slot_table.slots)) {
9478 2817 : chttpcli_slot *s =
9479 2817 : (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, idx);
9480 2817 : if (s->in_use && s->generation == gen) {
9481 2815 : slot = s;
9482 2815 : raw = s->ptr;
9483 : }
9484 : }
9485 2815 : if (!raw) {
9486 2 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
9487 2 : ccol__fatal_err(
9488 : "chttpcli_destroy: handle is stale or already destroyed "
9489 : "(double-destroy / use-after-destroy of a chttpcli handle)");
9490 : }
9491 5630 : if (chttpcli_call_runs_on_this_thread(raw)) {
9492 3 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
9493 3 : ccol__fatal_err(
9494 : "chttpcli_destroy: called from inside a request of the same "
9495 : "client (a write_fn of that client), which would wait for itself");
9496 : }
9497 2812 : if (chttpcli_runs_on_engine_thread()) {
9498 2 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
9499 2 : ccol__fatal_err(
9500 : "chttpcli_destroy: called on a thread of the async engine (a "
9501 : "write_fn of chttpcli_do_async_streaming or "
9502 : "chttpcli_do_pooled_streaming); the destroy waits for work that "
9503 : "the engine threads run, so destroy the client on another thread");
9504 : }
9505 2810 : slot->in_use = false;
9506 2810 : ccol_pintable_retire(&chttpcli_pintable, idx);
9507 2810 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
9508 :
9509 2810 : ccol__mutex_lock(raw->lock);
9510 2810 : raw->destroying = true;
9511 2810 : ccol__cond_var_broadcast(raw->available);
9512 2810 : ccol__mutex_unlock(raw->lock);
9513 :
9514 : {
9515 2810 : long delay_ns = 1000;
9516 3040 : while (ccol_pintable_pins(&chttpcli_pintable, idx) > 0) {
9517 230 : struct timespec ts = {.tv_sec = 0, .tv_nsec = delay_ns};
9518 230 : nanosleep(&ts, NULL);
9519 230 : if (delay_ns < 1000000L) delay_ns *= 2;
9520 : }
9521 : }
9522 :
9523 2810 : ccol__mutex_lock(raw->lock);
9524 2810 : while (raw->in_flight_count > 0)
9525 0 : ccol__cond_var_wait(raw->available, raw->lock);
9526 2810 : ccol__mutex_unlock(raw->lock);
9527 :
9528 2810 : ccol__mutex_lock(raw->async_count_lock);
9529 2904 : while (raw->async_in_flight_count > 0)
9530 94 : ccol__cond_var_wait(raw->async_count_drained, raw->async_count_lock);
9531 2810 : ccol__mutex_unlock(raw->async_count_lock);
9532 :
9533 2810 : if (raw->idle_pools) {
9534 2810 : for (const ccol_chmap_entry_ref *e =
9535 2810 : ccol_chmap_oldest_entry(raw->idle_pools);
9536 2892 : e;) {
9537 82 : const cmap_pair *k, *v;
9538 82 : e = ccol_chmap_entry_read(e, &k, &v);
9539 82 : cvec list = read_cvec(v->ptr);
9540 82 : if (list) {
9541 : chttp_conn c;
9542 254 : while (cvector_size(list) > 0 &&
9543 86 : cvector_pop_back(list, &c) == ccol_success)
9544 86 : conn_teardown(raw->m_procs, &c);
9545 82 : cvector__destroy(list);
9546 : }
9547 : }
9548 2810 : chashmap__destroy(raw->idle_pools);
9549 : }
9550 :
9551 2810 : ccol__mutex_lock(raw->lock);
9552 2810 : if (raw->idle_pools_async) {
9553 2810 : for (const ccol_chmap_entry_ref *e =
9554 2810 : ccol_chmap_oldest_entry(raw->idle_pools_async);
9555 2926 : e;) {
9556 116 : const cmap_pair *k, *v;
9557 116 : e = ccol_chmap_entry_read(e, &k, &v);
9558 116 : cvec list = read_cvec(v->ptr);
9559 116 : if (!list) continue;
9560 116 : size_t n = cvector_size(list);
9561 234 : for (size_t i = 0; i < n; i++) {
9562 118 : chttp_async_ctx *actx = *(chttp_async_ctx **)cvector_at(list, i);
9563 118 : int afd = actx->fd;
9564 118 : if (afd >= 0) shutdown(afd, SHUT_RDWR);
9565 : }
9566 : }
9567 : }
9568 2923 : while (raw->idle_total_count_async > 0)
9569 113 : ccol__cond_var_wait(raw->idle_async_drained, raw->lock);
9570 2810 : ccol__mutex_unlock(raw->lock);
9571 :
9572 2810 : if (raw->idle_pools_async) {
9573 2810 : for (const ccol_chmap_entry_ref *e =
9574 2810 : ccol_chmap_oldest_entry(raw->idle_pools_async);
9575 2811 : e;) {
9576 1 : const cmap_pair *k, *v;
9577 1 : e = ccol_chmap_entry_read(e, &k, &v);
9578 1 : cvec list = read_cvec(v->ptr);
9579 1 : if (list) cvector__destroy(list);
9580 : }
9581 2810 : chashmap__destroy(raw->idle_pools_async);
9582 : }
9583 :
9584 2810 : if (raw->tls_ctx) ctls_ctx_release(raw->tls_ctx);
9585 :
9586 2810 : ccol__mutex_destroy(raw->lock);
9587 2810 : ccol__cond_var_destroy(raw->available);
9588 2810 : ccol__cond_var_destroy(raw->idle_async_drained);
9589 2810 : ccol__mutex_destroy(raw->async_count_lock);
9590 2810 : ccol__cond_var_destroy(raw->async_count_drained);
9591 :
9592 2810 : ccol_memmgmt_procs *mp = raw->m_procs;
9593 2810 : ccol__mem_free(mp, raw->owned_cert_path);
9594 94 : ccol__mem_free(mp, raw->owned_key_path);
9595 94 : ccol__mem_free(mp, raw->owned_ca_bundle_path);
9596 94 : ccol__mem_free(mp, raw);
9597 2810 : if (mp) mp->free(mp);
9598 :
9599 2810 : ccol__rw_lock_wrlock(chttpcli_slot_table.rwlock);
9600 2810 : chttpcli_slot *slot2 =
9601 2810 : (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, idx);
9602 2810 : slot2->ptr = NULL;
9603 2810 : slot2->generation++;
9604 2810 : chttpcli_free_index_release_locked(idx);
9605 2810 : chttpcli_release_slot_table_if_deferred_locked();
9606 2810 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
9607 : }
9608 :
9609 : // Request execution
9610 : //
9611 : // A response that starts arriving while Tier 1 sends the request (a 401 or 413
9612 : // from a server that never reads the body). Every tier follows curl's rules:
9613 : // interim responses are dropped and the upload continues, a final status of 300
9614 : // or more stops the upload once its head is parsed, and a 2xx keeps uploading.
9615 : // A connection whose response started early is never reused.
9616 : typedef struct {
9617 : chttp1_parser parser;
9618 : bool parser_live;
9619 : bool done;
9620 : bool keep_alive;
9621 : bool stop_send;
9622 : bool answered_early;
9623 : size_t n_discarded;
9624 : ccol_retval error;
9625 : } chttp_early_resp;
9626 :
9627 : // Sets every field but the parser, which is read only while parser_live is set.
9628 654 : static void early_resp_init(chttp_early_resp *e) {
9629 654 : e->parser_live = false;
9630 654 : e->done = false;
9631 654 : e->keep_alive = false;
9632 654 : e->stop_send = false;
9633 654 : e->answered_early = false;
9634 654 : e->n_discarded = 0;
9635 654 : e->error = ccol_success;
9636 : }
9637 :
9638 : // Releases the line spill of e's parser if the parser was started, on every
9639 : // path that ends an early response.
9640 647 : static void early_resp_release(chttp_early_resp *e) {
9641 0 : if (e->parser_live) chttp1_parser_release(&e->parser);
9642 647 : e->parser_live = false;
9643 : }
9644 :
9645 : // Starts the parser of e for the response.
9646 10 : static void early_resp_start_parser(chttp_early_resp *e,
9647 : chttp_parse_ctx *pctx) {
9648 10 : ccol__call_once(client_http1_settings_bundler.once, init_chttp1_settings);
9649 10 : chttp1_parser_init(&e->parser, &client_http1_settings_bundler.settings);
9650 10 : e->parser.data = pctx;
9651 10 : (void)chttp1_parser_enable_line_spill(&e->parser, pctx->mp);
9652 10 : e->parser_live = true;
9653 10 : }
9654 :
9655 : // Feeds data to e's parser while the request goes out, under the rules above;
9656 : // an interim response is dropped and parsing continues after it. The state
9657 : // lands in e and pctx.
9658 3556 : static void early_resp_feed(chttp_early_resp *e, chttp_parse_ctx *pctx,
9659 : const char *data, size_t len) {
9660 3556 : while (len > 0 && !e->done && e->error == ccol_success) {
9661 3556 : if (!e->parser_live) early_resp_start_parser(e, pctx);
9662 3556 : chttp1_errno err = chttp1_parser_execute(&e->parser, data, len);
9663 3556 : if (err == CHTTP1_PAUSED) {
9664 6 : size_t consumed = chttp1_parser_consumed(&e->parser);
9665 6 : bool keep_alive = chttp1_should_keep_alive(&e->parser);
9666 6 : chttp1_parser_release(&e->parser);
9667 6 : e->parser_live = false;
9668 6 : data += consumed;
9669 6 : len -= consumed;
9670 6 : if (pctx->status_code >= 100 && pctx->status_code < 200) {
9671 0 : if (e->n_discarded >= CHTTP_MAX_INTERIM_RESPONSES) {
9672 0 : e->error = ccol_http_transfer_aborted;
9673 0 : break;
9674 : }
9675 0 : e->n_discarded++;
9676 0 : ccol_retval rrv = parse_ctx_reset_for_continue(pctx);
9677 0 : if (rrv != ccol_success) e->error = rrv;
9678 0 : continue;
9679 : }
9680 6 : e->done = true;
9681 6 : e->keep_alive = keep_alive;
9682 6 : if (len > 0) {
9683 0 : pctx->trailing_garbage = true;
9684 0 : e->keep_alive = false;
9685 : }
9686 : break;
9687 : }
9688 3550 : if (err == CHTTP1_USER) {
9689 0 : e->error = pctx->too_large ? ccol_msg_too_large
9690 0 : : (pctx->error ? ccol_not_enough_memory
9691 : : ccol_http_transfer_aborted);
9692 0 : break;
9693 : }
9694 3550 : if (err != CHTTP1_OK) e->error = ccol_http_transfer_aborted;
9695 : break;
9696 : }
9697 3556 : if (e->done || e->error != ccol_success || pctx->status_code >= 300)
9698 6 : e->stop_send = true;
9699 3556 : }
9700 :
9701 : // Handles the peer closing while the request goes out, since a message the
9702 : // parser holds may end at that close; with none there is no answer.
9703 2 : static void early_resp_eof(chttp_early_resp *e, chttp_parse_ctx *pctx) {
9704 2 : e->stop_send = true;
9705 2 : if (!e->parser_live || e->done) return;
9706 1 : chttp1_errno fe = chttp1_parser_finish(&e->parser);
9707 1 : chttp1_parser_release(&e->parser);
9708 1 : e->parser_live = false;
9709 1 : if ((fe == CHTTP1_OK || fe == CHTTP1_PAUSED) && pctx->message_complete &&
9710 0 : !(pctx->status_code >= 100 && pctx->status_code < 200)) {
9711 0 : e->done = true;
9712 0 : e->keep_alive = false;
9713 : } else {
9714 1 : e->error = ccol_http_transfer_aborted;
9715 : }
9716 : }
9717 :
9718 : // Sends data[0..len) like chttp_send_all while taking in a response that
9719 : // arrives meanwhile, so an early 401 or 413 isn't lost to a reset. It polls for
9720 : // input in the same poll as for room. Gives ccol_success when the send
9721 : // completes or the rules stop it; *sent_out is the number of bytes that went
9722 : // out.
9723 648 : static ccol_retval chttp_send_all_watch(chttp_conn *conn, const char *data,
9724 : size_t len, chttp_deadline *overall,
9725 : chttp_parse_ctx *pctx,
9726 : chttp_early_resp *e,
9727 : bool *any_bytes_read_out,
9728 : size_t *sent_out) {
9729 648 : size_t sent = 0;
9730 648 : *sent_out = 0;
9731 648 : short want_events = POLLOUT;
9732 648 : char buf[8192];
9733 648 : bool read_blocked = false;
9734 5042 : while (sent < len && !e->stop_send) {
9735 4395 : int wait_ms;
9736 4395 : if (!deadline_remaining_ms(overall, &wait_ms) ||
9737 4395 : !conn_inactivity_left_ms(conn, &wait_ms))
9738 1 : return ccol_timed_out;
9739 8788 : bool readable =
9740 4394 : conn->tls && !read_blocked && ctls_conn_has_pending_input(conn->tls);
9741 4394 : bool writable = false;
9742 4394 : if (!readable) {
9743 : #ifdef RUNNING_UNIT_TESTS
9744 4394 : if (tls_dir_note_wait((want_events & POLLOUT) != 0)) {
9745 : writable = true;
9746 : } else
9747 : #endif
9748 : {
9749 4393 : struct pollfd pfd = {.fd = conn->fd,
9750 4393 : .events = (short)(want_events | POLLIN),
9751 : .revents = 0};
9752 4393 : struct timespec wait_start;
9753 4393 : clock_gettime(CLOCK_MONOTONIC, &wait_start);
9754 4393 : int rc = poll(&pfd, 1, wait_ms);
9755 4393 : conn_inactivity_charge(conn, &wait_start);
9756 4393 : if (rc < 0) {
9757 1 : if (errno == EINTR) continue;
9758 0 : return ccol_http_transfer_aborted;
9759 : }
9760 4393 : if (rc == 0) continue;
9761 4392 : if (pfd.revents & POLLNVAL) return ccol_http_transfer_aborted;
9762 4392 : readable = (pfd.revents & POLLIN) != 0;
9763 7793 : writable = (pfd.revents & (POLLOUT | POLLERR | POLLHUP)) != 0 ||
9764 3401 : (readable && want_events == POLLIN);
9765 : }
9766 : }
9767 :
9768 4393 : if (readable) {
9769 3564 : ssize_t n = conn_read(conn, buf, sizeof(buf));
9770 3564 : if (n > 0) {
9771 3554 : read_blocked = false;
9772 3554 : *any_bytes_read_out = true;
9773 3554 : early_resp_feed(e, pctx, buf, (size_t)n);
9774 3554 : e->answered_early = e->done || e->parser_live;
9775 3554 : continue;
9776 : }
9777 10 : if (n == 0) {
9778 2 : read_blocked = false;
9779 2 : early_resp_eof(e, pctx);
9780 2 : continue;
9781 : }
9782 8 : if (errno != EWOULDBLOCK) {
9783 1 : e->stop_send = true;
9784 1 : continue;
9785 : }
9786 7 : read_blocked = true;
9787 7 : if (!writable) continue;
9788 : }
9789 :
9790 836 : ssize_t n = conn_write(conn, data + sent, len - sent);
9791 836 : if (n < 0) {
9792 1 : if (errno == EWOULDBLOCK) {
9793 1 : if (conn->tls)
9794 1 : want_events = conn_tls_wants_write(conn->tls) ? POLLOUT : POLLIN;
9795 1 : continue;
9796 : }
9797 0 : if (errno == EPIPE || errno == ECONNRESET || errno == ENOTCONN) {
9798 0 : e->stop_send = true;
9799 0 : continue;
9800 : }
9801 : return ccol_http_transfer_aborted;
9802 : }
9803 835 : if (n == 0) {
9804 0 : e->stop_send = true;
9805 0 : continue;
9806 : }
9807 835 : sent += (size_t)n;
9808 835 : *sent_out = sent;
9809 835 : want_events = POLLOUT;
9810 : }
9811 647 : if (e->error != ccol_success) return e->error;
9812 : return ccol_success;
9813 : }
9814 :
9815 : // Reads the rest of the response once chttp_send_all_watch is done, the message
9816 : // its parser holds or the next one. request_complete false means the connection
9817 : // is never reused.
9818 646 : static ccol_retval chttp_early_resp_finish(
9819 : chttp_conn *conn, chttp_parse_ctx *pctx, chttp_deadline *overall,
9820 : chttp_early_resp *e, bool request_complete, bool *keep_alive_out,
9821 : bool *any_bytes_read_out) {
9822 646 : ccol_retval rv;
9823 646 : if (e->done) {
9824 6 : *keep_alive_out = e->keep_alive;
9825 6 : rv = ccol_success;
9826 640 : } else if (e->parser_live) {
9827 3 : char *leftover = NULL;
9828 3 : size_t leftover_len = 0;
9829 3 : rv = chttp_read_message_with(&e->parser, conn, pctx, overall, NULL, NULL, 0,
9830 : keep_alive_out, any_bytes_read_out, &leftover,
9831 : &leftover_len);
9832 3 : chttp1_parser_release(&e->parser);
9833 3 : e->parser_live = false;
9834 3 : if (rv == ccol_success && pctx->status_code >= 100 &&
9835 : pctx->status_code < 200) {
9836 0 : if (e->n_discarded >= CHTTP_MAX_INTERIM_RESPONSES) {
9837 : rv = ccol_http_transfer_aborted;
9838 : } else {
9839 0 : rv = parse_ctx_reset_for_continue(pctx);
9840 : }
9841 0 : if (rv == ccol_success) {
9842 0 : char *next_leftover = NULL;
9843 0 : size_t next_leftover_len = 0;
9844 0 : rv = chttp_read_message_loop(conn, pctx, overall, NULL, leftover,
9845 0 : leftover_len, 0, e->n_discarded + 1,
9846 : keep_alive_out, any_bytes_read_out,
9847 : &next_leftover, &next_leftover_len);
9848 0 : ccol__mem_free(pctx->mp, leftover);
9849 0 : leftover = next_leftover;
9850 0 : leftover_len = next_leftover_len;
9851 : }
9852 : }
9853 3 : if (rv == ccol_success && leftover_len > 0) {
9854 0 : pctx->trailing_garbage = true;
9855 0 : *keep_alive_out = false;
9856 : }
9857 3 : ccol__mem_free(pctx->mp, leftover);
9858 : } else {
9859 637 : char *leftover = NULL;
9860 637 : size_t leftover_len = 0;
9861 637 : rv = chttp_read_message_loop(conn, pctx, overall, NULL, NULL, 0, 0,
9862 : e->n_discarded, keep_alive_out,
9863 : any_bytes_read_out, &leftover, &leftover_len);
9864 636 : if (rv == ccol_success && leftover_len > 0) {
9865 0 : pctx->trailing_garbage = true;
9866 0 : *keep_alive_out = false;
9867 : }
9868 636 : ccol__mem_free(pctx->mp, leftover);
9869 : }
9870 645 : if (rv == ccol_success && !request_complete) *keep_alive_out = false;
9871 645 : return rv;
9872 : }
9873 :
9874 : // Sends wire (the serialized request, body last) and reads the response. With
9875 : // use_100_continue the header block goes first and the body waits up to
9876 : // CHTTP_100_CONTINUE_WAIT_US for an answer; only the first byte of a message is
9877 : // bounded by that window. retry_unsafe is set once a request that isn't
9878 : // replayable went out in full, or a body went after a "100 Continue", so the
9879 : // caller never resends it.
9880 654 : static ccol_retval chttp_send_and_read(
9881 : chttp_conn *conn, const char *wire, size_t wire_len, size_t body_len,
9882 : bool use_100_continue, bool replayable, chttp_deadline *overall,
9883 : chttp_parse_ctx *pctx, bool *keep_alive_out, bool *any_bytes_read_out,
9884 : bool *retry_unsafe_out) {
9885 654 : *retry_unsafe_out = false;
9886 654 : chttp_early_resp early;
9887 654 : early_resp_init(&early);
9888 654 : size_t sent = 0;
9889 654 : ccol_retval prv;
9890 654 : if (!use_100_continue) {
9891 640 : prv = chttp_send_all_watch(conn, wire, wire_len, overall, pctx, &early,
9892 : any_bytes_read_out, &sent);
9893 640 : if (!replayable && sent == wire_len) *retry_unsafe_out = true;
9894 640 : if (prv == ccol_success)
9895 639 : prv = chttp_early_resp_finish(conn, pctx, overall, &early,
9896 639 : !early.answered_early && sent == wire_len,
9897 : keep_alive_out, any_bytes_read_out);
9898 639 : early_resp_release(&early);
9899 639 : return prv;
9900 : }
9901 :
9902 14 : size_t header_len = wire_len - body_len;
9903 14 : prv = chttp_send_all(conn, wire, header_len, overall);
9904 14 : if (prv != ccol_success) return prv;
9905 :
9906 : #ifdef RUNNING_UNIT_TESTS
9907 14 : __atomic_add_fetch(&chttp_tier1_continue_waits, 1, __ATOMIC_RELAXED);
9908 : #endif
9909 14 : chttp_deadline continue_dl = deadline_make(CHTTP_100_CONTINUE_WAIT_US);
9910 14 : chttp_deadline wait_dl = deadline_earlier(continue_dl, *overall);
9911 :
9912 14 : char *leftover = NULL;
9913 14 : size_t leftover_len = 0;
9914 14 : prv = chttp_read_message_loop(conn, pctx, overall, &wait_dl, NULL, 0, 100, 0,
9915 : keep_alive_out, any_bytes_read_out, &leftover,
9916 : &leftover_len);
9917 14 : if (prv == ccol_timed_out) {
9918 1 : int overall_ms;
9919 1 : if (!deadline_remaining_ms(overall, &overall_ms)) return ccol_timed_out;
9920 1 : prv = chttp_send_all_watch(conn, wire + header_len, body_len, overall, pctx,
9921 : &early, any_bytes_read_out, &sent);
9922 1 : if (!replayable && sent == body_len) *retry_unsafe_out = true;
9923 1 : if (prv == ccol_success)
9924 1 : prv = chttp_early_resp_finish(conn, pctx, overall, &early,
9925 1 : !early.answered_early && sent == body_len,
9926 : keep_alive_out, any_bytes_read_out);
9927 1 : early_resp_release(&early);
9928 1 : return prv;
9929 : }
9930 13 : if (prv != ccol_success) {
9931 2 : ccol__mem_free(pctx->mp, leftover);
9932 2 : return prv;
9933 : }
9934 :
9935 11 : if (pctx->status_code != 100) {
9936 4 : *keep_alive_out = false;
9937 4 : if (leftover_len > 0) pctx->trailing_garbage = true;
9938 4 : ccol__mem_free(pctx->mp, leftover);
9939 4 : return ccol_success;
9940 : }
9941 :
9942 7 : prv = parse_ctx_reset_for_continue(pctx);
9943 7 : if (prv != ccol_success) {
9944 0 : ccol__mem_free(pctx->mp, leftover);
9945 0 : return prv;
9946 : }
9947 :
9948 7 : *retry_unsafe_out = true;
9949 7 : *any_bytes_read_out = false;
9950 7 : if (leftover_len > 0) {
9951 2 : *any_bytes_read_out = true;
9952 2 : early_resp_feed(&early, pctx, leftover, leftover_len);
9953 : }
9954 7 : ccol__mem_free(pctx->mp, leftover);
9955 7 : prv = early.error;
9956 7 : if (prv == ccol_success)
9957 7 : prv = chttp_send_all_watch(conn, wire + header_len, body_len, overall, pctx,
9958 : &early, any_bytes_read_out, &sent);
9959 7 : if (prv == ccol_success)
9960 6 : prv = chttp_early_resp_finish(conn, pctx, overall, &early,
9961 6 : !early.answered_early && sent == body_len,
9962 : keep_alive_out, any_bytes_read_out);
9963 7 : early_resp_release(&early);
9964 7 : return prv;
9965 : }
9966 :
9967 : // Runs one Tier 1 request on cli and follows its redirects; chttpcli_do,
9968 : // chttpcli_do_streaming and the convenience calls all end here. It sets
9969 : // *resp_out to NULL first and anchors the overall deadline before taking a
9970 : // limiter slot, so time spent waiting for a slot counts. It pushes a call
9971 : // frame, takes a TLS snapshot under cli->lock, and per hop takes a pooled
9972 : // connection or opens one, sends and reads. A reused connection that died
9973 : // before any response byte is retried once when the request is safe to resend.
9974 : // A connection whose request asked for close is never pooled.
9975 630 : static ccol_retval chttp_do_internal(struct chttpclient *cli,
9976 : const chttp_request *req, bool streaming,
9977 : chttpcli_write_fn user_write_fn,
9978 : void *user_write_ctx,
9979 : chttpcli_response **resp_out,
9980 : int *status_code_out) {
9981 630 : if (!streaming) {
9982 615 : if (!resp_out) return ccol_invalid_args;
9983 615 : *resp_out = NULL;
9984 : }
9985 630 : if (!cli || !req) return ccol_invalid_args;
9986 626 : if (streaming && !user_write_fn) return ccol_invalid_args;
9987 :
9988 625 : uint64_t request_timeout_us;
9989 625 : ccol__mutex_lock(cli->lock);
9990 625 : request_timeout_us = cli->request_timeout_us;
9991 625 : ccol__mutex_unlock(cli->lock);
9992 625 : chttp_deadline overall_dl = deadline_make(request_timeout_us);
9993 :
9994 625 : ccol_retval rv = slot_acquire(cli, &overall_dl);
9995 625 : if (rv != ccol_success) return rv;
9996 :
9997 623 : ccol_memmgmt_procs *mp = cli->m_procs;
9998 :
9999 623 : uint64_t connect_timeout_us;
10000 623 : uint64_t inactivity_timeout_us;
10001 623 : bool verify_host;
10002 623 : ctls_ctx *tls_ctx;
10003 623 : bool tls_ctx_usable;
10004 623 : size_t max_response_body_size;
10005 623 : uint64_t tls_generation;
10006 623 : ccol__mutex_lock(cli->lock);
10007 623 : tls_ctx_retry_if_oom_locked(cli);
10008 623 : connect_timeout_us = cli->connect_timeout_us;
10009 623 : inactivity_timeout_us = cli->inactivity_timeout_us;
10010 623 : tls_ctx = cli->tls_ctx;
10011 623 : tls_ctx_usable = cli->tls_ctx_usable;
10012 623 : bool tls_ctx_oom = cli->tls_ctx_oom;
10013 623 : tls_generation = cli->tls_generation;
10014 623 : max_response_body_size = cli->max_response_body_size;
10015 1246 : verify_host =
10016 623 : !cli->tls.insecure_skip_verify && !cli->tls.insecure_skip_hostname_check;
10017 623 : if (tls_ctx) ctls_ctx_retain(tls_ctx);
10018 623 : ccol__mutex_unlock(cli->lock);
10019 :
10020 623 : char *cur_url = ccol_strdup(mp, req->url);
10021 622 : if (!cur_url) {
10022 1 : if (tls_ctx) ctls_ctx_release(tls_ctx);
10023 1 : slot_release(cli);
10024 1 : return ccol_not_enough_memory;
10025 : }
10026 :
10027 622 : chttp_request_body empty_body = CHTTP_NO_BODY;
10028 622 : chttp_method cur_method = req->method;
10029 622 : chttp_request_body cur_body = req->body;
10030 :
10031 622 : char *carried_auth = NULL;
10032 622 : char *carried_auth_origin = NULL;
10033 :
10034 622 : char *initial_origin_key = NULL;
10035 622 : unsigned redirect_drops = 0;
10036 :
10037 622 : ccol_retval result = ccol_http_too_many_redirects;
10038 :
10039 622 : for (int hop = 0; hop <= CHTTP_MAX_REDIRECTS; hop++) {
10040 710 : chttp_url url;
10041 710 : ccol_retval prv = parse_chttp_url(mp, cur_url, &url);
10042 710 : if (prv != ccol_success) {
10043 : result = prv;
10044 621 : break;
10045 : }
10046 :
10047 690 : if (!initial_origin_key) {
10048 604 : initial_origin_key = ccol_strdup(mp, url.origin_key);
10049 603 : if (!initial_origin_key) {
10050 1 : url_free(mp, &url);
10051 1 : result = ccol_not_enough_memory;
10052 1 : break;
10053 : }
10054 : } else {
10055 86 : redirect_drops =
10056 86 : redirect_header_drops(initial_origin_key, url.origin_key);
10057 : }
10058 :
10059 689 : if (url.is_https && !tls_ctx_usable) {
10060 2 : url_free(mp, &url);
10061 2 : result = tls_ctx_unusable_code(tls_ctx_oom);
10062 : break;
10063 : }
10064 :
10065 687 : const char *effective_auth = NULL;
10066 687 : if (url.userinfo_authorization) {
10067 : effective_auth = url.userinfo_authorization;
10068 684 : } else if (carried_auth &&
10069 3 : origin_keys_same(carried_auth_origin, url.origin_key)) {
10070 687 : effective_auth = carried_auth;
10071 : }
10072 687 : if (url.userinfo_authorization) {
10073 6 : char *na = ccol_strdup(mp, url.userinfo_authorization);
10074 6 : char *no = ccol_strdup(mp, url.origin_key);
10075 6 : if (!na || !no) {
10076 0 : ccol__mem_free(mp, na);
10077 0 : ccol__mem_free(mp, no);
10078 0 : url_free(mp, &url);
10079 0 : result = ccol_not_enough_memory;
10080 0 : break;
10081 : }
10082 6 : ccol__mem_free(mp, carried_auth);
10083 6 : ccol__mem_free(mp, carried_auth_origin);
10084 : carried_auth = na;
10085 : carried_auth_origin = no;
10086 684 : } else if (carried_auth &&
10087 3 : !origin_keys_same(carried_auth_origin, url.origin_key)) {
10088 1 : ccol__mem_free(mp, carried_auth);
10089 1 : ccol__mem_free(mp, carried_auth_origin);
10090 : carried_auth = NULL;
10091 : carried_auth_origin = NULL;
10092 : }
10093 :
10094 687 : chttp_request hop_req = *req;
10095 687 : hop_req.method = cur_method;
10096 687 : hop_req.body = cur_body;
10097 :
10098 687 : char *wire = NULL;
10099 687 : size_t wire_len = 0;
10100 687 : chttp_header_presence hop_hp = {0};
10101 687 : prv = serialize_request(mp, &hop_req, &url, effective_auth, redirect_drops,
10102 : &wire, &wire_len, &hop_hp);
10103 687 : if (prv != ccol_success) {
10104 15 : url_free(mp, &url);
10105 15 : result = prv;
10106 15 : break;
10107 : }
10108 :
10109 672 : chttp_deadline connect_dl = deadline_make(connect_timeout_us);
10110 :
10111 672 : chttp_conn conn;
10112 672 : bool reused = idle_pool_take(cli, url.origin_key, &conn);
10113 672 : if (!reused) {
10114 542 : prv = conn_open(mp, &url, url.is_https, tls_ctx, verify_host,
10115 : tls_generation, &connect_dl, &overall_dl, &conn);
10116 542 : if (prv != ccol_success) {
10117 23 : ccol__mem_free(mp, wire);
10118 23 : url_free(mp, &url);
10119 23 : result = prv;
10120 23 : break;
10121 : }
10122 : }
10123 649 : conn_inactivity_start(&conn, inactivity_timeout_us);
10124 :
10125 649 : chttp_parse_ctx pctx;
10126 649 : memset(&pctx, 0, sizeof(pctx));
10127 649 : pctx.mp = mp;
10128 649 : pctx.is_head_request = (cur_method == CHTTP_HEAD);
10129 :
10130 649 : chttp_bodybuf bb;
10131 649 : memset(&bb, 0, sizeof(bb));
10132 649 : bb.mp = mp;
10133 649 : bb.max_size = max_response_body_size;
10134 649 : pctx.requested_sink_fn = streaming ? user_write_fn : sink_buffered;
10135 649 : pctx.requested_sink_ctx = streaming ? user_write_ctx : &bb;
10136 :
10137 649 : char *herr = NULL;
10138 1298 : pctx.headers =
10139 649 : chashmap_create_full(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE,
10140 : ccol_string, ccol_string, mp, NULL, NULL, &herr);
10141 649 : if (!pctx.headers) {
10142 1 : ccol__mem_free(mp, wire);
10143 1 : conn_teardown(mp, &conn);
10144 1 : url_free(mp, &url);
10145 1 : result = ccol_not_enough_memory;
10146 1 : break;
10147 : }
10148 :
10149 648 : bool body_carrying_method =
10150 648 : (cur_method == CHTTP_POST || cur_method == CHTTP_PUT ||
10151 648 : cur_method == CHTTP_PATCH);
10152 648 : bool has_explicit_expect = hop_hp.has_expect;
10153 17 : bool use_100_continue = req->expect_continue && !has_explicit_expect &&
10154 662 : body_carrying_method && cur_body.data &&
10155 : cur_body.len > 0;
10156 :
10157 648 : bool keep_alive = false;
10158 648 : bool any_bytes_read = false;
10159 648 : bool retry_unsafe = false;
10160 648 : bool replayable = request_is_replayable(cur_method, &hop_hp);
10161 648 : prv = chttp_send_and_read(&conn, wire, wire_len, cur_body.len,
10162 : use_100_continue, replayable, &overall_dl, &pctx,
10163 : &keep_alive, &any_bytes_read, &retry_unsafe);
10164 647 : if (prv != ccol_success && reused && !any_bytes_read && !retry_unsafe) {
10165 6 : conn_teardown(mp, &conn);
10166 6 : chttp_deadline retry_connect_dl = deadline_make(connect_timeout_us);
10167 6 : prv = conn_open(mp, &url, url.is_https, tls_ctx, verify_host,
10168 : tls_generation, &retry_connect_dl, &overall_dl, &conn);
10169 6 : if (prv == ccol_success) {
10170 6 : reused = false;
10171 6 : conn_inactivity_start(&conn, inactivity_timeout_us);
10172 6 : prv = chttp_send_and_read(
10173 : &conn, wire, wire_len, cur_body.len, use_100_continue, replayable,
10174 : &overall_dl, &pctx, &keep_alive, &any_bytes_read, &retry_unsafe);
10175 : }
10176 : }
10177 647 : ccol__mem_free(mp, wire);
10178 647 : if (prv != ccol_success) {
10179 35 : conn_teardown(mp, &conn);
10180 35 : parse_ctx_free_fields(&pctx);
10181 35 : ccol__mem_free(mp, bb.buf);
10182 35 : url_free(mp, &url);
10183 35 : result = prv;
10184 35 : break;
10185 : }
10186 :
10187 1224 : bool reusable =
10188 612 : keep_alive && !pctx.trailing_garbage && !hop_hp.request_close;
10189 612 : if (reusable) {
10190 224 : idle_pool_offer(cli, &conn);
10191 : } else {
10192 388 : conn_teardown(mp, &conn);
10193 : }
10194 :
10195 612 : if (pctx.will_redirect) {
10196 99 : if (hop >= CHTTP_MAX_REDIRECTS) {
10197 1 : parse_ctx_free_fields(&pctx);
10198 1 : ccol__mem_free(mp, bb.buf);
10199 1 : url_free(mp, &url);
10200 1 : result = ccol_http_too_many_redirects;
10201 12 : break;
10202 : }
10203 98 : ccol_retval resolve_rv = ccol_success;
10204 98 : char *next_url =
10205 98 : resolve_redirect_url(mp, &url, pctx.location, &resolve_rv);
10206 98 : bool transport_refused = false;
10207 288 : ccol_retval transport_rv =
10208 : next_url
10209 92 : ? redirect_transport_allowed(
10210 92 : mp, &url, next_url, req->prevent_tls_downgrade_on_redirect)
10211 98 : : ccol_success;
10212 92 : if (transport_rv != ccol_success) {
10213 4 : ccol__mem_free(mp, next_url);
10214 : next_url = NULL;
10215 : transport_refused = true;
10216 : }
10217 98 : bool preserve = (pctx.status_code == 307 || pctx.status_code == 308);
10218 98 : parse_ctx_free_fields(&pctx);
10219 98 : ccol__mem_free(mp, bb.buf);
10220 98 : url_free(mp, &url);
10221 98 : ccol__mem_free(mp, cur_url);
10222 98 : cur_url = NULL;
10223 :
10224 98 : if (!next_url) {
10225 10 : result = transport_refused ? transport_rv : resolve_rv;
10226 : break;
10227 : }
10228 88 : cur_url = next_url;
10229 88 : if (!preserve && cur_method != CHTTP_HEAD) {
10230 86 : cur_method = CHTTP_GET;
10231 86 : cur_body = empty_body;
10232 : }
10233 88 : continue;
10234 : }
10235 :
10236 513 : if (streaming) {
10237 11 : if (status_code_out) *status_code_out = pctx.status_code;
10238 11 : parse_ctx_free_fields(&pctx);
10239 11 : url_free(mp, &url);
10240 11 : result = ccol_success;
10241 11 : break;
10242 : }
10243 :
10244 502 : chttpcli_response *resp = resp_alloc(mp);
10245 502 : if (!resp) {
10246 1 : parse_ctx_free_fields(&pctx);
10247 1 : ccol__mem_free(mp, bb.buf);
10248 1 : url_free(mp, &url);
10249 1 : result = ccol_not_enough_memory;
10250 1 : break;
10251 : }
10252 501 : resp->status_code = pctx.status_code;
10253 501 : resp->body = bb.buf;
10254 501 : resp->body_len = bb.len;
10255 501 : resp->headers = pctx.headers;
10256 501 : pctx.headers = NULL;
10257 501 : resp->ccol__field_lines = pctx.field_lines;
10258 501 : pctx.field_lines = NULL;
10259 501 : parse_ctx_free_fields(&pctx);
10260 501 : url_free(mp, &url);
10261 501 : *resp_out = resp;
10262 501 : result = ccol_success;
10263 501 : break;
10264 : }
10265 :
10266 621 : ccol__mem_free(mp, cur_url);
10267 84 : ccol__mem_free(mp, carried_auth);
10268 84 : ccol__mem_free(mp, carried_auth_origin);
10269 621 : ccol__mem_free(mp, initial_origin_key);
10270 621 : if (tls_ctx) ctls_ctx_release(tls_ctx);
10271 621 : slot_release(cli);
10272 621 : return result;
10273 : }
10274 :
10275 : // Runs a buffered request on h synchronously (Tier 1), the plain blocking call.
10276 : // *resp_out is NULL before anything can fail, even for a stale handle.
10277 620 : ccol_retval chttpcli_do(chttpcli h, const chttp_request *req,
10278 : chttpcli_response **resp_out) {
10279 620 : if (!resp_out) return ccol_invalid_args;
10280 619 : *resp_out = NULL;
10281 619 : struct chttpclient *raw = chttpcli_resolve(h);
10282 619 : if (!raw) return ccol_invalid_args;
10283 615 : chttpcli_call_frame frame;
10284 615 : chttpcli_call_push(&frame, raw, false);
10285 615 : ccol_retval rv =
10286 615 : chttp_do_internal(raw, req, false, NULL, NULL, resp_out, NULL);
10287 615 : chttpcli_call_pop(&frame);
10288 615 : chttpcli_resolve_unpin(raw);
10289 615 : return rv;
10290 : }
10291 :
10292 : // Runs a streaming request on h synchronously, so a large body needs no buffer:
10293 : // the body goes to write_fn and *status_code_out gets the final status.
10294 16 : ccol_retval chttpcli_do_streaming(chttpcli h, const chttp_request *req,
10295 : chttpcli_write_fn write_fn, void *write_ctx,
10296 : int *status_code_out) {
10297 16 : struct chttpclient *raw = chttpcli_resolve(h);
10298 16 : if (!raw) return ccol_invalid_args;
10299 15 : chttpcli_call_frame frame;
10300 15 : chttpcli_call_push(&frame, raw, false);
10301 15 : ccol_retval rv = chttp_do_internal(raw, req, true, write_fn, write_ctx, NULL,
10302 : status_code_out);
10303 14 : chttpcli_call_pop(&frame);
10304 14 : chttpcli_resolve_unpin(raw);
10305 14 : return rv;
10306 : }
10307 :
10308 : // Default client
10309 : //
10310 : // Creates the default client once, for chttp_default_client; client_at_exit
10311 : // destroys it before OpenSSL's cleanup.
10312 29 : static void init_default_client(void) {
10313 29 : ccol__call_once(cli_engine_bundler.exit_hook_once, client_exit_hook_install);
10314 29 : atomic_store(&default_client_bundler.client, chttpcli_create(NULL));
10315 29 : }
10316 :
10317 : // Destroys the default client from client_at_exit, so its threads are gone
10318 : // before OpenSSL's cleanup, unless a Tier 1 call runs on it (it may be the call
10319 : // that called exit()). chttp_default_client gives CHTTPCLI_NULL afterwards.
10320 30 : static void default_client_destroy_if_idle(void) {
10321 30 : chttpcli h = atomic_load(&default_client_bundler.client);
10322 30 : if (!h) return;
10323 28 : struct chttpclient *raw = chttpcli_resolve(h);
10324 28 : if (!raw) return;
10325 28 : ccol__mutex_lock(raw->lock);
10326 28 : bool busy = raw->in_flight_count > 0;
10327 28 : ccol__mutex_unlock(raw->lock);
10328 28 : chttpcli_resolve_unpin(raw);
10329 28 : if (busy) return;
10330 28 : if (atomic_compare_exchange_strong(&default_client_bundler.client, &h, 0))
10331 28 : chttpcli__destroy(h);
10332 : }
10333 :
10334 : // Gives the process's default client, created on first use, for the convenience
10335 : // calls and for callers that need no client of their own.
10336 308 : chttpcli chttp_default_client(void) {
10337 308 : ccol__call_once(default_client_bundler.once, init_default_client);
10338 308 : return atomic_load(&default_client_bundler.client);
10339 : }
10340 :
10341 : // At unload or exit, clears the default client handle and then destroys the
10342 : // client (so the defensive compare-and-swap in destroy can't race), and frees
10343 : // the slot table when no client is left, or leaves that to the last destroy.
10344 39 : __attribute__((destructor)) static void cleanup_default_client(void) {
10345 39 : chttpcli cli = atomic_exchange(&default_client_bundler.client, 0);
10346 39 : if (cli) chttpcli__destroy(cli);
10347 :
10348 39 : ccol__call_once(chttpcli_slot_table.once, chttpcli_slot_table_init_globals);
10349 39 : ccol__rw_lock_wrlock(chttpcli_slot_table.rwlock);
10350 39 : if (chttpcli_any_slot_live_locked()) {
10351 3 : chttpcli_slot_table.release_deferred = true;
10352 : } else {
10353 36 : chttpcli_release_slot_table_locked();
10354 : }
10355 39 : ccol__rw_lock_unlock(chttpcli_slot_table.rwlock);
10356 39 : }
10357 :
10358 : // Tells whether any slot names a client. It reads ptr and not in_use, because a
10359 : // destroy clears in_use first and still needs the table until its last step.
10360 : // The caller holds the write lock.
10361 39 : static bool chttpcli_any_slot_live_locked(void) {
10362 39 : size_t slot_count = cvector_size(chttpcli_slot_table.slots);
10363 74 : for (size_t i = 0; i < slot_count; i++) {
10364 38 : chttpcli_slot *slot =
10365 38 : (chttpcli_slot *)cvector_at(chttpcli_slot_table.slots, i);
10366 38 : if (slot->ptr != NULL) return true;
10367 : }
10368 : return false;
10369 : }
10370 :
10371 : // Releases the slot table if the exit destructor deferred that and no slot is
10372 : // live any more; the last destroy calls it. Out of line, so the destroy path
10373 : // keeps its shape. The caller holds the write lock.
10374 : static __attribute__((noinline)) void
10375 2810 : chttpcli_release_slot_table_if_deferred_locked(void) {
10376 2810 : if (chttpcli_slot_table.release_deferred &&
10377 0 : !chttpcli_any_slot_live_locked()) {
10378 0 : chttpcli_release_slot_table_locked();
10379 : }
10380 2810 : }
10381 :
10382 : // Frees the bookkeeping of the slot table and the pin index, setting each to
10383 : // NULL so a later call sees it released, at exit or after the last destroy. The
10384 : // caller holds the write lock and no slot is live.
10385 36 : static void chttpcli_release_slot_table_locked(void) {
10386 36 : cvector_destroy(chttpcli_slot_table.slots);
10387 36 : cvector_destroy(chttpcli_slot_table.free_indices);
10388 36 : ccol_pintable_dispose(&chttpcli_pintable);
10389 36 : chttpcli_slot_table.release_deferred = false;
10390 36 : }
10391 :
10392 : // Convenience API
10393 : //
10394 : // Runs req on the default client, for callers that need no client of their own.
10395 : // *resp_out is set to NULL first.
10396 266 : ccol_retval chttp_do_default(const chttp_request *req,
10397 : chttpcli_response **resp_out) {
10398 266 : if (!resp_out) return ccol_invalid_args;
10399 266 : *resp_out = NULL;
10400 266 : chttpcli cli = chttp_default_client();
10401 266 : if (!cli) return ccol_unexpected_failure;
10402 265 : return chttpcli_do(cli, req, resp_out);
10403 : }
10404 :
10405 : // Builds a request from the arguments and runs it on the default client. A bad
10406 : // method or an inconsistent body is ccol_invalid_args before the create, so a
10407 : // failed create means only a failed allocation.
10408 240 : ccol_retval chttp_perform(chttp_method method, const char *url,
10409 : const chttp_request_body *body, chmap headers,
10410 : chttpcli_response **resp_out) {
10411 240 : if (!resp_out) return ccol_invalid_args;
10412 234 : *resp_out = NULL;
10413 234 : if (!url) return ccol_invalid_args;
10414 226 : if ((unsigned)method >= (unsigned)CHTTP_ANY) return ccol_invalid_args;
10415 224 : if (body && !body->data && body->len > 0) return ccol_invalid_args;
10416 220 : chttp_request *req = chttp_request_create(method, url, body, NULL);
10417 220 : if (!req) return ccol_not_enough_memory;
10418 :
10419 220 : req->headers = headers;
10420 220 : ccol_retval rv = chttp_do_default(req, resp_out);
10421 220 : req->headers = NULL;
10422 220 : chttp_request_free(req);
10423 220 : return rv;
10424 : }
10425 :
10426 : // Run a GET, POST, PUT, DELETE or PATCH on the default client through
10427 : // chttp_perform, the one-line forms of the most common requests.
10428 169 : ccol_retval chttp_get(const char *url, chttpcli_response **resp_out) {
10429 169 : return chttp_perform(CHTTP_GET, url, NULL, NULL, resp_out);
10430 : }
10431 :
10432 31 : ccol_retval chttp_post(const char *url, const chttp_request_body *body,
10433 : chttpcli_response **resp_out) {
10434 31 : return chttp_perform(CHTTP_POST, url, body, NULL, resp_out);
10435 : }
10436 :
10437 5 : ccol_retval chttp_put(const char *url, const chttp_request_body *body,
10438 : chttpcli_response **resp_out) {
10439 5 : return chttp_perform(CHTTP_PUT, url, body, NULL, resp_out);
10440 : }
10441 :
10442 4 : ccol_retval chttp_delete(const char *url, chttpcli_response **resp_out) {
10443 4 : return chttp_perform(CHTTP_DELETE, url, NULL, NULL, resp_out);
10444 : }
10445 :
10446 6 : ccol_retval chttp_patch(const char *url, const chttp_request_body *body,
10447 : chttpcli_response **resp_out) {
10448 6 : return chttp_perform(CHTTP_PATCH, url, body, NULL, resp_out);
10449 : }
10450 :
10451 : // Response API
10452 : //
10453 : // The stack buffer size for the response header lookups (as for requests).
10454 : enum { CHTTP_RESP_NAME_STACK_BUF = CHTTP_NAME_STACK_BUF };
10455 : // Lower-cases name with resp's procs for the response header accessors, on the
10456 : // stack when it fits, so looking up known names on every response allocates
10457 : // nothing. Gives the buffer or NULL.
10458 340 : static char *resp_lower_name(const chttpcli_response *resp, const char *name,
10459 : char *stack_buf, size_t *len_out) {
10460 340 : return lower_name_copy(resp->ccol__m_procs, name, stack_buf, len_out);
10461 : }
10462 :
10463 : // Looks up the lower-case name in resp's header map, for the header accessors.
10464 131 : static const char *resp_map_value(const chttpcli_response *resp,
10465 : const char *lower, size_t nlen) {
10466 131 : cmap_pair kp = {.ptr = (void *)lower, .size = nlen + 1};
10467 131 : cmap_pair vp;
10468 131 : if (chashmap_get_elem_ref((chmap)resp->headers, &kp, &vp) != ccol_success)
10469 : return NULL;
10470 121 : return (const char *)vp.ptr;
10471 : }
10472 :
10473 : // Finds occurrence index of the lower-case name and counts all occurrences into
10474 : // *count_out (may be NULL), for the header accessors. A repeated name has
10475 : // records in the field lines; a name that appears once has only its map entry.
10476 231 : static const char *resp_occurrence(const chttpcli_response *resp,
10477 : const char *lower, size_t nlen, size_t index,
10478 : size_t *count_out) {
10479 231 : const chttp_field_lines *lines =
10480 : (const chttp_field_lines *)resp->ccol__field_lines;
10481 231 : size_t seen = 0;
10482 231 : const char *found = NULL;
10483 231 : const chttp_field_slot *slot = field_lines_find(lines, lower, nlen);
10484 681 : for (uint32_t o = slot ? slot->head : 0; o;) {
10485 365 : chttp_field_rec r = field_rec_at(lines, o - 1);
10486 365 : if (seen == index) {
10487 203 : found = field_rec_value(lines, o - 1, &r);
10488 203 : if (!count_out) return found;
10489 : }
10490 219 : seen++;
10491 219 : o = r.next;
10492 : }
10493 85 : if (seen == 0) {
10494 22 : const char *v = resp_map_value(resp, lower, nlen);
10495 22 : seen = v ? 1 : 0;
10496 22 : found = (v && index == 0) ? v : NULL;
10497 : }
10498 85 : if (count_out) *count_out = seen;
10499 : return found;
10500 : }
10501 :
10502 : // Gives the value of name in resp (repeated occurrences joined by ", ",
10503 : // Set-Cookie its first), or NULL. It's the accessor for most callers.
10504 110 : const char *chttpcli_resp_header(const chttpcli_response *resp,
10505 : const char *name) {
10506 110 : if (!resp || !name || !resp->headers) return NULL;
10507 109 : char stack_lower[CHTTP_RESP_NAME_STACK_BUF];
10508 109 : size_t nlen;
10509 109 : char *lower = resp_lower_name(resp, name, stack_lower, &nlen);
10510 109 : if (!lower) return NULL;
10511 109 : const char *v = resp_map_value(resp, lower, nlen);
10512 109 : if (lower != stack_lower) ccol__mem_free(resp->ccol__m_procs, lower);
10513 : return v;
10514 : }
10515 :
10516 : // Gives how many times name appears in resp, so a caller can walk a repeated
10517 : // field.
10518 68 : size_t chttpcli_resp_header_count(const chttpcli_response *resp,
10519 : const char *name) {
10520 68 : if (!resp || !name || !resp->headers) return 0;
10521 66 : char stack_lower[CHTTP_RESP_NAME_STACK_BUF];
10522 66 : size_t nlen;
10523 66 : char *lower = resp_lower_name(resp, name, stack_lower, &nlen);
10524 66 : if (!lower) return 0;
10525 66 : size_t count = 0;
10526 66 : (void)resp_occurrence(resp, lower, nlen, 0, &count);
10527 66 : if (lower != stack_lower) ccol__mem_free(resp->ccol__m_procs, lower);
10528 66 : return count;
10529 : }
10530 :
10531 : // Gives occurrence index of name in resp, or NULL, for walking a repeated field
10532 : // such as Set-Cookie.
10533 167 : const char *chttpcli_resp_header_at(const chttpcli_response *resp,
10534 : const char *name, size_t index) {
10535 167 : if (!resp || !name || !resp->headers) return NULL;
10536 165 : char stack_lower[CHTTP_RESP_NAME_STACK_BUF];
10537 165 : size_t nlen;
10538 165 : char *lower = resp_lower_name(resp, name, stack_lower, &nlen);
10539 165 : if (!lower) return NULL;
10540 165 : const char *v = resp_occurrence(resp, lower, nlen, index, NULL);
10541 165 : if (lower != stack_lower) ccol__mem_free(resp->ccol__m_procs, lower);
10542 : return v;
10543 : }
10544 :
10545 : // Frees a response through the procs copy it carries, so it may be freed after
10546 : // its client is gone.
10547 2310 : void chttpcli_resp_free(chttpcli_response *resp) {
10548 2310 : if (!resp) return;
10549 1278 : ccol_memmgmt_procs procs;
10550 1278 : ccol_memmgmt_procs *mp = NULL;
10551 1278 : if (resp->ccol__m_procs) {
10552 131 : procs = *resp->ccol__m_procs;
10553 131 : mp = &procs;
10554 : }
10555 1278 : ccol__mem_free(mp, resp->body);
10556 1279 : if (resp->headers) chashmap__destroy((chmap)resp->headers);
10557 1279 : field_lines_free(mp, (chttp_field_lines *)resp->ccol__field_lines);
10558 1279 : ccol__mem_free(mp, resp);
10559 : }
|