include/hyperman/hm_core.h

filter: Statementstmt 92.3% 3025 / 3363 (103 uncoverable) Branchbran 79.0% 2229 / 3384 (515 uncoverable) Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 85.7% 5254 / 6747 (618 uncoverable) CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/hyperman/hm_compress.h ↑ Summary include/hyperman/hm_parse.h »
1 #ifndef HM_CORE_H
2 #define HM_CORE_H
3  
4 /* Hyperman loop core: connections, HTTP parse and
5 * serialize, PSGI dispatch (sync, streaming, Future), watchers, deferred
6 * queue, timeouts/fairness, listener, workers, and the prefork supervisor.
7 * Requires hm_future.h (futures + C closures) and hyperman.h (backends). */
8  
9 #define HM_POOL_MAX 1024 /* pooled hm_conn structs kept per loop */
10 #define HM_IOV_MAX 64 /* writev: header + up to 63 body chunks */
11 #define HM_SWEEP_SECS 5.0 /* timeout sweep interval */
12 #define HM_HIDX_STACK 64 /* header-line index on the stack before
13 falling back to the loop's growable one */
14 #define HM_WB_HIWAT (1 << 20) /* queued response bytes a connection may
15 hold before hm_process stops serving
16 its pipeline until the client reads */
17 #define HM_WB_KEEP (1 << 20) /* a pooled connection keeps a write
18 buffer up to this; larger ones are
19 freed, so one big response does not
20 pin its buffer for the pool's life */
21  
22 #include "hm_win.h" /* the socket/IO shim: hm_os_*, hm_iovec, hm_memmem.
23 First, so every later header sees the platform
24 headers it pulls; a passthrough on POSIX. */
25 #include "hm_parse.h" /* hm_hline, hm_parse_index, hm_chunked_* */
26 #include "hm_proxy.h" /* the PROXY protocol header, v1 and v2 */
27 #ifndef _WIN32
28 #include <pwd.h> /* user => 'name' (hm_resolve_drop) */
29 #include <grp.h> /* group => 'name' */
30 #include <netdb.h> /* getaddrinfo (hm_resolve) */
31 #include <sys/un.h> /* path => listeners */
32 #include <sys/stat.h>
33 #endif
34 #include "hm_abi.h" /* public C ABI: hm_abi table + callback typedefs */
35  
36 #if defined(HM_HAVE_SENDFILE_LINUX)
37 #include <sys/sendfile.h>
38 #elif defined(HM_HAVE_SENDFILE_FREEBSD) || defined(HM_HAVE_SENDFILE_MACOS)
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/uio.h>
42 #endif
43  
44 typedef struct hm_loop hm_loop;
45  
46 /* A streaming response body (filehandle / IO-object PSGI bodies): instead
47 * of slurping the whole file into one SV, the connection drains its write
48 * buffer and refills it a chunk at a time - or hands the file straight to
49 * sendfile(2) on a plaintext socket. `sv` keeps the body (and so its fd)
50 * alive; kind 1 reads the fd at an explicit offset (pread), kind 2 pulls
51 * a getline object. At most HM_BSRC_CHUNK response-body bytes are ever
52 * buffered per connection. */
53 #define HM_BSRC_CHUNK 65536
54 #define HM_SENDFILE_MAX (1 << 20) /* bytes per sendfile(2) call */
55 typedef struct {
56 int kind; /* 0 none, 1 regular-file fd, 2 getline */
57 int fd; /* kind 1: borrowed from the body's handle */
58 off_t off; /* kind 1: next byte to read */
59 UV remaining; /* bytes still owed to the client */
60 SV *sv; /* the body, owned: keeps the fd alive */
61 unsigned char nosf; /* sendfile(2) refused; use the read path */
62 } hm_bsrc;
63 typedef struct hm_conn hm_conn;
64  
65 /* A bound listening socket. The loop holds an array of these; a connection
66 * remembers the one it was accepted on so TLS-wrap, SERVER_PORT, and the
67 * built-in https redirect are all per-listener. */
68 typedef struct {
69 int fd; /* bound listener fd, -1 until bound */
70 char *host; /* bind host (owned) */
71 int port;
72 void *tls_ctx; /* SSL_CTX*; NULL = plain */
73 int http2; /* per-listener h2 (h2c / ALPN) */
74 int http3; /* per-listener h3: a QUIC listener on the
75 * same host and port, over UDP. Intrinsically
76 * the same origin as the TLS listener it sits
77 * on - same certificate, same SNI registry -
78 * which is why it is a flag here rather than
79 * a listener of its own (hm_quic.h) */
80 int redirect_https; /* 0 = off; else target https port for 301 */
81  
82 /* What the context above was built from, kept so a worker can build
83 * another one. The spec these are copied from lives in the parent's
84 * cfg, which a worker does not hold - and without them tls_reload
85 * would have nothing to rebuild with. Owned copies: the spec's
86 * strings belong to the parent's config and outlive nothing here. */
87 char *tls_cert; /* NULL on a plain listener */
88 char *tls_key;
89 char *tls_ca; /* NULL unless client certs are verified */
90 int tls_verify;
91 SV *tls_sni; /* the SNI map run() was given, or NULL: a
92 * tls_reload with no map rebuilds from it */
93  
94 /* The QUIC half, when http3 is on. It rides on this listener rather
95 * than being one of its own because h3 is intrinsically the same origin
96 * as the TLS listener it advertises from: same host, same port number,
97 * same certificate, same SNI registry - only the transport differs. */
98 int udp_fd; /* bound SOCK_DGRAM fd, or -1 */
99 void *quic; /* hm_quic_srv *, or NULL */
100 void *quic_ctx; /* the QUIC-side SSL_CTX */
101 char *altsvc; /* precomputed Alt-Svc value, or NULL */
102 int starved; /* accept hit EMFILE: read interest is off
103 * until a short timer puts it back */
104 int is_unix; /* a path listener: no peer address, no
105 * TCP options, SERVER_PORT 0 */
106 int proxy_protocol; /* a connection starts with a PROXY header
107 * (hm_proxy_readable), before any TLS */
108 } hm_listener;
109  
110 struct hm_conn {
111 int fd;
112 char *rbuf; /* owned; grows for large bodies, capacity kept */
113 size_t rlen, rcap;
114 char *wbuf; /* owned; capacity kept across requests */
115 size_t wlen, woff, wcap;
116 int writing; /* write watcher armed? */
117 int keepalive;
118 int awaiting; /* parked on a pending Future? */
119 UV id; /* generation id, guards fd reuse */
120 UV nreqs; /* requests served on this connection */
121 SV *io_sv; /* psgix.io: dup'd filehandle, per conn */
122 SV *cid_sv; /* psgix.hyperman.conn: [fd, id], per conn */
123 SV *peer_sv; /* cached env values, constant for the */
124 SV *peer_host_sv; /* life of the connection: REMOTE_ADDR, */
125 SV *peer_port_sv; /* REMOTE_HOST, REMOTE_PORT, */
126 SV *sname_sv; /* SERVER_NAME, */
127 SV *sport_sv; /* SERVER_PORT */
128 SV *resp_f; /* pending response Future (awaiting) */
129 SV *env_sv; /* held while parked, for access_log */
130 void *h2; /* hm_h2_sess* when in HTTP/2 mode */
131 void *ssl; /* SSL* when this is a TLS connection */
132 const char *tls_proto; /* SSL_PROTOCOL / SSL_CIPHER for $env. */
133 const char *tls_cipher; /* OpenSSL-owned, valid for the conn */
134 void *tls_peer; /* hm_tls_peer*, only if a client cert */
135 unsigned char tls_hs; /* TLS handshake in progress */
136 unsigned char tls_r_wants_w; /* SSL_read blocked wanting write */
137 unsigned char tls_failed; /* SSL_new failed at accept: closed */
138 unsigned char stream_open; /* a streamed response has begun and
139 * not closed: one per request */
140 UV body_rx; /* body bytes since body_phase began */
141 time_t body_t0; /* when body_phase began */
142 unsigned char tls_w_wants_r; /* SSL_write blocked wanting read */
143 unsigned char ktls_tx; /* TX offloaded to the kernel (reporting
144 * only - the write paths ask OpenSSL
145 * itself, see hm_ktls_tx) */
146 unsigned char recv_fallback; /* this connection reads off readiness for
147 * good: completion was unavailable or
148 * refused once, and a persistent watcher
149 * is armed */
150 unsigned char recv_inflight; /* a completion-mode recv is outstanding
151 * into c->rbuf; the kernel may write to
152 * it at any moment, so it must not be
153 * grown, freed or reused until the
154 * completion lands */
155 unsigned char recv_lent; /* reading off a lent readiness watcher
156 * while requests wait unconsumed in
157 * rbuf (hm_recv_unsafe) */
158 unsigned char again_queued; /* hm_again_push has it for the top of
159 * the next turn (hm_run_again) */
160 unsigned char detached; /* app took the socket (see hm_detach) */
161 unsigned char tunnel; /* a 101 stream handle owns the bytes both
162 * ways (hm_stream_open): what the peer
163 * sends goes to the handle's read half,
164 * never to the request parser */
165 unsigned char accepts_gzip; /* this request's Accept-Encoding */
166 unsigned char cont_sent; /* a 100 Continue has gone out for the
167 * request being read. Per request, and
168 * on the connection rather than on the
169 * stack, because the headers stay in rbuf
170 * and hm_process re-reads them on every
171 * readable event until the body is whole */
172 unsigned char is_head; /* the request being answered is a HEAD:
173 * the headers go out, the body does not */
174 unsigned char in_app; /* a synchronous handler for this
175 * connection is on the C stack. A ->get
176 * inside it pumps this same loop, so a
177 * close asked for meanwhile is deferred
178 * to the frame that called the app */
179 unsigned char close_deferred; /* hm_close was asked for while in_app */
180 unsigned char read_paused; /* read interest dropped while in_app with
181 * a full buffer (hm_read_pause) */
182 unsigned char pp_wait; /* awaiting the PROXY header: nothing
183 * else reads this socket until it is
184 * parsed (hm_proxy_readable) */
185 char proxy_addr[INET6_ADDRSTRLEN]; /* the proxy that connected, once
186 * the header named the real client */
187 int proxy_port;
188 unsigned char backlogged; /* hm_process stopped on a full write
189 * buffer; the drain re-queues it */
190 unsigned char req_11; /* the request on the plate is HTTP/1.1 */
191 unsigned char stream_mode; /* a streamed body's framing (HM_SM_*) */
192 unsigned char stream_done; /* a streamed body ended with keep-alive
193 * on: the drain serves the pipeline */
194 UV stream_serial; /* streamed responses begun on this conn; a
195 * Writer carries the one it belongs to, so a
196 * writer kept past its response cannot end
197 * the next one */
198 UV stream_left; /* HM_SM_LENGTH: body octets still owed */
199 size_t chunk_pos; /* chunked body: octets validated so far, so
200 * a re-scan starts at the last chunk boundary
201 * rather than at the first chunk */
202 size_t chunk_dec; /* decoded octets up to chunk_pos */
203 hm_bsrc bsrc; /* streaming body being dripped, if any */
204 int last_status; /* last response status/bytes (logging) */
205 size_t last_blen;
206 char peer[INET6_ADDRSTRLEN]; /* REMOTE_ADDR, filled at accept */
207 int peer_port; /* REMOTE_PORT, filled at accept */
208 time_t last_active;
209 time_t req_start; /* first byte of an incomplete request */
210 time_t last_rx; /* last read that delivered bytes: the body
211 * phase is timed from here, not from the
212 * request's first byte */
213 unsigned char body_phase; /* headers complete, body still arriving:
214 * hm_sweep applies body_timeout */
215 /* A body being drained to a temp file rather than accumulated in rbuf.
216 * -1 when not spilling. The fd becomes psgi.input and the handle owns it
217 * from that moment; the file is unlinked at creation, so nothing is left
218 * behind however the request ends. */
219 int spill_fd;
220 long spill_got; /* body octets already written to it */
221 hm_conn *lru_prev, *lru_next;
222 hm_conn *pool_next;
223 hm_loop *loop;
224 hm_listener *lst; /* listener this conn was accepted on */
225 };
226  
227 /* QUIC's expiry min-heap. hm_quic.h owns every operation on it; the type is
228 * here because hm_loop carries one BY VALUE, so the "has QUIC anything to do"
229 * test on the loop's hot path is a load and a compare rather than a
230 * dereference. ngtcp2 rearms a connection's expiry after essentially every
231 * packet, and none of the backend timer vtables can carry that - see the
232 * header comment in hm_quic.h for the costing. */
233 typedef struct hm_qconn hm_qconn;
234 typedef struct { hm_qconn **a; int n, cap; } hm_qheap;
235  
236 /* app-owned fd watcher: a one-shot Future, a persistent Perl callback, or a
237 * persistent C callback (the ABI path - dispatched with no Perl frame) */
238 typedef struct {
239 SV *sv; /* future or Perl cb; NULL for a C watcher */
240 unsigned char is_cb;
241 hm_abi_io_cb c_cb; /* C watcher; checked before sv */
242 void *c_ud;
243 } hm_iow;
244  
245 /* timer watcher */
246 #define HM_TW_FUTURE 0
247 #define HM_TW_CB 1
248 #define HM_TW_SWEEP 2
249 #define HM_TW_HARDSTOP 3
250 #define HM_TW_C 4 /* ABI: C callback, cancellable via handle */
251 typedef struct hm_tw_s {
252 int kind;
253 SV *sv;
254 hm_loop *loop;
255 hm_abi_timer_cb c_cb; /* HM_TW_C only */
256 void *c_ud;
257 double due; /* oneshot deadline, monotonic seconds; 0 = none */
258 /* Cancelled, and waiting on the loop's graveyard to be freed. The
259 * backends fill a whole event array before any of it is dispatched, so
260 * a timer cancelled from an earlier event in the batch may still be
261 * named by a later one; freeing it at once was a use after free. */
262 unsigned char dead;
263 struct hm_tw_s *gy_next;
264 } hm_tw;
265  
266 /* The deadline a oneshot is armed for, on the clock hm_dispatch checks it
267 * against. The backend's own timer is a wake-up hint, not the deadline:
268 * kqueue's EVFILT_TIMER on NetBSD is a callout in scheduler ticks, and in a
269 * VM those ticks run ahead of CLOCK_MONOTONIC. */
270 #define hm_tw_due(secs) ((double)hm_now_ns() / 1e9 + (secs))
271  
272 typedef struct { int fd; UV id; } hm_again;
273  
274 /* The events one hm_loop_run frame took from the backend and has not yet
275 * dispatched. A nested run (a handler's ->get) sits inside one of them, and
276 * the rest are already out of the kernel: a oneshot timer is never reported
277 * again, so a nested wait for the event next to it waited forever. Each
278 * frame links its batch here, and a nested one dispatches what its callers
279 * still hold before it waits. */
280 typedef struct hm_batch_s {
281 hm_event *evs;
282 int n, i; /* i: the next one to dispatch */
283 struct hm_batch_s *up; /* the batch of the frame that called us */
284 } hm_batch;
285  
286 /* One piece of an access-log line. The format string is compiled to these
287 * once, in the parent, so writing a line is a walk over an array and never a
288 * parse: a literal run, an $env value (the key SV carries its hash), or one
289 * of the computed fields. */
290 #define HM_LT_LIT 0 /* literal bytes */
291 #define HM_LT_ENV 1 /* $env->{key}, escaped; "-" when absent */
292 #define HM_LT_DASH 2 /* %l: always "-" */
293 #define HM_LT_STATUS 3 /* %s, %>s */
294 #define HM_LT_BYTES 4 /* %b: body bytes, "-" when there were none */
295 #define HM_LT_BYTES0 5 /* %B: body bytes, "0" when there were none */
296 #define HM_LT_TIME 6 /* %t: [dd/Mon/YYYY:HH:MM:SS +ZZZZ] */
297 #define HM_LT_TIME_ISO 7 /* json: YYYY-MM-DDTHH:MM:SS+ZZZZ */
298 #define HM_LT_REQLINE 8 /* %r: METHOD URI PROTO */
299 #define HM_LT_QUERY 9 /* %q: ?query, or nothing */
300 #define HM_LT_PID 10 /* %P */
301 #define HM_LT_DUR_US 11 /* %D: microseconds since the request was built */
302 #define HM_LT_DUR_S 12 /* %T: whole seconds of the same */
303 typedef struct {
304 int kind;
305 char *lit; /* HM_LT_LIT: owned */
306 size_t litlen;
307 SV *key; /* HM_LT_ENV: a shared-string SV, hash precomputed */
308 } hm_logtok;
309  
310 struct hm_loop {
311 int pid; /* the process that created this loop
312 (hm_os_getpid: MSVC has no pid_t) */
313 hm_backend *be;
314 hm_conn **conns; /* [HM_MAXFD] */
315 hm_iow *io_r, *io_w; /* [HM_MAXFD] app io watchers */
316 AV *deferred; /* run-soon callbacks */
317 hm_again *again; /* conns with buffered requests */
318 int again_n, again_cap;
319 hm_hline *hidx; /* header-line index overflow buffer */
320 int hidx_cap;
321 hm_conn *lru_head, *lru_tail;
322 hm_conn *pool; int pool_n;
323 /* Completion-mode receive (io_uring only, opt-in). `completion` is set
324 * once at loop start when the backend can do it and the operator asked.
325 * `quar` holds read buffers belonging to connections that closed with a
326 * recv still outstanding - see hm_quar_push. */
327 int completion;
328 struct hm_quar *quar;
329 hm_tw *tw_gy; /* cancelled timers, freed between batches */
330 int starved_retry; /* a listener waits for hm_accept_unstarve */
331 hm_tw *sweep_tw;
332 SV *app; /* server: PSGI app coderef */
333 hm_listener *listeners; /* server: bound listeners */
334 int nlisteners;
335 int attached; /* server attached (>=1 listener) */
336 int nconns;
337 int stop;
338 int stopping; /* graceful shutdown in progress */
339 int running;
340 hm_batch *batch; /* the innermost run's (see hm_batch) */
341 int perl_owned; /* created via Hyperman::Loop->new */
342 time_t now;
343 double idle_timeout;
344 double header_timeout;
345 double body_timeout; /* a body stalled this long is closed */
346 double request_timeout; /* whole request ceiling; 0 = none */
347 UV body_min_rate; /* bytes/s floor over a body; 0 = none */
348 int max_pipeline; /* fairness: requests per conn per wakeup */
349 size_t max_read; /* request size ceiling (headers + body) */
350 int compress; /* gzip responses (0 = off, the default) */
351 size_t compress_min; /* below this, gzip buys nothing */
352 int compress_level; /* gzip level; HZ_LEVEL by default */
353 SV *compress_types; /* AV of extra compressible media types */
354 SV *self_sv; /* cached psgix.loop wrapper */
355 SV *log_cb; /* access_log coderef, or NULL */
356 int log_fd; /* fast access-log fd (C writer), or -1 */
357 char *log_buf; /* pending Combined-format log lines */
358 size_t log_len, log_cap;
359 time_t log_ts_sec; /* second the cached stamp below is for */
360 char log_ts[32]; /* "dd/Mon/YYYY:HH:MM:SS +ZZZZ", 1Hz */
361 time_t date_sec; /* second the Date header below is for */
362 char date_hdr[40]; /* "Date: <IMF-fixdate>\r\n", 1Hz */
363 hm_logtok *logtok; /* the compiled access_log_format */
364 int nlogtok;
365 int log_json; /* values escaped for JSON, not CLF */
366 int log_wants_t0; /* the format reads %D/%T: stamp requests */
367 time_t log_iso_sec; /* second the ISO stamp below is for */
368 char log_iso[40]; /* "YYYY-MM-DDTHH:MM:SS+ZZZZ", 1Hz */
369 UV requests; /* requests dispatched (stats) */
370 UV accepts; /* connections accepted (stats) */
371 UV denied; /* connections dropped at accept, denylist */
372 UV bytes_out; /* response bytes queued (stats) */
373 UV datagrams; /* QUIC datagrams taken off the wire */
374 UV h3_conns; /* QUIC handshakes completed */
375 UV h3_live; /* QUIC connections open now */
376 UV h3_requests; /* requests served over HTTP/3 */
377 UV datagrams_out; /* QUIC datagrams sent (one sendto
378 * each: no GSO anywhere yet) */
379 UV http3_max_conns; /* ceiling on h3_live, 0 = unlimited */
380 hm_qheap qheap; /* QUIC expiry deadlines (hm_quic.h) */
381 UV max_requests; /* recycle worker after N (0=off) */
382 int recycle_pending; /* max_requests hit; drain at loop top */
383 double shutdown_grace; /* graceful-drain bound (secs) */
384 hm_tw *hardstop_tw;
385 };
386  
387 /* One served request, counted, and max_requests tested - for every protocol
388 * that finishes one. The bound belongs to the worker and not to HTTP/1: a
389 * site whose browsers all negotiate h2 would otherwise never reach it, and
390 * the worker it was meant to retire grows for as long as the box lets it.
391 *
392 * Not on the 101 paths (h2c upgrade, detach, tunnel), which count their
393 * request and deliberately do not test: the socket there has just left this
394 * loop for an application that means to hold it open, and a drain decided by
395 * the request that handed it over is the one moment it must not happen.
396 *
397 * A function and not a macro because the argument is read five times. */
398 868 static void hm_count_request(hm_loop *loop) {
399 868 loop->requests++;
400 /*
401 # uncoverable condition right count:3 class:ignore_covered_err
402 # uncoverable condition right count:4 class:ignore_covered_err */
403 868 ▶ if (loop->max_requests && loop->requests >= loop->max_requests
Branch: 2 branches
BranchTrueFalseTotal
if (loop->max_requests && loop->requests >= loop->max_requests 82 786 868
if (loop->max_requests && loop->requests >= loop->max_requests 8 74 82
404 8 ▶ && !loop->stopping && loop->attached)
Branch: 2 branches
BranchTrueFalseTotal
&& !loop->stopping && loop->attached) 8 0 8
&& !loop->stopping && loop->attached) 8 0 8
405 8 loop->recycle_pending = 1; /* drain at the loop iteration boundary */
406 868 }
407  
408 /* Does a Hyperman::Writer's tag slot hold this string? The four-element
409 * writer shapes (h2 and h3) have the same arity, so they are told apart by
410 * the tag and never by length - a length test routes an HTTP/3 body into an
411 * nghttp2 session. Used from xs/writer.xs. */
412 84 static int hm_writer_tag_is(pTHX_ AV *w, const char *want, STRLEN wantlen) {
413 84 SV **t = av_fetch(w, 3, 0);
414 STRLEN l;
415 const char *p;
416 /*
417 # uncoverable branch true class:ignore_covered_err
418 # uncoverable condition left count:1 class:ignore_covered_err
419 # uncoverable condition left count:2 class:ignore_covered_err
420 # uncoverable condition left count:3 class:ignore_covered_err */
421 84 ▶ if (!t || !*t || !SvOK(*t)) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!t || !*t || !SvOK(*t)) return 0; 84 0 84
if (!t || !*t || !SvOK(*t)) return 0; 84 0 84
if (!t || !*t || !SvOK(*t)) return 0; 0 84 84
422 84 p = SvPV(*t, l);
423 84 ▶ return l == wantlen && memcmp(p, want, l) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
return l == wantlen && memcmp(p, want, l) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 84 0 84
return l == wantlen && memcmp(p, want, l) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 84 0 84
424 }
425  
426 /* Find the listener owning a ready fd (listener count is tiny). */
427 28851 static hm_listener *hm_listener_for_fd(hm_loop *loop, int fd) {
428 int i;
429 30224 ▶ for (i = 0; i < loop->nlisteners; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) 29017 1207 30224
430 29017 ▶ if (loop->listeners[i].fd == fd) return &loop->listeners[i];
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].fd == fd) return &loop->listeners[i]; 27644 1373 29017
431 1207 return NULL;
432 }
433  
434 /* The same, for the QUIC side. Separate rather than a flag on the above,
435 * because a UDP listener fd is never in loop->conns[] and the caller wants
436 * to know which of the two it has. */
437 1207 static hm_listener *hm_listener_for_udp(hm_loop *loop, int fd) {
438 int i;
439 2566 ▶ for (i = 0; i < loop->nlisteners; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) 1359 1207 2566
440 /*
441 # uncoverable branch true class:ignore_covered_err
442 # uncoverable condition left count:1 class:ignore_covered_err
443 # uncoverable condition left count:2 class:ignore_covered_err
444 # uncoverable condition right count:2 class:ignore_covered_err */
445 1359 ▶ if (loop->listeners[i].udp_fd >= 0 && loop->listeners[i].udp_fd == fd)
Branch: 2 branches
BranchTrueFalseTotal
if (loop->listeners[i].udp_fd >= 0 && loop->listeners[i].udp_fd == fd) 0 1359 1359
if (loop->listeners[i].udp_fd >= 0 && loop->listeners[i].udp_fd == fd) 0 0 0
446 0 return &loop->listeners[i]; /* # uncoverable statement class:ignore_covered_err */
447 1207 return NULL;
448 }
449  
450 static SV *hm_empty_input; /* shared empty psgi.input */
451 static SV *hm_empty_input_sv(pTHX); /* ... checked still open */
452 #ifndef _WIN32
453 static pid_t hm_children[1024]; /* the supervisor's pool (POSIX only) */
454 static time_t hm_child_start[1024];
455 /* The WORKER INDEX each of those was forked with, which is not its position
456 * here: this array is kept packed by swapping the last entry down over a
457 * departed one, so a position means nothing beyond "somebody lives here". The
458 * index is an identity - it picks the worker's waker slot and its CPU - so it
459 * has to travel with the child rather than be recomputed from where the child
460 * happens to sit. */
461 static int hm_child_widx[1024];
462 static int hm_nchildren = 0;
463 #endif
464 static UV hm_id_counter = 0;
465  
466 static SV *hm_loop_to_sv(pTHX_ hm_loop *loop);
467 static void hm_on_signal(pTHX_ hm_loop *loop);
468 static void hm_deliver(pTHX_ int fd, UV id, SV *resp);
469 static int hm_flush(pTHX_ hm_conn *c);
470 static void hm_process(pTHX_ hm_conn *c);
471 static int hm_queue_response(pTHX_ hm_conn *c, SV *resp);
472 static void hm_close(pTHX_ hm_loop *loop, hm_conn *c);
473 static void hm_wb_reserve(hm_conn *c, size_t need);
474 static void hm_wb_put(hm_conn *c, const char *p, size_t n);
475 static void hm_again_push(hm_loop *loop, hm_conn *c);
476 static void hm_tw_gy_sweep(hm_loop *loop);
477 static void hm_h2_free(pTHX_ void *h2); /* defined in hm_http2.h */
478 static void hm_readable(pTHX_ hm_conn *c);
479 static void hm_read_resume(hm_loop *loop, hm_conn *c);
480  
481 /* ABI v6 stream handles, defined in hm_stream.h (included below, after the
482 * HTTP/1 and HTTP/2 halves it sits on top of). The two counters are read on
483 * the close and flush paths rather than called into, because they are zero
484 * for every connection that never opened a handle - which is nearly all of
485 * them - and a list walk per flush is not free. */
486 static int hm_stream_live_n = 0;
487 static int hm_stream_paused_n = 0;
488 static void hm_quic_readable(pTHX_ hm_loop *loop, hm_listener *lst); /* hm_quic.h */
489 static void hm_quic_expire(pTHX_ hm_loop *loop); /* hm_quic.h */
490 static void hm_quic_srv_attach(pTHX_ hm_loop *loop, hm_listener *lst, int widx);
491 static void hm_quic_srv_free(pTHX_ hm_listener *lst);
492 static void hm_quic_shutdown(pTHX_ hm_loop *loop);
493 static void hm_quic_ctx_swap(pTHX_ hm_listener *lst, void *fresh);
494 static uint64_t hm_quic_next_deadline(hm_loop *loop);
495 static void hm_quic_secret_init(void);
496 static void hm_stream_conn_gone(pTHX_ int fd, UV id);
497 static int hm_stream_deliver(pTHX_ int fd, UV cid, int64_t sid,
498 const char *buf, STRLEN len, int fin);
499 static void hm_stream_h2_gone(pTHX_ int fd, UV id, int64_t sid);
500 static void hm_stream_drained(pTHX_ hm_conn *c);
501 static int hm_h2_reentrant(hm_conn *c); /* hm_http2.h */
502  
503 #include "hm_tls.h" /* SSL_CTX, wrap, hm_cread/hm_cwrite */
504  
505 /* ---- small utilities ----------------------------------------------------- */
506  
507 18 static const char *hm_reason(int s) {
508 /*
509 # uncoverable branch true count:1
510 # uncoverable branch true count:5
511 # uncoverable branch true count:6
512 # uncoverable branch true count:7
513 # uncoverable branch true count:8
514 # uncoverable branch true count:9
515 # uncoverable branch true count:10
516 # uncoverable branch true count:11
517 # uncoverable branch true count:12
518 # uncoverable branch true count:13
519 # uncoverable branch true count:14
520 # uncoverable branch true count:15
521 # uncoverable branch true count:17 */
522 18 switch (s) {
523 10 case 100: return "Continue"; case 101: return "Switching Protocols";
524 2 case 102: return "Processing"; case 103: return "Early Hints";
525 0 case 200: return "OK"; case 201: return "Created"; /* # uncoverable statement */
526 0 case 204: return "No Content"; case 301: return "Moved Permanently"; /* # uncoverable statement */
527 0 case 302: return "Found"; case 304: return "Not Modified"; /* # uncoverable statement */
528 0 case 400: return "Bad Request"; case 401: return "Unauthorized"; /* # uncoverable statement */
529 0 case 403: return "Forbidden"; case 404: return "Not Found"; /* # uncoverable statement */
530 0 case 405: return "Method Not Allowed"; /* # uncoverable statement */
531 1 case 426: return "Upgrade Required";
532 0 case 500: return "Internal Server Error"; /* # uncoverable statement */
533 5 default: return "OK";
534 }
535 }
536  
537 /* Tiny decimal formatters: snprintf's format parsing and locale machinery
538 * are measurable at hot-path request rates. Return bytes written. */
539 777 static size_t hm_utoa(char *out, unsigned long v) {
540 char tmp[20];
541 777 size_t n = 0, i;
542 1361 ▶ do { tmp[n++] = (char)('0' + v % 10); v /= 10; } while (v);
Branch: 1 branch
BranchTrueFalseTotal
do { tmp[n++] = (char)('0' + v % 10); v /= 10; } while (v); 584 777 1361
543 2138 ▶ for (i = 0; i < n; i++) out[i] = tmp[n - 1 - i];
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) out[i] = tmp[n - 1 - i]; 1361 777 2138
544 777 return n;
545 }
546 99 static size_t hm_itoa(char *out, long v) {
547 /*
548 # uncoverable branch true
549 # uncoverable condition left count:1 class:ignore_covered_err */
550 99 ▶ if (v < 0) { out[0] = '-'; return 1 + hm_utoa(out + 1, 0UL - (unsigned long)v); }
Branch: 1 branch
BranchTrueFalseTotal
if (v < 0) { out[0] = '-'; return 1 + hm_utoa(out + 1, 0UL - (unsigned long)v); } 0 99 99
551 99 return hm_utoa(out, (unsigned long)v);
552 }
553  
554 /* Status line for the response: precomputed for the common statuses, built
555 * into buf (>= 64 bytes) otherwise. Sets *len, returns the line. */
556 867 static const char *hm_status_line(int s, size_t *len, char *buf) {
557 #define HM_SL(str) do { *len = sizeof(str) - 1; return str; } while (0)
558 867 switch (s) {
559 828 case 200: HM_SL("HTTP/1.1 200 OK\r\n");
560 1 case 201: HM_SL("HTTP/1.1 201 Created\r\n");
561 4 case 204: HM_SL("HTTP/1.1 204 No Content\r\n");
562 2 case 301: HM_SL("HTTP/1.1 301 Moved Permanently\r\n");
563 1 case 302: HM_SL("HTTP/1.1 302 Found\r\n");
564 3 case 304: HM_SL("HTTP/1.1 304 Not Modified\r\n");
565 1 case 400: HM_SL("HTTP/1.1 400 Bad Request\r\n");
566 1 case 401: HM_SL("HTTP/1.1 401 Unauthorized\r\n");
567 1 case 403: HM_SL("HTTP/1.1 403 Forbidden\r\n");
568 2 case 404: HM_SL("HTTP/1.1 404 Not Found\r\n");
569 1 case 405: HM_SL("HTTP/1.1 405 Method Not Allowed\r\n");
570 4 case 500: HM_SL("HTTP/1.1 500 Internal Server Error\r\n");
571 }
572 #undef HM_SL
573 {
574 18 const char *r = hm_reason(s);
575 18 size_t rl = strlen(r), n = 9;
576 18 memcpy(buf, "HTTP/1.1 ", 9);
577 18 n += hm_itoa(buf + n, (long)s);
578 18 buf[n++] = ' ';
579 18 memcpy(buf + n, r, rl); n += rl;
580 18 buf[n++] = '\r'; buf[n++] = '\n';
581 18 *len = n;
582 18 return buf;
583 }
584 }
585  
586 /* Format a peer sockaddr into a printable REMOTE_ADDR string and its port ("" /
587 * 0 on failure or for address families we don't serve). */
588 935 static void hm_fmt_peer(char *out, size_t outlen, int *port, const struct sockaddr *sa) {
589 935 out[0] = '\0';
590 /*
591 # uncoverable branch false class:ignore_covered_err
592 # uncoverable condition right count:1 class:ignore_covered_err */
593 935 ▶ if (port) *port = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (port) *port = 0; 935 0 935
594 /*
595 # uncoverable branch true
596 # uncoverable condition left count:1 class:ignore_covered_err */
597 935 ▶ if (!sa) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sa) return; 0 935 935
598 935 ▶ if (sa->sa_family == AF_INET) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa->sa_family == AF_INET) { 933 2 935
599 933 const struct sockaddr_in *s4 = (const struct sockaddr_in *)sa;
600 933 inet_ntop(AF_INET, &s4->sin_addr, out, (socklen_t)outlen);
601 /*
602 # uncoverable branch false class:ignore_covered_err
603 # uncoverable condition right count:1 class:ignore_covered_err */
604 933 ▶ if (port) *port = ntohs(s4->sin_port);
Branch: 1 branch
BranchTrueFalseTotal
if (port) *port = ntohs(s4->sin_port); 933 0 933
605 /*
606 # uncoverable branch true class:ignore_covered_err
607 # uncoverable condition left count:1 class:ignore_covered_err */
608 2 ▶ } else if (sa->sa_family == AF_INET6) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (sa->sa_family == AF_INET6) { 0 2 2
609 0 const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)sa; /* # uncoverable statement class:ignore_covered_err */
610 /* An IPv4 client of a dual-stack listener arrives as ::ffff:a.b.c.d.
611 * Formatted as the IPv4 it is: the denylist and the rate limiter
612 * key on the string, and "1.2.3.4" must be one client whichever
613 * listener it came through. */
614 /*
615 # uncoverable statement class:ignore_covered_err
616 # uncoverable branch true class:ignore_covered_err
617 # uncoverable branch false class:ignore_covered_err
618 # uncoverable condition left count:1 class:ignore_covered_err
619 # uncoverable condition right count:1 class:ignore_covered_err */
620 0 ▶ if (IN6_IS_ADDR_V4MAPPED(&s6->sin6_addr))
Branch: 4 branches
BranchTrueFalseTotal
if (IN6_IS_ADDR_V4MAPPED(&s6->sin6_addr)) 0 0 0
if (IN6_IS_ADDR_V4MAPPED(&s6->sin6_addr)) 0 0 0
if (IN6_IS_ADDR_V4MAPPED(&s6->sin6_addr)) 0 0 0
if (IN6_IS_ADDR_V4MAPPED(&s6->sin6_addr)) 0 0 0
621 0 inet_ntop(AF_INET, ((const unsigned char *)&s6->sin6_addr) + 12, /* # uncoverable statement */
622 out, (socklen_t)outlen); /* # uncoverable statement */
623 else
624 0 inet_ntop(AF_INET6, &s6->sin6_addr, out, (socklen_t)outlen); /* # uncoverable statement class:ignore_covered_err */
625 /*
626 # uncoverable statement class:ignore_covered_err
627 # uncoverable branch true class:ignore_covered_err
628 # uncoverable branch false class:ignore_covered_err
629 # uncoverable condition left count:1 class:ignore_covered_err
630 # uncoverable condition right count:1 class:ignore_covered_err */
631 0 ▶ if (port) *port = ntohs(s6->sin6_port);
Branch: 1 branch
BranchTrueFalseTotal
if (port) *port = ntohs(s6->sin6_port); 0 0 0
632 }
633 }
634  
635 92 static void hm_set_nonblock(int fd) { hm_os_set_nonblock(fd); }
636  
637 /* fd of a filehandle / IO ref, or a plain fd number */
638 20 static int hm_fd_of(pTHX_ SV *sv) {
639 /*
640 # uncoverable branch false
641 # uncoverable condition right count:1 class:ignore_covered_err */
642 20 ▶ if (SvROK(sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(sv)) { 20 0 20
643 20 IO *io = sv_2io(sv);
644 20 ▶ if (io && IoIFP(io)) return PerlIO_fileno(IoIFP(io)); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (io && IoIFP(io)) return PerlIO_fileno(IoIFP(io)); /* # uncoverable condition right count:1 class:ignore_covered_err */ 20 0 20
if (io && IoIFP(io)) return PerlIO_fileno(IoIFP(io)); /* # uncoverable condition right count:1 class:ignore_covered_err */ 19 1 20
645 1 croak("Hyperman: not an open filehandle");
646 }
647 0 return (int)SvIV(sv); /* # uncoverable statement */
648 }
649  
650 /* a fresh anonymous glob with an IO slot (standard idiom) */
651 927 static GV *hm_anon_glob(pTHX) {
652 927 GV *gv = newGVgen("Hyperman");
653 927 ▶ (void)GvIOn(gv);
Branch: 5 branches
BranchTrueFalseTotal
(void)GvIOn(gv); 927 0 927
(void)GvIOn(gv); 0 927 927
(void)GvIOn(gv); 0 0 0
(void)GvIOn(gv); 927 0 927
(void)GvIOn(gv); 0 927 927
654 927 SvREFCNT_inc((SV *)gv);
655 927 (void)hv_delete(GvSTASH(gv), GvNAME(gv), GvNAMELEN(gv), G_DISCARD);
656 927 return gv;
657 }
658  
659 /* A read handle over an already-open descriptor, rewound. The handle owns the
660 * descriptor from this point. */
661 5 static SV *hm_input_from_fd(pTHX_ int fd) {
662 PerlIO *fp;
663 GV *gv;
664 IO *io;
665 /*
666 # uncoverable branch true
667 # uncoverable condition left count:1 class:ignore_covered_err */
668 5 ▶ if (PerlLIO_lseek(fd, 0, SEEK_SET) < 0) { PerlLIO_close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (PerlLIO_lseek(fd, 0, SEEK_SET) < 0) { PerlLIO_close(fd); return NULL; } 0 5 5
669 5 fp = PerlIO_fdopen(fd, "rb");
670 /*
671 # uncoverable branch true
672 # uncoverable condition left count:1 class:ignore_covered_err */
673 5 ▶ if (!fp) { PerlLIO_close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) { PerlLIO_close(fd); return NULL; } 0 5 5
674 5 gv = hm_anon_glob(aTHX);
675 /*
676 # uncoverable branch true
677 # uncoverable condition left count:1 class:ignore_covered_err */
678 5 ▶ if (!gv) { PerlIO_close(fp); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!gv) { PerlIO_close(fp); return NULL; } 0 5 5
679 5 ▶ io = GvIOn(gv);
Branch: 5 branches
BranchTrueFalseTotal
io = GvIOn(gv); 5 0 5
io = GvIOn(gv); 0 5 5
io = GvIOn(gv); 0 0 0
io = GvIOn(gv); 5 0 5
io = GvIOn(gv); 5 0 5
680 5 IoIFP(io) = fp;
681 5 IoTYPE(io) = IoTYPE_RDONLY;
682 5 return newRV_noinc((SV *)gv);
683 }
684  
685 /* A temp file for a body being drained out of the read buffer.
686 *
687 * Unlinked the instant it exists, so the descriptor is its only reference: it
688 * goes away when the request ends, when the handler dies, or when the worker
689 * is killed, and there is no cleanup path anywhere to forget. Nothing is
690 * inherited across a fork either, which is the failure this workspace keeps
691 * meeting from the other direction. */
692 /* Where a body temp file goes. TMPDIR is the POSIX spelling of the question
693 * and TEMP the Windows one - asking only the first left Windows falling back
694 * to a "/tmp" that is not there, which is a failed mkstemp on every request
695 * carrying a body. */
696 6 static const char *hm_tmpdir(void) {
697 6 const char *d = getenv("TMPDIR");
698 /*
699 # uncoverable branch true class:ignore_covered_err
700 # uncoverable condition left count:1 class:ignore_covered_err
701 # uncoverable condition left count:2 class:ignore_covered_err
702 # uncoverable condition right count:2 class:ignore_covered_err */
703 6 ▶ if (d && *d) return d;
Branch: 2 branches
BranchTrueFalseTotal
if (d && *d) return d; 0 6 6
if (d && *d) return d; 0 0 0
704 #ifdef _WIN32
705 if ((d = getenv("TEMP")) && *d) return d;
706 if ((d = getenv("TMP")) && *d) return d;
707 return ".";
708 #else
709 6 return "/tmp";
710 #endif
711 }
712  
713 /* dir + "/hm-body-XXXXXX" into buf, or 0 if the directory will not fit. */
714 6 static int hm_body_tmppath(char *buf, size_t cap) {
715 6 const char *dir = hm_tmpdir();
716 6 size_t dl = strlen(dir);
717 /*
718 # uncoverable branch true
719 # uncoverable condition left count:1 class:ignore_covered_err */
720 6 ▶ if (dl + sizeof("/hm-body-XXXXXX") > cap) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (dl + sizeof("/hm-body-XXXXXX") > cap) return 0; 0 6 6
721 6 my_strlcpy(buf, dir, cap);
722 /*
723 # uncoverable branch false class:ignore_covered_err
724 # uncoverable condition right count:1 class:ignore_covered_err
725 # uncoverable condition right count:2 class:ignore_covered_err
726 # uncoverable condition right count:3 class:ignore_covered_err */
727 6 ▶ if (dl && dir[dl - 1] != '/' && dir[dl - 1] != '\\')
Branch: 3 branches
BranchTrueFalseTotal
if (dl && dir[dl - 1] != '/' && dir[dl - 1] != '\\') 6 0 6
if (dl && dir[dl - 1] != '/' && dir[dl - 1] != '\\') 6 0 6
if (dl && dir[dl - 1] != '/' && dir[dl - 1] != '\\') 6 0 6
728 6 my_strlcat(buf, "/", cap);
729 6 my_strlcat(buf, "hm-body-XXXXXX", cap);
730 6 return 1;
731 }
732  
733 5 static int hm_body_tmpfile(void) {
734 char path[512];
735 int fd;
736 /*
737 # uncoverable branch true
738 # uncoverable condition left count:1 class:ignore_covered_err */
739 5 ▶ if (!hm_body_tmppath(path, sizeof path)) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_body_tmppath(path, sizeof path)) return -1; 0 5 5
740 5 fd = mkstemp(path);
741 /*
742 # uncoverable branch true
743 # uncoverable condition left count:1 class:ignore_covered_err */
744 5 ▶ if (fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return -1; 0 5 5
745 5 (void)unlink(path);
746 5 return fd;
747 }
748  
749 /* Above this, the body goes to a temp file instead of a second copy in
750 * memory. Below it, the copy is cheaper than an inode and three syscalls. */
751 #ifndef HM_SPILL_BODY
752 # define HM_SPILL_BODY (1024 * 1024)
753 #endif
754  
755 /* psgi.input over a temp file, for a body large enough that a second copy in
756 * memory is the wrong trade.
757 *
758 * The file is UNLINKED as soon as it is open, and the handle keeps it alive:
759 * it vanishes when the handle is closed, whether that is a normal response, a
760 * handler that died, or the worker being killed mid-request. There is no
761 * cleanup path to forget and nothing on disk for another process to find.
762 *
763 * Returns NULL to fall back to the in-memory handle, because a server that
764 * cannot make a temp file should still serve the request.
765 */
766 1 static SV *hm_new_input_file(pTHX_ const char *body, STRLEN len) {
767 char path[512];
768 int fd;
769 1 STRLEN off = 0;
770  
771 /*
772 # uncoverable branch true
773 # uncoverable condition left count:1 class:ignore_covered_err */
774 1 ▶ if (!hm_body_tmppath(path, sizeof path)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_body_tmppath(path, sizeof path)) return NULL; 0 1 1
775  
776 1 fd = mkstemp(path);
777 /*
778 # uncoverable branch true
779 # uncoverable condition left count:1 class:ignore_covered_err */
780 1 ▶ if (fd < 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return NULL; 0 1 1
781 1 (void)PerlLIO_unlink(path); /* the handle is the only reference */
782  
783 2 ▶ while (off < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (off < len) { 1 1 2
784 1 SSize_t n = PerlLIO_write(fd, body + off, len - off);
785 /*
786 # uncoverable branch true
787 # uncoverable condition left count:1 class:ignore_covered_err */
788 1 ▶ if (n <= 0) { PerlLIO_close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { PerlLIO_close(fd); return NULL; } 0 1 1
789 1 off += (STRLEN)n;
790 }
791 /*
792 # uncoverable branch true
793 # uncoverable condition left count:1 class:ignore_covered_err */
794 1 ▶ if (PerlLIO_lseek(fd, 0, SEEK_SET) < 0) { PerlLIO_close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (PerlLIO_lseek(fd, 0, SEEK_SET) < 0) { PerlLIO_close(fd); return NULL; } 0 1 1
795  
796 1 return hm_input_from_fd(aTHX_ fd);
797 }
798  
799 /* psgi.input: an in-memory read handle over the request body, via the
800 * PerlIO :scalar layer - the C equivalent of open($fh,'<',\$body).
801 *
802 * WINDOWS TAKES THE FILE AT EVERY SIZE. PerlIO_openn is declared in perlio.h
803 * but is not among the symbols perl5xx.dll exports, so the :scalar layer
804 * cannot be reached from XS there at all - it is a link error, which is what
805 * the first Windows build of this core hit. The temp file needs nothing but
806 * PerlIO_fdopen, which IS exported, and it is the path every platform
807 * already runs for a body over HM_SPILL_BODY rather than a second one
808 * written for this. The trade is an inode and three syscalls on a Windows
809 * request that carries a body. */
810 111 static SV *hm_new_input(pTHX_ const char *body, STRLEN len) {
811 #ifdef _WIN32
812 SV *f = hm_new_input_file(aTHX_ body, len);
813 return f ? f : &PL_sv_undef;
814 #else
815 static int layer_loaded = 0;
816 SV *bufsv;
817 111 ▶ if (len > HM_SPILL_BODY) {
Branch: 1 branch
BranchTrueFalseTotal
if (len > HM_SPILL_BODY) { 1 110 111
818 1 SV *f = hm_new_input_file(aTHX_ body, len);
819 /*
820 # uncoverable branch false
821 # uncoverable condition right count:1 class:ignore_covered_err */
822 1 ▶ if (f) return f;
Branch: 1 branch
BranchTrueFalseTotal
if (f) return f; 1 0 1
823 }
824 110 bufsv = newSVpvn(body, len);
825 110 SV *rv = sv_2mortal(newRV_noinc(bufsv));
826 PerlIO *fp;
827 GV *gv;
828 IO *io;
829 110 ▶ if (!layer_loaded) {
Branch: 1 branch
BranchTrueFalseTotal
if (!layer_loaded) { 83 27 110
830 83 load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("PerlIO::scalar"), NULL);
831 83 layer_loaded = 1;
832 }
833 110 fp = PerlIO_openn(aTHX_ ":scalar", "r", -1, 0, 0, NULL, 1, &rv);
834 /*
835 # uncoverable branch true
836 # uncoverable condition left count:1 class:ignore_covered_err */
837 110 ▶ if (!fp) return &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) return &PL_sv_undef; 0 110 110
838 110 gv = hm_anon_glob(aTHX);
839 110 ▶ io = GvIO(gv);
Branch: 4 branches
BranchTrueFalseTotal
io = GvIO(gv); 110 0 110
io = GvIO(gv); 0 110 110
io = GvIO(gv); 0 0 0
io = GvIO(gv); 110 0 110
840 110 IoIFP(io) = fp;
841 110 IoTYPE(io) = IoTYPE_RDONLY;
842 110 return newRV_noinc((SV *)gv);
843 #endif
844 }
845  
846 /* The shared empty psgi.input, as every bodyless request gets it: one glob
847 * for the whole worker, because a fresh :scalar handle per request is a
848 * glob, an IO and a layer for a body that is not there. One check keeps the
849 * sharing honest: an application that closed it (or re-opened it over
850 * something else) left a handle with no input stream, and the next request
851 * would read a closed filehandle. A new one replaces it then. */
852 848 static SV *hm_empty_input_sv(pTHX) {
853 /*
854 # uncoverable branch false class:ignore_covered_err
855 # uncoverable condition right count:1 class:ignore_covered_err
856 # uncoverable condition right count:2 class:ignore_covered_err */
857 848 ▶ if (hm_empty_input && SvROK(hm_empty_input)) {
Branch: 2 branches
BranchTrueFalseTotal
if (hm_empty_input && SvROK(hm_empty_input)) { 848 0 848
if (hm_empty_input && SvROK(hm_empty_input)) { 848 0 848
858 848 SV *gv = SvRV(hm_empty_input);
859 848 ▶ IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 5 branches
BranchTrueFalseTotal
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 848 0 848
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 848 0 848
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 0 848 848
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 0 0 0
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 848 0 848
860 848 ▶ if (io && IoIFP(io)) return SvREFCNT_inc(hm_empty_input); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (io && IoIFP(io)) return SvREFCNT_inc(hm_empty_input); /* # uncoverable condition right count:1 class:ignore_covered_err */ 848 0 848
if (io && IoIFP(io)) return SvREFCNT_inc(hm_empty_input); /* # uncoverable condition right count:1 class:ignore_covered_err */ 847 1 848
861 1 SvREFCNT_dec(hm_empty_input);
862 1 hm_empty_input = NULL;
863 }
864 1 hm_empty_input = hm_new_input(aTHX_ "", 0);
865 1 return SvREFCNT_inc(hm_empty_input);
866 }
867  
868 /* psgix.io: a dup of the client socket, so an app that hijacks it keeps
869 * the socket alive after the server side closes. Absent on Windows:
870 * duplicating a socket there is WSADuplicateSocket, not dup(2), and the
871 * result would have to be re-wrapped for perl's IO layer - unproven, and
872 * psgix.io is optional in PSGI, so it is simply not offered. */
873 812 static SV *hm_fh_for_fd(pTHX_ int fd) {
874 #ifdef _WIN32
875 (void)fd;
876 return &PL_sv_undef;
877 #else
878 812 int nfd = dup(fd);
879 PerlIO *fp;
880 GV *gv;
881 IO *io;
882 /*
883 # uncoverable branch true class:ignore_covered_err
884 # uncoverable condition left count:1 class:ignore_covered_err */
885 812 ▶ if (nfd < 0) return &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
if (nfd < 0) return &PL_sv_undef; 0 812 812
886 812 fp = PerlIO_fdopen(nfd, "r+");
887 /*
888 # uncoverable branch true
889 # uncoverable condition left count:1 class:ignore_covered_err */
890 812 ▶ if (!fp) { hm_os_close(nfd); return &PL_sv_undef; }
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) { hm_os_close(nfd); return &PL_sv_undef; } 0 812 812
891 812 gv = hm_anon_glob(aTHX);
892 812 ▶ io = GvIO(gv);
Branch: 4 branches
BranchTrueFalseTotal
io = GvIO(gv); 812 0 812
io = GvIO(gv); 0 812 812
io = GvIO(gv); 0 0 0
io = GvIO(gv); 812 0 812
893 812 IoIFP(io) = fp;
894 812 IoOFP(io) = fp;
895 812 IoTYPE(io) = IoTYPE_RDWR;
896 812 return newRV_noinc((SV *)gv);
897 #endif
898 }
899  
900 /* Read out a filehandle / IO::Handle-like response body, honouring
901 * ->getline/->close on objects (PSGI body protocol). Returns a PV SV. */
902 4 static SV *hm_slurp_body(pTHX_ SV *body) {
903 4 SV *out = newSVpvs("");
904 4 ▶ if (sv_isobject(body) /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
if (sv_isobject(body) /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 1 4
905 3 ▶ && gv_fetchmethod_autoload(SvSTASH(SvRV(body)), "getline", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
&& gv_fetchmethod_autoload(SvSTASH(SvRV(body)), "getline", 0)) { 3 0 3
906 6 for (;;) {
907 9 dSP;
908 SV *chunk;
909 int n;
910 9 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 9 9
911 9 ▶ XPUSHs(body);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(body); 0 9 9
912 9 PUTBACK;
913 9 n = call_method("getline", G_SCALAR | G_EVAL);
914 9 SPAGAIN;
915 9 ▶ chunk = n ? POPs : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
chunk = n ? POPs : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 9 0 9
916 9 ▶ if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 4 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 9 0 9
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 8 1 9
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 8 0 8
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 2 6 8
917 3 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 3 0 3
918 3 break;
919 }
920 6 sv_catsv(out, chunk);
921 6 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 6 0 6
922 }
923 5 ▶ if (gv_fetchmethod_autoload(SvSTASH(SvRV(body)), "close", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (gv_fetchmethod_autoload(SvSTASH(SvRV(body)), "close", 0)) { 2 1 3
924 2 dSP;
925 2 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 2 2
926 2 ▶ XPUSHs(body);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(body); 0 2 2
927 2 PUTBACK;
928 2 call_method("close", G_DISCARD | G_EVAL);
929 2 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 2 0 2
930 }
931 /*
932 # uncoverable branch false class:ignore_covered_err
933 # uncoverable condition right count:1 class:ignore_covered_err
934 # uncoverable condition right count:2 class:ignore_covered_err
935 # uncoverable condition left count:3 class:ignore_covered_err
936 # uncoverable condition right count:3 class:ignore_covered_err */
937 1 ▶ } else if (SvROK(body) && (SvTYPE(SvRV(body)) == SVt_PVGV
Branch: 2 branches
BranchTrueFalseTotal
} else if (SvROK(body) && (SvTYPE(SvRV(body)) == SVt_PVGV 1 0 1
} else if (SvROK(body) && (SvTYPE(SvRV(body)) == SVt_PVGV 0 1 1
938 0 ▶ || SvTYPE(SvRV(body)) == SVt_PVIO)) { /* # uncoverable statement class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
|| SvTYPE(SvRV(body)) == SVt_PVIO)) { /* # uncoverable statement class:ignore_covered_err */ 0 0 0
939 /* sv_2io croaks on anything that is not a handle, and this is not
940 * under an eval: a body of [200, [], {}] would unwind the loop */
941 1 IO *io = sv_2io(body);
942 /*
943 # uncoverable branch false class:ignore_covered_err
944 # uncoverable condition right count:1 class:ignore_covered_err
945 # uncoverable condition right count:2 class:ignore_covered_err */
946 1 ▶ if (io && IoIFP(io)) {
Branch: 2 branches
BranchTrueFalseTotal
if (io && IoIFP(io)) { 1 0 1
if (io && IoIFP(io)) { 1 0 1
947 char buf[8192];
948 SSize_t got;
949 2 ▶ while ((got = PerlIO_read(IoIFP(io), buf, sizeof(buf))) > 0)
Branch: 1 branch
BranchTrueFalseTotal
while ((got = PerlIO_read(IoIFP(io), buf, sizeof(buf))) > 0) 1 1 2
950 1 sv_catpvn(out, buf, got);
951 1 PerlIO_close(IoIFP(io));
952 1 IoIFP(io) = NULL;
953 1 IoOFP(io) = NULL;
954 }
955 }
956 4 return out;
957 }
958  
959 /* ---- streaming body sources ---------------------------------------------- *
960 * The lift: can this filehandle-ish body be streamed rather than slurped?
961 *
962 * - a glob / IO ref over a regular file lifts to (fd, tell, remaining):
963 * remaining is the Content-Length header when the response carries one,
964 * else file-size minus position (which is then also what the auto
965 * Content-Length announces).
966 * - a blessed object lifts when it has BOTH getline and fileno over a
967 * regular file AND the response promises a Content-Length - the range
968 * contract Punk::SendFile::Reader satisfies; the raw fd position is
969 * taken as the read point, so hand over a handle that has not been
970 * buffer-read from. Without a usable fd, a getline object with a
971 * Content-Length still streams, one chunk per getline (kind 2).
972 *
973 * Anything else returns 0 and the caller slurps, exactly as before. */
974  
975 2 static UV hm_bsrc_method_uv(pTHX_ SV *obj, const char *meth, int *ok) {
976 2 dSP;
977 2 UV out = 0;
978 int n;
979 2 *ok = 0;
980 2 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 2 2
981 2 ▶ XPUSHs(obj);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(obj); 0 2 2
982 2 PUTBACK;
983 2 n = call_method(meth, G_SCALAR | G_EVAL);
984 2 SPAGAIN;
985 /*
986 # uncoverable branch false class:ignore_covered_err
987 # uncoverable condition right count:1 class:ignore_covered_err */
988 2 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 2 0 2
989 2 SV *r = POPs;
990 /*
991 # uncoverable branch false class:ignore_covered_err
992 # uncoverable condition right count:1 class:ignore_covered_err
993 # uncoverable condition right count:2 class:ignore_covered_err
994 # uncoverable condition right count:3 class:ignore_covered_err */
995 2 ▶ if (!SvTRUE(ERRSV) && SvOK(r) && SvIV(r) >= 0) {
Branch: 4 branches
BranchTrueFalseTotal
if (!SvTRUE(ERRSV) && SvOK(r) && SvIV(r) >= 0) { 2 0 2
if (!SvTRUE(ERRSV) && SvOK(r) && SvIV(r) >= 0) { 2 0 2
if (!SvTRUE(ERRSV) && SvOK(r) && SvIV(r) >= 0) { 2 0 2
if (!SvTRUE(ERRSV) && SvOK(r) && SvIV(r) >= 0) { 2 0 2
996 2 out = (UV)SvUV(r);
997 2 *ok = 1;
998 }
999 }
1000 2 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 2 0 2
1001 2 return out;
1002 }
1003  
1004 18 static int hm_bsrc_lift(pTHX_ SV *body, hm_bsrc *bs, int has_len, UV clen) {
1005 /*
1006 # uncoverable branch true
1007 # uncoverable condition left count:1 class:ignore_covered_err */
1008 18 ▶ if (!SvROK(body)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(body)) return 0; 0 18 18
1009  
1010 18 ▶ if (sv_isobject(body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sv_isobject(body)) { 6 12 18
1011 6 HV *stash = SvSTASH(SvRV(body));
1012 6 int fd = -1, ok = 0;
1013 /*
1014 # uncoverable branch true
1015 # uncoverable condition left count:1 class:ignore_covered_err */
1016 6 ▶ if (!gv_fetchmethod_autoload(stash, "getline", 0)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!gv_fetchmethod_autoload(stash, "getline", 0)) return 0; 0 6 6
1017 6 ▶ if (!has_len) return 0; /* no promised length, keep the slurp */
Branch: 1 branch
BranchTrueFalseTotal
if (!has_len) return 0; /* no promised length, keep the slurp */ 3 3 6
1018 3 ▶ if (gv_fetchmethod_autoload(stash, "fileno", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (gv_fetchmethod_autoload(stash, "fileno", 0)) { 2 1 3
1019 2 UV v = hm_bsrc_method_uv(aTHX_ body, "fileno", &ok);
1020 /*
1021 # uncoverable branch false class:ignore_covered_err
1022 # uncoverable condition right count:1 class:ignore_covered_err */
1023 2 ▶ if (ok) fd = (int)v;
Branch: 1 branch
BranchTrueFalseTotal
if (ok) fd = (int)v; 2 0 2
1024 }
1025 3 ▶ if (fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { 2 1 3
1026 struct stat st;
1027 off_t pos;
1028 /*
1029 # uncoverable branch false class:ignore_covered_err
1030 # uncoverable condition right count:1 class:ignore_covered_err
1031 # uncoverable condition right count:2 class:ignore_covered_err
1032 # uncoverable condition right count:3 class:ignore_covered_err */
1033 2 ▶ if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode)
Branch: 2 branches
BranchTrueFalseTotal
if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) 2 0 2
if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) 2 0 2
1034 2 ▶ && (pos = lseek(fd, 0, SEEK_CUR)) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& (pos = lseek(fd, 0, SEEK_CUR)) >= 0) { 2 0 2
1035 2 bs->kind = 1;
1036 2 bs->fd = fd;
1037 2 bs->off = pos;
1038 2 bs->remaining = clen;
1039 2 bs->sv = SvREFCNT_inc(body);
1040 2 return 1;
1041 }
1042 }
1043 1 bs->kind = 2;
1044 1 bs->remaining = clen;
1045 1 bs->sv = SvREFCNT_inc(body);
1046 1 return 1;
1047 }
1048  
1049 /*
1050 # uncoverable branch false class:ignore_covered_err
1051 # uncoverable condition right count:1 class:ignore_covered_err
1052 # uncoverable condition left count:2 class:ignore_covered_err
1053 # uncoverable condition right count:2 class:ignore_covered_err */
1054 12 ▶ if (SvTYPE(SvRV(body)) == SVt_PVGV || SvTYPE(SvRV(body)) == SVt_PVIO) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTYPE(SvRV(body)) == SVt_PVGV || SvTYPE(SvRV(body)) == SVt_PVIO) { 0 12 12
if (SvTYPE(SvRV(body)) == SVt_PVGV || SvTYPE(SvRV(body)) == SVt_PVIO) { 0 0 0
1055 12 IO *io = sv_2io(body);
1056 12 ▶ PerlIO *fp = io ? IoIFP(io) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
PerlIO *fp = io ? IoIFP(io) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 12 0 12
1057 struct stat st;
1058 int fd;
1059 off_t pos;
1060 /*
1061 # uncoverable branch true
1062 # uncoverable condition left count:1 class:ignore_covered_err */
1063 12 ▶ if (!fp) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) return 0; 0 12 12
1064 12 fd = PerlIO_fileno(fp);
1065 /*
1066 # uncoverable condition left count:2 class:ignore_covered_err
1067 # uncoverable condition left count:3 class:ignore_covered_err */
1068 12 ▶ if (fd < 0 || fstat(fd, &st) < 0 || !S_ISREG(st.st_mode)) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (fd < 0 || fstat(fd, &st) < 0 || !S_ISREG(st.st_mode)) return 0; 11 1 12
if (fd < 0 || fstat(fd, &st) < 0 || !S_ISREG(st.st_mode)) return 0; 11 0 11
if (fd < 0 || fstat(fd, &st) < 0 || !S_ISREG(st.st_mode)) return 0; 0 11 11
1069 11 pos = (off_t)PerlIO_tell(fp);
1070 /*
1071 # uncoverable branch true class:ignore_covered_err
1072 # uncoverable condition left count:1 class:ignore_covered_err
1073 # uncoverable condition left count:2 class:ignore_covered_err */
1074 11 ▶ if (pos < 0 || pos > st.st_size) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (pos < 0 || pos > st.st_size) return 0; 11 0 11
if (pos < 0 || pos > st.st_size) return 0; 0 11 11
1075 11 bs->kind = 1;
1076 11 bs->fd = fd;
1077 11 bs->off = pos;
1078 11 ▶ bs->remaining = has_len ? clen : (UV)(st.st_size - pos);
Branch: 1 branch
BranchTrueFalseTotal
bs->remaining = has_len ? clen : (UV)(st.st_size - pos); 7 4 11
1079 11 bs->sv = SvREFCNT_inc(body);
1080 11 return 1;
1081 }
1082 0 return 0; /* # uncoverable statement */
1083 }
1084  
1085 /* Close out a source: the PSGI body contract says the server closes the
1086 * handle it was given (hm_slurp_body has always done so). Objects get
1087 * their close method; a glob's PerlIO is closed directly. */
1088 14 static void hm_bsrc_release(pTHX_ hm_bsrc *bs) {
1089 /*
1090 # uncoverable branch true
1091 # uncoverable condition left count:1 class:ignore_covered_err */
1092 14 ▶ if (!bs->kind) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!bs->kind) return; 0 14 14
1093 /*
1094 # uncoverable branch false class:ignore_covered_err
1095 # uncoverable condition right count:1 class:ignore_covered_err */
1096 14 ▶ if (bs->sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (bs->sv) { 14 0 14
1097 14 ▶ if (sv_isobject(bs->sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sv_isobject(bs->sv)) { 3 11 14
1098 /*
1099 # uncoverable branch false class:ignore_covered_err
1100 # uncoverable condition right count:1 class:ignore_covered_err */
1101 3 ▶ if (gv_fetchmethod_autoload(SvSTASH(SvRV(bs->sv)), "close", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (gv_fetchmethod_autoload(SvSTASH(SvRV(bs->sv)), "close", 0)) { 3 0 3
1102 3 dSP;
1103 3 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 3 3
1104 3 ▶ XPUSHs(bs->sv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(bs->sv); 0 3 3
1105 3 PUTBACK;
1106 3 call_method("close", G_DISCARD | G_EVAL);
1107 3 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 3 0 3
1108 }
1109 }
1110 else {
1111 11 IO *io = sv_2io(bs->sv);
1112 /*
1113 # uncoverable branch false class:ignore_covered_err
1114 # uncoverable condition right count:1 class:ignore_covered_err
1115 # uncoverable condition right count:2 class:ignore_covered_err */
1116 11 ▶ if (io && IoIFP(io)) {
Branch: 2 branches
BranchTrueFalseTotal
if (io && IoIFP(io)) { 11 0 11
if (io && IoIFP(io)) { 11 0 11
1117 11 PerlIO_close(IoIFP(io));
1118 11 IoIFP(io) = NULL;
1119 11 IoOFP(io) = NULL;
1120 }
1121 }
1122 14 SvREFCNT_dec(bs->sv);
1123 }
1124 14 memset(bs, 0, sizeof(*bs));
1125 }
1126  
1127 /* Refill the write buffer with the next chunk of the source. Returns the
1128 * bytes added; 0 when the source is spent; -1 on a source that ended
1129 * early (file truncated under us, getline died or dried up) - the client
1130 * was promised more bytes than it will get, so the connection must not
1131 * be reused. */
1132 45 static ssize_t hm_bsrc_fill(pTHX_ hm_conn *c) {
1133 45 hm_bsrc *bs = &c->bsrc;
1134 45 ▶ if (!bs->remaining) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!bs->remaining) return 0; 1 44 45
1135 44 ▶ if (bs->kind == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (bs->kind == 1) { 1 43 44
1136 1 size_t want = bs->remaining < HM_BSRC_CHUNK
1137 ? (size_t)bs->remaining : HM_BSRC_CHUNK;
1138 ssize_t n;
1139 1 hm_wb_reserve(c, want);
1140 1 n = hm_os_pread(bs->fd, c->wbuf + c->wlen, want, bs->off);
1141 /*
1142 # uncoverable branch true
1143 # uncoverable condition left count:1 class:ignore_covered_err */
1144 1 ▶ if (n <= 0) { c->keepalive = 0; return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { c->keepalive = 0; return -1; } 0 1 1
1145 1 c->wlen += (size_t)n;
1146 1 bs->off += n;
1147 1 bs->remaining -= (UV)n;
1148 1 return n;
1149 }
1150 0 for (;;) { /* kind 2: one getline */ /* # uncoverable statement class:ignore_covered_err */
1151 43 dSP;
1152 SV *chunk;
1153 43 STRLEN l = 0;
1154 43 const char *p = NULL;
1155 int n;
1156 43 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 43 43
1157 43 ▶ XPUSHs(bs->sv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(bs->sv); 0 43 43
1158 43 PUTBACK;
1159 43 n = call_method("getline", G_SCALAR | G_EVAL);
1160 43 SPAGAIN;
1161 43 ▶ chunk = n > 0 ? POPs : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
chunk = n > 0 ? POPs : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 43 0 43
1162 /*
1163 # uncoverable branch true class:ignore_covered_err
1164 # uncoverable condition left count:1 class:ignore_covered_err
1165 # uncoverable condition left count:2 class:ignore_covered_err
1166 # uncoverable condition left count:3 class:ignore_covered_err */
1167 43 ▶ if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) {
Branch: 4 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { 43 0 43
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { 43 0 43
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { 43 0 43
if (SvTRUE(ERRSV) || !chunk || !SvOK(chunk)) { 0 43 43
1168 0 ▶ PUTBACK; FREETMPS; LEAVE; /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; /* # uncoverable statement */ 0 0 0
1169 0 c->keepalive = 0; /* remaining > 0 here */ /* # uncoverable statement */
1170 43 return -1; /* # uncoverable statement class:ignore_covered_err */
1171 }
1172 43 p = SvPV(chunk, l);
1173 /*
1174 # uncoverable branch true class:ignore_covered_err
1175 # uncoverable condition left count:1 class:ignore_covered_err */
1176 43 ▶ if (l > bs->remaining) l = (STRLEN)bs->remaining; /* hold the framing */
Branch: 1 branch
BranchTrueFalseTotal
if (l > bs->remaining) l = (STRLEN)bs->remaining; /* hold the framing */ 0 43 43
1177 /*
1178 # uncoverable branch false class:ignore_covered_err
1179 # uncoverable condition right count:1 class:ignore_covered_err */
1180 43 ▶ if (l) hm_wb_put(c, p, l);
Branch: 1 branch
BranchTrueFalseTotal
if (l) hm_wb_put(c, p, l); 43 0 43
1181 43 bs->remaining -= (UV)l;
1182 43 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 43 0 43
1183 /*
1184 # uncoverable branch false
1185 # uncoverable condition right count:1 class:ignore_covered_err */
1186 43 ▶ if (l) return (ssize_t)l;
Branch: 1 branch
BranchTrueFalseTotal
if (l) return (ssize_t)l; 43 0 43
1187 /*
1188 # uncoverable statement
1189 # uncoverable branch true
1190 # uncoverable branch false
1191 # uncoverable condition left count:1
1192 # uncoverable condition right count:1 */
1193 0 ▶ if (!bs->remaining) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!bs->remaining) return 0; 0 0 0
1194 /* an empty chunk with bytes still owed: ask again */
1195 }
1196 }
1197  
1198 /* Scan a header AV for Content-Length; fills *out and returns 1 if found. */
1199 21 static int hm_hav_clen(pTHX_ AV *hav, UV *out) {
1200 SSize_t i, n;
1201 /*
1202 # uncoverable branch true
1203 # uncoverable condition left count:1 class:ignore_covered_err */
1204 21 ▶ if (!hav) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!hav) return 0; 0 21 21
1205 21 n = av_len(hav) + 1;
1206 36 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 25 11 36
1207 25 SV **k = av_fetch(hav, i, 0);
1208 STRLEN kl;
1209 const char *ks;
1210 /*
1211 # uncoverable branch true class:ignore_covered_err
1212 # uncoverable condition left count:1 class:ignore_covered_err
1213 # uncoverable condition left count:2 class:ignore_covered_err */
1214 25 ▶ if (!k || !*k) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!k || !*k) continue; 25 0 25
if (!k || !*k) continue; 0 25 25
1215 25 ks = SvPV(*k, kl);
1216 25 ▶ if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 10 15 25
if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 10 0 10
1217 10 SV **v = av_fetch(hav, i + 1, 0);
1218 /*
1219 # uncoverable branch false class:ignore_covered_err
1220 # uncoverable condition right count:1 class:ignore_covered_err
1221 # uncoverable condition right count:2 class:ignore_covered_err
1222 # uncoverable condition right count:3 class:ignore_covered_err */
1223 10 ▶ if (v && *v && SvOK(*v)) {
Branch: 3 branches
BranchTrueFalseTotal
if (v && *v && SvOK(*v)) { 10 0 10
if (v && *v && SvOK(*v)) { 10 0 10
if (v && *v && SvOK(*v)) { 10 0 10
1224 /* Digits only. SvUV of "abc" is 0, which selected the
1225 * counted mode with a length of nothing and cut the body
1226 * at its first write; a value that is not a length is
1227 * treated as absent, and the framing chosen without it. */
1228 STRLEN vl, j;
1229 10 const char *vs = SvPV(*v, vl);
1230 /*
1231 # uncoverable branch true class:ignore_covered_err
1232 # uncoverable condition left count:1 class:ignore_covered_err
1233 # uncoverable condition left count:2 class:ignore_covered_err */
1234 10 ▶ if (vl == 0 || vl > 19) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (vl == 0 || vl > 19) return 0; 10 0 10
if (vl == 0 || vl > 19) return 0; 0 10 10
1235 50 ▶ for (j = 0; j < vl; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < vl; j++) 41 9 50
1236 41 ▶ if (vs[j] < '0' || vs[j] > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (vs[j] < '0' || vs[j] > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 41 0 41
if (vs[j] < '0' || vs[j] > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 40 41
1237 9 *out = (UV)SvUV(*v);
1238 9 return 1;
1239 }
1240 }
1241 }
1242 11 return 0;
1243 }
1244  
1245 /* a [500, [...], [$msg]] PSGI triple (mortal) */
1246 6 static SV *hm_500_resp(pTHX_ const char *msg) {
1247 6 AV *resp = newAV();
1248 6 AV *hdrs = newAV();
1249 6 AV *body = newAV();
1250 6 av_push(hdrs, newSVpvs("Content-Type"));
1251 6 av_push(hdrs, newSVpvs("text/plain"));
1252 6 av_push(body, newSVpv(msg, 0));
1253 6 av_push(resp, newSViv(500));
1254 6 av_push(resp, newRV_noinc((SV *)hdrs));
1255 6 av_push(resp, newRV_noinc((SV *)body));
1256 6 return sv_2mortal(newRV_noinc((SV *)resp));
1257 }
1258  
1259 /* ---- connections --------------------------------------------------------- */
1260  
1261 /* Return a connection struct to the pool, or free it when the pool is full.
1262 * The buffers ride along so the steady state allocates nothing - but only
1263 * at their ordinary sizes. A read buffer grown for a 15MB body, or a write
1264 * buffer grown for one slow client, would otherwise stay that size for as
1265 * long as the pool held the struct, and a thousand of them is the whole
1266 * ceiling resident for nothing. */
1267 933 static void hm_pool_conn(hm_loop *loop, hm_conn *c) {
1268 933 ▶ if (c->rbuf && c->rcap > HM_RBUF) { free(c->rbuf); c->rbuf = NULL; c->rcap = 0; } /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c->rbuf && c->rcap > HM_RBUF) { free(c->rbuf); c->rbuf = NULL; c->rcap = 0; } /* # uncoverable condition right count:1 class:ignore_covered_err */ 933 0 933
if (c->rbuf && c->rcap > HM_RBUF) { free(c->rbuf); c->rbuf = NULL; c->rcap = 0; } /* # uncoverable condition right count:1 class:ignore_covered_err */ 6 927 933
1269 933 ▶ if (c->wbuf && c->wcap > HM_WB_KEEP) { free(c->wbuf); c->wbuf = NULL; c->wcap = 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (c->wbuf && c->wcap > HM_WB_KEEP) { free(c->wbuf); c->wbuf = NULL; c->wcap = 0; } 873 60 933
if (c->wbuf && c->wcap > HM_WB_KEEP) { free(c->wbuf); c->wbuf = NULL; c->wcap = 0; } 5 868 873
1270 /*
1271 # uncoverable branch false
1272 # uncoverable condition right count:1 class:ignore_covered_err */
1273 933 ▶ if (loop->pool_n < HM_POOL_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->pool_n < HM_POOL_MAX) { 933 0 933
1274 933 c->pool_next = loop->pool;
1275 933 loop->pool = c;
1276 933 loop->pool_n++;
1277 } else {
1278 /*
1279 # uncoverable statement
1280 # uncoverable branch true
1281 # uncoverable branch false
1282 # uncoverable condition left count:1
1283 # uncoverable condition right count:1 */
1284 0 ▶ if (c->wbuf) free(c->wbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->wbuf) free(c->wbuf); 0 0 0
1285 /*
1286 # uncoverable statement
1287 # uncoverable branch true
1288 # uncoverable branch false
1289 # uncoverable condition left count:1
1290 # uncoverable condition right count:1 */
1291 0 ▶ if (c->rbuf) free(c->rbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->rbuf) free(c->rbuf); 0 0 0
1292 0 free(c); /* # uncoverable statement */
1293 }
1294 933 }
1295  
1296 940 static void hm_lru_unlink(hm_loop *loop, hm_conn *c) {
1297 940 ▶ if (c->lru_prev) c->lru_prev->lru_next = c->lru_next;
Branch: 1 branch
BranchTrueFalseTotal
if (c->lru_prev) c->lru_prev->lru_next = c->lru_next; 54 886 940
1298 /*
1299 # uncoverable branch false class:ignore_covered_err
1300 # uncoverable condition right count:1 class:ignore_covered_err */
1301 886 ▶ else if (loop->lru_head == c) loop->lru_head = c->lru_next;
Branch: 1 branch
BranchTrueFalseTotal
else if (loop->lru_head == c) loop->lru_head = c->lru_next; 886 0 886
1302 940 ▶ if (c->lru_next) c->lru_next->lru_prev = c->lru_prev;
Branch: 1 branch
BranchTrueFalseTotal
if (c->lru_next) c->lru_next->lru_prev = c->lru_prev; 125 815 940
1303 /*
1304 # uncoverable branch false class:ignore_covered_err
1305 # uncoverable condition right count:1 class:ignore_covered_err */
1306 815 ▶ else if (loop->lru_tail == c) loop->lru_tail = c->lru_prev;
Branch: 1 branch
BranchTrueFalseTotal
else if (loop->lru_tail == c) loop->lru_tail = c->lru_prev; 815 0 815
1307 940 c->lru_prev = c->lru_next = NULL;
1308 940 }
1309  
1310 958 static void hm_lru_touch(hm_loop *loop, hm_conn *c) {
1311 958 c->last_active = loop->now;
1312 958 ▶ if (loop->lru_tail == c) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->lru_tail == c) return; 951 7 958
1313 7 hm_lru_unlink(loop, c);
1314 7 c->lru_prev = loop->lru_tail;
1315 /*
1316 # uncoverable branch false class:ignore_covered_err
1317 # uncoverable condition right count:1 class:ignore_covered_err */
1318 7 ▶ if (loop->lru_tail) loop->lru_tail->lru_next = c;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->lru_tail) loop->lru_tail->lru_next = c; 7 0 7
1319 7 loop->lru_tail = c;
1320 /*
1321 # uncoverable branch true class:ignore_covered_err
1322 # uncoverable condition left count:1 class:ignore_covered_err */
1323 7 ▶ if (!loop->lru_head) loop->lru_head = c;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->lru_head) loop->lru_head = c; 0 7 7
1324 }
1325  
1326 /* ---- completion-mode receive ---------------------------------------------
1327 *
1328 * A readiness backend says "this fd has bytes" and the core reads them. A
1329 * completion backend is asked for the read UP FRONT and hands back bytes that
1330 * are already in the buffer - which is how the read syscall stops being a
1331 * syscall per request and becomes part of one batched submission per turn of
1332 * the loop.
1333 *
1334 * What that costs is that the kernel holds a pointer into c->rbuf for a while,
1335 * and the two things the core does casually with that buffer - GROW it, and
1336 * POOL it for the next connection - both become memory corruption if they
1337 * happen while a read is outstanding. Growth is handled by only ever growing
1338 * before arming (hm_arm_recv). Pooling is handled here.
1339 *
1340 * The identity problem is the other half. A completion can outlive the
1341 * connection that asked for it: hm_close closes the fd, the number is reused
1342 * by a new connection moments later, and the old read lands looking exactly
1343 * like the new one's. So every read carries a token of fd plus the
1344 * connection's generation id, and a completion whose token does not match the
1345 * connection now holding that fd is somebody else's. */
1346  
1347 #define HM_RECV_TOKEN(c) \
1348 (((uint64_t)(c)->id << 17) | (uint64_t)(unsigned)(c)->fd)
1349  
1350 /* A read buffer whose connection is gone but whose kernel read is not. Parked
1351 * under the token the kernel will hand back, and freed when it does. */
1352 typedef struct hm_quar {
1353 uint64_t token;
1354 char *buf;
1355 struct hm_quar *next;
1356 } hm_quar;
1357  
1358 /*
1359 # uncoverable statement
1360 # uncoverable subroutine */
1361 0 static void hm_quar_push(hm_loop *loop, uint64_t token, char *buf) {
1362 hm_quar *q;
1363 /*
1364 # uncoverable statement
1365 # uncoverable branch true
1366 # uncoverable branch false
1367 # uncoverable condition left count:1
1368 # uncoverable condition right count:1 */
1369 0 ▶ if (!buf) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!buf) return; 0 0 0
1370 0 q = (hm_quar *)malloc(sizeof(hm_quar)); /* # uncoverable statement */
1371 /* Out of memory with a read outstanding: the buffer CANNOT be freed, so
1372 * it is leaked deliberately. One leaked read buffer beats handing the
1373 * kernel a pointer into the heap it no longer owns. */
1374 /*
1375 # uncoverable statement
1376 # uncoverable branch true
1377 # uncoverable branch false
1378 # uncoverable condition left count:1
1379 # uncoverable condition right count:1 */
1380 0 ▶ if (!q) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!q) return; 0 0 0
1381 0 q->token = token; /* # uncoverable statement */
1382 0 q->buf = buf; /* # uncoverable statement */
1383 0 q->next = loop->quar; /* # uncoverable statement */
1384 0 loop->quar = q; /* # uncoverable statement */
1385 }
1386  
1387 /*
1388 # uncoverable statement
1389 # uncoverable subroutine */
1390 0 static void hm_quar_release(hm_loop *loop, uint64_t token) {
1391 0 hm_quar **pp = &loop->quar, *q; /* # uncoverable statement */
1392 /*
1393 # uncoverable statement
1394 # uncoverable branch true
1395 # uncoverable branch false
1396 # uncoverable condition left count:1
1397 # uncoverable condition right count:1 */
1398 0 ▶ while ((q = *pp)) {
Branch: 1 branch
BranchTrueFalseTotal
while ((q = *pp)) { 0 0 0
1399 /*
1400 # uncoverable statement
1401 # uncoverable branch true
1402 # uncoverable branch false
1403 # uncoverable condition left count:1
1404 # uncoverable condition right count:1 */
1405 0 ▶ if (q->token == token) { *pp = q->next; free(q->buf); free(q); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (q->token == token) { *pp = q->next; free(q->buf); free(q); return; } 0 0 0
1406 0 pp = &q->next; /* # uncoverable statement */
1407 }
1408 }
1409  
1410 171 static void hm_quar_free_all(hm_loop *loop) {
1411 171 hm_quar *q = loop->quar, *n;
1412 /*
1413 # uncoverable branch true class:ignore_covered_err
1414 # uncoverable condition left count:1 class:ignore_covered_err */
1415 171 ▶ while (q) { n = q->next; free(q->buf); free(q); q = n; }
Branch: 1 branch
BranchTrueFalseTotal
while (q) { n = q->next; free(q->buf); free(q); q = n; } 0 171 171
1416 171 loop->quar = NULL;
1417 171 }
1418  
1419 /* Ask for this connection's next read. 1 if one is now outstanding, 0 if the
1420 * caller must fall back to a readiness watcher - which is always correct, so
1421 * every refusal here is a performance decision and never a correctness one. */
1422 861 static int hm_arm_recv(hm_loop *loop, hm_conn *c) {
1423 size_t want;
1424 /*
1425 # uncoverable branch false class:ignore_covered_err
1426 # uncoverable condition right count:1 class:ignore_covered_err
1427 # uncoverable condition left count:2 class:ignore_covered_err
1428 # uncoverable condition right count:2 class:ignore_covered_err */
1429 861 ▶ if (!loop->completion || !loop->be->submit_recv) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!loop->completion || !loop->be->submit_recv) return 0; 0 861 861
if (!loop->completion || !loop->be->submit_recv) return 0; 0 0 0
1430 /* TLS reads belong to OpenSSL: the bytes on the socket are ciphertext and
1431 * the engine may already hold plaintext this would never see. */
1432 /*
1433 # uncoverable statement
1434 # uncoverable branch true
1435 # uncoverable branch false
1436 # uncoverable condition left count:1
1437 # uncoverable condition right count:1
1438 # uncoverable condition left count:2
1439 # uncoverable condition right count:2
1440 # uncoverable condition left count:3
1441 # uncoverable condition right count:3
1442 # uncoverable condition left count:4
1443 # uncoverable condition right count:4 */
1444 0 ▶ if (c->ssl || c->recv_inflight || c->detached || c->pp_wait) return 0;
Branch: 4 branches
BranchTrueFalseTotal
if (c->ssl || c->recv_inflight || c->detached || c->pp_wait) return 0; 0 0 0
if (c->ssl || c->recv_inflight || c->detached || c->pp_wait) return 0; 0 0 0
if (c->ssl || c->recv_inflight || c->detached || c->pp_wait) return 0; 0 0 0
if (c->ssl || c->recv_inflight || c->detached || c->pp_wait) return 0; 0 0 0
1445 /*
1446 # uncoverable statement
1447 # uncoverable branch true
1448 # uncoverable branch false
1449 # uncoverable condition left count:1
1450 # uncoverable condition right count:1 */
1451 0 ▶ if (c->rlen == c->rcap) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen == c->rcap) { 0 0 0
1452 /* Grow BEFORE the kernel is given the pointer. Never while a read is
1453 * outstanding, which is why this cannot live in the completion. */
1454 size_t ncap;
1455 /*
1456 # uncoverable statement
1457 # uncoverable branch true
1458 # uncoverable branch false
1459 # uncoverable condition left count:1
1460 # uncoverable condition right count:1 */
1461 0 ▶ if (c->rcap >= loop->max_read) return 0; /* the readiness path owns
Branch: 1 branch
BranchTrueFalseTotal
if (c->rcap >= loop->max_read) return 0; /* the readiness path owns 0 0 0
1462 * the oversize/413 answer */
1463 0 ncap = c->rcap * 2; /* # uncoverable statement */
1464 /*
1465 # uncoverable statement
1466 # uncoverable branch true
1467 # uncoverable branch false
1468 # uncoverable condition left count:1
1469 # uncoverable condition right count:1 */
1470 0 ▶ if (ncap > loop->max_read) ncap = loop->max_read;
Branch: 1 branch
BranchTrueFalseTotal
if (ncap > loop->max_read) ncap = loop->max_read; 0 0 0
1471 0 c->rbuf = (char *)hm_xrealloc(c->rbuf, ncap); /* # uncoverable statement */
1472 0 c->rcap = ncap; /* # uncoverable statement */
1473 }
1474 0 want = c->rcap - c->rlen; /* # uncoverable statement */
1475 /*
1476 # uncoverable statement
1477 # uncoverable branch true
1478 # uncoverable branch false
1479 # uncoverable condition left count:1
1480 # uncoverable condition right count:1 */
1481 0 ▶ if (loop->be->submit_recv(loop->be, c->fd, c->rbuf + c->rlen, want,
Branch: 1 branch
BranchTrueFalseTotal
if (loop->be->submit_recv(loop->be, c->fd, c->rbuf + c->rlen, want, 0 0 0
1482 0 HM_RECV_TOKEN(c)) != 0) /* # uncoverable statement */
1483 0 return 0; /* # uncoverable statement */
1484 0 c->recv_inflight = 1; /* # uncoverable statement */
1485 0 return 1; /* # uncoverable statement */
1486 }
1487  
1488 static int hm_read_lend(hm_loop *loop, hm_conn *c);
1489 static void hm_read_unlend(hm_loop *loop, hm_conn *c);
1490  
1491 /* Requests are waiting in rbuf behind a park, a streamed body or a full write
1492 * buffer, and whoever serves them will memmove the buffer down. A completion
1493 * armed now holds rbuf + rlen, and after the move it lands past the new rlen
1494 * while rlen counts it from the front: the parser re-reads the tail of the
1495 * request it already served and waits for the rest of it until the idle
1496 * sweep. (t/27 on every Linux smoker with liburing: the request after a
1497 * pipelined one behind a sendfile body was never read.) */
1498 /*
1499 # uncoverable statement
1500 # uncoverable subroutine */
1501 0 static int hm_recv_unsafe(hm_conn *c) {
1502 0 return c->rlen > 0 /* # uncoverable statement */
1503 0 ▶ && (c->again_queued || c->bsrc.kind || c->awaiting /* # uncoverable statement */
Branch: 4 branches
BranchTrueFalseTotal
&& (c->again_queued || c->bsrc.kind || c->awaiting /* # uncoverable statement */ 0 0 0
&& (c->again_queued || c->bsrc.kind || c->awaiting /* # uncoverable statement */ 0 0 0
&& (c->again_queued || c->bsrc.kind || c->awaiting /* # uncoverable statement */ 0 0 0
&& (c->again_queued || c->bsrc.kind || c->awaiting /* # uncoverable statement */ 0 0 0
1504 0 ▶ || c->backlogged || c->stream_open); /* # uncoverable statement */
Branch: 2 branches
BranchTrueFalseTotal
|| c->backlogged || c->stream_open); /* # uncoverable statement */ 0 0 0
|| c->backlogged || c->stream_open); /* # uncoverable statement */ 0 0 0
1505 }
1506  
1507 /* Arm the next read however this connection reads: a completion if it can,
1508 * a readiness watcher otherwise. */
1509 871 static void hm_rearm_read(hm_loop *loop, hm_conn *c) {
1510 /* A readiness read happens at rlen as it stands at the time, so it is
1511 * safe across the move; given back once the buffer has been served. */
1512 /*
1513 # uncoverable branch true class:ignore_covered_err
1514 # uncoverable condition left count:1 class:ignore_covered_err */
1515 871 ▶ if (c->recv_lent) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_lent) { 0 871 871
1516 /*
1517 # uncoverable statement
1518 # uncoverable branch true
1519 # uncoverable branch false
1520 # uncoverable condition left count:1
1521 # uncoverable condition right count:1 */
1522 0 ▶ if (hm_recv_unsafe(c)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_recv_unsafe(c)) return; 0 0 0
1523 0 hm_read_unlend(loop, c); /* # uncoverable statement */
1524 0 c->recv_lent = 0; /* # uncoverable statement */
1525 }
1526 /* Already reading off readiness: the watcher is persistent and
1527 * level-triggered, so re-adding it would be a syscall per response on
1528 * epoll for no effect at all. */
1529 871 ▶ if (c->recv_fallback) return;
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_fallback) return; 10 861 871
1530 /* A read is already outstanding: the kernel holds rbuf + rlen and will
1531 * complete into it. A readiness watcher added now would read the same
1532 * bytes into the same offset first. hm_arm_recv refuses for the same
1533 * reason, but its refusal is not a request to fall back. */
1534 /*
1535 # uncoverable branch true
1536 # uncoverable condition left count:1 class:ignore_covered_err */
1537 861 ▶ if (c->recv_inflight) return;
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_inflight) return; 0 861 861
1538 /*
1539 # uncoverable branch true class:ignore_covered_err
1540 # uncoverable condition left count:1 class:ignore_covered_err
1541 # uncoverable condition left count:2 class:ignore_covered_err
1542 # uncoverable condition right count:2 class:ignore_covered_err */
1543 861 ▶ if (loop->completion && hm_recv_unsafe(c)) {
Branch: 2 branches
BranchTrueFalseTotal
if (loop->completion && hm_recv_unsafe(c)) { 0 861 861
if (loop->completion && hm_recv_unsafe(c)) { 0 0 0
1544 /*
1545 # uncoverable statement
1546 # uncoverable branch true
1547 # uncoverable branch false
1548 # uncoverable condition left count:1
1549 # uncoverable condition right count:1 */
1550 0 ▶ if (hm_read_lend(loop, c)) c->recv_lent = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_read_lend(loop, c)) c->recv_lent = 1; 0 0 0
1551 0 return; /* # uncoverable statement */
1552 }
1553 /*
1554 # uncoverable branch true
1555 # uncoverable condition left count:1 class:ignore_covered_err */
1556 861 ▶ if (hm_arm_recv(loop, c)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_arm_recv(loop, c)) return; 0 861 861
1557 861 c->recv_fallback = 1;
1558 861 loop->be->add_io(loop->be, c->fd, HM_EV_READ, 0);
1559 }
1560  
1561 /* Lend a completion-mode connection a readiness watcher for as long as an
1562 * application call that may wait on it is on the stack: an HTTP/2 handler
1563 * waiting for its body to drain is waiting for window updates on this very
1564 * socket. No completion is outstanding then - HM_EV_RECV re-arms only after
1565 * hm_process returns, and arming one under it would let the kernel write into
1566 * a buffer nghttp2 is consuming - so without the watcher the handler pumps a
1567 * loop that never reads its connection. 1 if lent. */
1568 0 static int hm_read_lend(hm_loop *loop, hm_conn *c) {
1569 /*
1570 # uncoverable branch false class:ignore_covered_err
1571 # uncoverable condition right count:1 class:ignore_covered_err
1572 # uncoverable condition left count:2 class:ignore_covered_err
1573 # uncoverable condition right count:2 class:ignore_covered_err
1574 # uncoverable condition left count:3 class:ignore_covered_err
1575 # uncoverable condition right count:3 class:ignore_covered_err */
1576 0 ▶ if (!loop->completion || c->recv_fallback || c->recv_inflight) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!loop->completion || c->recv_fallback || c->recv_inflight) return 0; 0 0 0
if (!loop->completion || c->recv_fallback || c->recv_inflight) return 0; 0 0 0
if (!loop->completion || c->recv_fallback || c->recv_inflight) return 0; 0 0 0
1577 0 c->recv_fallback = 1; /* # uncoverable statement */
1578 0 loop->be->add_io(loop->be, c->fd, HM_EV_READ, 0); /* # uncoverable statement */
1579 0 return 1; /* # uncoverable statement */
1580 }
1581  
1582 /* And take it back: the caller's hm_rearm_read returns it to completion. */
1583 /*
1584 # uncoverable statement
1585 # uncoverable subroutine */
1586 0 static void hm_read_unlend(hm_loop *loop, hm_conn *c) {
1587 /*
1588 # uncoverable statement
1589 # uncoverable branch true
1590 # uncoverable branch false
1591 # uncoverable condition left count:1
1592 # uncoverable condition right count:1 */
1593 0 ▶ if (!c->read_paused) loop->be->remove_io(loop->be, c->fd, HM_EV_READ);
Branch: 1 branch
BranchTrueFalseTotal
if (!c->read_paused) loop->be->remove_io(loop->be, c->fd, HM_EV_READ); 0 0 0
1594 0 c->read_paused = 0; /* # uncoverable statement */
1595 0 c->recv_fallback = 0; /* # uncoverable statement */
1596 0 }
1597  
1598 930 static void hm_close(pTHX_ hm_loop *loop, hm_conn *c) {
1599 /* A synchronous handler for this connection is on the stack: its ->get
1600 * pumped this loop and the loop found the peer gone, or the sweep found
1601 * it idle. The frame that called the app still holds c and will finish
1602 * with it (hm_process's consumed/memmove, hm_queue_response), so the
1603 * struct cannot be pooled - the next accept would hand it to a new
1604 * client and the first client's response would land on the second's
1605 * socket. Stop reading, mark it, and let that frame close it. */
1606 930 ▶ if (c->in_app) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->in_app) { 1 929 930
1607 /*
1608 # uncoverable branch false class:ignore_covered_err
1609 # uncoverable condition right count:1 class:ignore_covered_err */
1610 1 ▶ if (!c->close_deferred) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->close_deferred) { 1 0 1
1611 1 c->close_deferred = 1;
1612 1 loop->be->remove_io(loop->be, c->fd,
1613 1 ▶ HM_EV_READ | (c->writing ? HM_EV_WRITE : 0)); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
HM_EV_READ | (c->writing ? HM_EV_WRITE : 0)); /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 1 1
1614 1 c->writing = 0;
1615 }
1616 1 return;
1617 }
1618 /* Stream handles open on this connection die with it. They are told
1619 * first, while the connection is still consistent, and they are only
1620 * marked dead - the handle itself belongs to whoever opened it until
1621 * it calls stream_close. */
1622 929 ▶ if (hm_stream_live_n) hm_stream_conn_gone(aTHX_ c->fd, c->id);
Branch: 1 branch
BranchTrueFalseTotal
if (hm_stream_live_n) hm_stream_conn_gone(aTHX_ c->fd, c->id); 12 917 929
1623 /* Before anything else touches the buffers: if the kernel is still
1624 * holding a pointer into this connection's read buffer, take the buffer
1625 * away from the connection so the pooling below cannot hand it to the
1626 * next one. The connection is pooled with a NULL rbuf and hm_new_conn
1627 * allocates a fresh one. */
1628 /* c is never NULL here - every caller passes a live connection, and this
1629 * function dereferences it unconditionally a few lines down. The `c &&`
1630 * these two guards used to carry was dead, and it told a static analyser
1631 * the opposite of the truth: cppcheck reported four null dereferences
1632 * from it, all of them the guard's fault rather than the code's. */
1633 /*
1634 # uncoverable branch true class:ignore_covered_err
1635 # uncoverable condition left count:1 class:ignore_covered_err */
1636 929 ▶ if (c->recv_inflight) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_inflight) { 0 929 929
1637 /*
1638 # uncoverable statement
1639 # uncoverable branch true
1640 # uncoverable branch false
1641 # uncoverable condition left count:1
1642 # uncoverable condition right count:1 */
1643 0 ▶ if (loop->be->cancel_recv) loop->be->cancel_recv(loop->be, c->fd);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->be->cancel_recv) loop->be->cancel_recv(loop->be, c->fd); 0 0 0
1644 0 hm_quar_push(loop, HM_RECV_TOKEN(c), c->rbuf); /* # uncoverable statement */
1645 0 c->rbuf = NULL; /* # uncoverable statement */
1646 0 c->rcap = 0; /* # uncoverable statement */
1647 0 c->rlen = 0; /* # uncoverable statement */
1648 0 c->recv_inflight = 0; /* # uncoverable statement */
1649 }
1650 929 ▶ if (c->spill_fd >= 0) { /* a body was still draining */
Branch: 1 branch
BranchTrueFalseTotal
if (c->spill_fd >= 0) { /* a body was still draining */ 1 928 929
1651 1 PerlLIO_close(c->spill_fd);
1652 1 c->spill_fd = -1;
1653 1 c->spill_got = 0;
1654 }
1655 929 int fd = c->fd;
1656 929 SV *pending = c->resp_f; /* cancelled below, once state is consistent */
1657 929 c->resp_f = NULL;
1658 929 ▶ loop->be->remove_io(loop->be, fd, HM_EV_READ | (c->writing ? HM_EV_WRITE : 0)); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
loop->be->remove_io(loop->be, fd, HM_EV_READ | (c->writing ? HM_EV_WRITE : 0)); /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 928 929
1659 929 ▶ if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc); /* mid-stream abort */
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc); /* mid-stream abort */ 1 928 929
1660 929 ▶ if (c->ssl) hm_tls_conn_free(c);
Branch: 1 branch
BranchTrueFalseTotal
if (c->ssl) hm_tls_conn_free(c); 61 868 929
1661 929 hm_os_close(fd);
1662 929 hm_lru_unlink(loop, c);
1663 929 loop->conns[fd] = NULL;
1664 929 loop->nconns--;
1665 929 ▶ if (c->io_sv) { SvREFCNT_dec(c->io_sv); c->io_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->io_sv) { SvREFCNT_dec(c->io_sv); c->io_sv = NULL; } 807 122 929
1666 929 ▶ if (c->cid_sv) { SvREFCNT_dec(c->cid_sv); c->cid_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->cid_sv) { SvREFCNT_dec(c->cid_sv); c->cid_sv = NULL; } 807 122 929
1667 /*
1668 # uncoverable branch true class:ignore_covered_err
1669 # uncoverable condition left count:1 class:ignore_covered_err */
1670 929 ▶ if (c->env_sv) { SvREFCNT_dec(c->env_sv); c->env_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { SvREFCNT_dec(c->env_sv); c->env_sv = NULL; } 0 929 929
1671 929 ▶ if (c->peer_sv) { SvREFCNT_dec(c->peer_sv); c->peer_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_sv) { SvREFCNT_dec(c->peer_sv); c->peer_sv = NULL; } 805 124 929
1672 929 ▶ if (c->peer_host_sv) { SvREFCNT_dec(c->peer_host_sv); c->peer_host_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_host_sv) { SvREFCNT_dec(c->peer_host_sv); c->peer_host_sv = NULL; } 805 124 929
1673 929 ▶ if (c->peer_port_sv) { SvREFCNT_dec(c->peer_port_sv); c->peer_port_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_port_sv) { SvREFCNT_dec(c->peer_port_sv); c->peer_port_sv = NULL; } 805 124 929
1674 929 ▶ if (c->sname_sv) { SvREFCNT_dec(c->sname_sv); c->sname_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->sname_sv) { SvREFCNT_dec(c->sname_sv); c->sname_sv = NULL; } 807 122 929
1675 929 ▶ if (c->sport_sv) { SvREFCNT_dec(c->sport_sv); c->sport_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->sport_sv) { SvREFCNT_dec(c->sport_sv); c->sport_sv = NULL; } 807 122 929
1676 /* Detached from the connection BEFORE it is torn down: freeing the
1677 * session cancels every stream's parked Future, and a continuation
1678 * that fires on that cancel looks the stream up through c->h2. */
1679 929 ▶ if (c->h2) { void *h2 = c->h2; c->h2 = NULL; hm_h2_free(aTHX_ h2); }
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) { void *h2 = c->h2; c->h2 = NULL; hm_h2_free(aTHX_ h2); } 0 929 929
1680 929 hm_pool_conn(loop, c);
1681 929 ▶ if (loop->stopping && loop->nconns == 0) loop->stop = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (loop->stopping && loop->nconns == 0) loop->stop = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 928 929
if (loop->stopping && loop->nconns == 0) loop->stop = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
1682 /* client went away while awaiting: cancel the response Future so
1683 * in-flight async work can abort (propagates up the then-chain) */
1684 929 ▶ if (pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (pending) { 1 928 929
1685 1 dSP;
1686 1 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 1 1
1687 1 ▶ XPUSHs(pending);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(pending); 0 1 1
1688 1 PUTBACK;
1689 1 call_method("cancel", G_DISCARD | G_EVAL);
1690 1 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 1 0 1
1691 1 SvREFCNT_dec(pending);
1692 }
1693 }
1694  
1695 /* ---- detach: hand a live HTTP/1 connection to the application ------------ *
1696 * The seam a protocol upgrade (WebSocket) needs: the socket stays open and
1697 * becomes the app's, while the server forgets it entirely so the app's own
1698 * io watchers on that fd fire (hm_dispatch routes to loop->io_r/io_w only
1699 * when conns[fd] is NULL).
1700 *
1701 * Two phases, because the callers of the app frame keep using the conn after
1702 * it returns (hm_process's consumed/memmove, hm_deliver's flush):
1703 *
1704 * hm_detach - immediate: validate, disarm the server's watchers so
1705 * no further bytes are pulled in, flag the conn.
1706 * hm_conn_release - deferred: hm_close minus the close(2) and minus the
1707 * watcher removal, run once the caller is done with the
1708 * conn. After it, conns[fd] is NULL and the fd is the
1709 * application's to own and to close.
1710 *
1711 * The app must not have produced any response bytes for this request, and
1712 * returns a sentinel (conventionally [101, [], []]) which is discarded. */
1713 10 static int hm_detach(pTHX_ hm_loop *loop, int fd, UV id) {
1714 hm_conn *c;
1715 #ifdef _WIN32
1716 /* The fd is a CRT wrapper around a SOCKET (hm_win.h). Handing that to
1717 * perl's IO layer to own, after this server stops watching it, has not
1718 * been proven on a real Windows box - so it is refused rather than
1719 * half-supported. A WebSocket tier over this server falls back to
1720 * psgi.streaming, which is its documented second transport. */
1721 (void)loop; (void)fd; (void)id; (void)c;
1722 return -6;
1723 #else
1724 10 ▶ if (fd < 0 || fd >= HM_MAXFD) return -1; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 || fd >= HM_MAXFD) return -1; /* # uncoverable condition left count:1 class:ignore_covered_err */ 10 0 10
if (fd < 0 || fd >= HM_MAXFD) return -1; /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 9 10
1725 9 c = loop->conns[fd];
1726 9 ▶ if (!c || c->id != id) return -1; /* gone, or a stale ticket */ /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!c || c->id != id) return -1; /* gone, or a stale ticket */ /* # uncoverable condition left count:2 class:ignore_covered_err */ 8 1 9
if (!c || c->id != id) return -1; /* gone, or a stale ticket */ /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 8 8
1727 /*
1728 # uncoverable branch true
1729 # uncoverable condition left count:1 class:ignore_covered_err */
1730 8 ▶ if (c->h2) return -2; /* HTTP/2 streams share a conn */
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) return -2; /* HTTP/2 streams share a conn */ 0 8 8
1731 8 ▶ if (c->ssl) return -3; /* TLS state cannot be handed on */
Branch: 1 branch
BranchTrueFalseTotal
if (c->ssl) return -3; /* TLS state cannot be handed on */ 1 7 8
1732 7 ▶ if (c->wlen != c->woff /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
if (c->wlen != c->woff /* # uncoverable condition left count:2 class:ignore_covered_err */ 6 1 7
1733 7 ▶ || c->bsrc.kind) return -4; /* output still draining */
Branch: 1 branch
BranchTrueFalseTotal
|| c->bsrc.kind) return -4; /* output still draining */ 0 6 6
1734 6 ▶ if (c->detached) return -5; /* already handed over */
Branch: 1 branch
BranchTrueFalseTotal
if (c->detached) return -5; /* already handed over */ 2 4 6
1735 4 loop->be->remove_io(loop->be, fd,
1736 4 ▶ HM_EV_READ | (c->writing ? HM_EV_WRITE : 0)); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
HM_EV_READ | (c->writing ? HM_EV_WRITE : 0)); /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 4 4
1737 4 c->writing = 0;
1738 4 c->detached = 1;
1739 4 return 0;
1740 #endif
1741 }
1742  
1743 /* Deferred half of hm_detach: forget the connection without closing its fd. */
1744 4 static void hm_conn_release(pTHX_ hm_loop *loop, hm_conn *c) {
1745 4 int fd = c->fd;
1746 4 SV *pending = c->resp_f;
1747 /* The fd survives, the connection object does not: a handle naming it
1748 * is as dead as it would be after a close. */
1749 /*
1750 # uncoverable branch true class:ignore_covered_err
1751 # uncoverable condition left count:1 class:ignore_covered_err */
1752 4 ▶ if (hm_stream_live_n) hm_stream_conn_gone(aTHX_ c->fd, c->id);
Branch: 1 branch
BranchTrueFalseTotal
if (hm_stream_live_n) hm_stream_conn_gone(aTHX_ c->fd, c->id); 0 4 4
1753 4 c->resp_f = NULL; /* # uncoverable statement class:ignore_covered_err */
1754 /*
1755 # uncoverable statement class:ignore_covered_err
1756 # uncoverable branch true
1757 # uncoverable condition left count:1 */
1758 4 ▶ if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc);
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc); 0 4 4
1759 4 hm_lru_unlink(loop, c);
1760 4 loop->conns[fd] = NULL;
1761 4 loop->nconns--;
1762 /*
1763 # uncoverable branch false class:ignore_covered_err
1764 # uncoverable condition right count:1 class:ignore_covered_err */
1765 4 ▶ if (c->io_sv) { SvREFCNT_dec(c->io_sv); c->io_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->io_sv) { SvREFCNT_dec(c->io_sv); c->io_sv = NULL; } 4 0 4
1766 /*
1767 # uncoverable branch false class:ignore_covered_err
1768 # uncoverable condition right count:1 class:ignore_covered_err */
1769 4 ▶ if (c->cid_sv) { SvREFCNT_dec(c->cid_sv); c->cid_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->cid_sv) { SvREFCNT_dec(c->cid_sv); c->cid_sv = NULL; } 4 0 4
1770 /*
1771 # uncoverable branch true class:ignore_covered_err
1772 # uncoverable condition left count:1 class:ignore_covered_err */
1773 4 ▶ if (c->env_sv) { SvREFCNT_dec(c->env_sv); c->env_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { SvREFCNT_dec(c->env_sv); c->env_sv = NULL; } 0 4 4
1774 /*
1775 # uncoverable branch false class:ignore_covered_err
1776 # uncoverable condition right count:1 class:ignore_covered_err */
1777 4 ▶ if (c->peer_sv) { SvREFCNT_dec(c->peer_sv); c->peer_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_sv) { SvREFCNT_dec(c->peer_sv); c->peer_sv = NULL; } 4 0 4
1778 /*
1779 # uncoverable branch false class:ignore_covered_err
1780 # uncoverable condition right count:1 class:ignore_covered_err */
1781 4 ▶ if (c->peer_host_sv) { SvREFCNT_dec(c->peer_host_sv); c->peer_host_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_host_sv) { SvREFCNT_dec(c->peer_host_sv); c->peer_host_sv = NULL; } 4 0 4
1782 /*
1783 # uncoverable branch false class:ignore_covered_err
1784 # uncoverable condition right count:1 class:ignore_covered_err */
1785 4 ▶ if (c->peer_port_sv) { SvREFCNT_dec(c->peer_port_sv); c->peer_port_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_port_sv) { SvREFCNT_dec(c->peer_port_sv); c->peer_port_sv = NULL; } 4 0 4
1786 /*
1787 # uncoverable branch false class:ignore_covered_err
1788 # uncoverable condition right count:1 class:ignore_covered_err */
1789 4 ▶ if (c->sname_sv) { SvREFCNT_dec(c->sname_sv); c->sname_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->sname_sv) { SvREFCNT_dec(c->sname_sv); c->sname_sv = NULL; } 4 0 4
1790 /*
1791 # uncoverable branch false class:ignore_covered_err
1792 # uncoverable condition right count:1 class:ignore_covered_err */
1793 4 ▶ if (c->sport_sv) { SvREFCNT_dec(c->sport_sv); c->sport_sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->sport_sv) { SvREFCNT_dec(c->sport_sv); c->sport_sv = NULL; } 4 0 4
1794 4 hm_pool_conn(loop, c);
1795 /*
1796 # uncoverable branch true class:ignore_covered_err
1797 # uncoverable condition left count:1 class:ignore_covered_err
1798 # uncoverable condition left count:2 class:ignore_covered_err
1799 # uncoverable condition right count:2 class:ignore_covered_err */
1800 4 ▶ if (loop->stopping && loop->nconns == 0) loop->stop = 1;
Branch: 2 branches
BranchTrueFalseTotal
if (loop->stopping && loop->nconns == 0) loop->stop = 1; 0 4 4
if (loop->stopping && loop->nconns == 0) loop->stop = 1; 0 0 0
1801 /* the request's own Future, if any, is simply dropped - the app owns
1802 * the socket now, so there is nothing left to cancel it for */
1803 /*
1804 # uncoverable statement class:ignore_covered_err
1805 # uncoverable branch true
1806 # uncoverable condition left count:1 */
1807 4 ▶ if (pending) SvREFCNT_dec(pending);
Branch: 1 branch
BranchTrueFalseTotal
if (pending) SvREFCNT_dec(pending); 0 4 4
1808 4 }
1809  
1810 934 static hm_conn *hm_new_conn(hm_loop *loop, int fd, hm_listener *lst) {
1811 hm_conn *c;
1812 934 ▶ if (loop->pool) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->pool) { 794 140 934
1813 char *wbuf, *rbuf; size_t wcap, rcap;
1814 794 c = loop->pool;
1815 794 loop->pool = c->pool_next;
1816 794 loop->pool_n--;
1817 794 wbuf = c->wbuf; wcap = c->wcap; /* keep the buffers */
1818 794 rbuf = c->rbuf; rcap = c->rcap;
1819 794 memset(c, 0, sizeof(*c));
1820 794 c->wbuf = wbuf; c->wcap = wcap;
1821 794 c->rbuf = rbuf; c->rcap = rcap;
1822 } else {
1823 140 c = (hm_conn *)hm_xcalloc(1, sizeof(hm_conn));
1824 }
1825 934 ▶ if (!c->rbuf) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->rbuf) { 145 789 934
1826 145 c->rbuf = (char *)hm_xmalloc(HM_RBUF);
1827 145 c->rcap = HM_RBUF;
1828 }
1829 934 c->fd = fd;
1830 934 c->keepalive = 1;
1831 934 c->spill_fd = -1; /* 0 is a real fd; the zeroed struct is not
1832 * "not spilling" without this */
1833 934 c->spill_got = 0;
1834 934 c->id = ++hm_id_counter;
1835 934 c->loop = loop;
1836 934 c->lst = lst;
1837 934 c->last_active = loop->now;
1838 934 loop->conns[fd] = c;
1839 934 loop->nconns++;
1840 #ifndef HM_HAVE_ACCEPT4
1841 hm_set_nonblock(fd); /* accept4 did it where there is one */
1842 #endif
1843 934 ▶ if (!(lst && lst->is_unix)) { /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!(lst && lst->is_unix)) { /* # uncoverable condition left count:1 class:ignore_covered_err */ 934 0 934
if (!(lst && lst->is_unix)) { /* # uncoverable condition left count:1 class:ignore_covered_err */ 932 2 934
1844 932 int one = 1;
1845 932 hm_os_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
1846 }
1847 934 ▶ if (lst && lst->proxy_protocol) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (lst && lst->proxy_protocol) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 934 0 934
if (lst && lst->proxy_protocol) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 14 920 934
1848 /* The PROXY header comes first, on the raw socket, before TLS can
1849 * wrap it and before any request byte is read. Readiness reads for
1850 * life (recv_fallback), the header-phase timeout from now, and no
1851 * TLS until hm_proxy_readable has the client's address. */
1852 14 c->pp_wait = 1;
1853 14 c->recv_fallback = 1;
1854 14 c->req_start = loop->now;
1855 14 loop->be->add_io(loop->be, fd, HM_EV_READ, 0);
1856 }
1857 920 ▶ else if (lst && lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
else if (lst && lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 920 0 920
else if (lst && lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 60 860 920
1858 /* TLS wraps first: the handshake is driven off readiness, and
1859 * hm_arm_recv would decline a TLS connection anyway. The handshake
1860 * is timed as a request header is (req_start): a peer that opens a
1861 * socket and never finishes its ClientHello was holding a slot for
1862 * idle_timeout. A wrap that fails (SSL_new under memory pressure)
1863 * closes rather than serving plaintext on a TLS listener. */
1864 60 c->req_start = loop->now;
1865 /*
1866 # uncoverable branch true
1867 # uncoverable condition left count:1 class:ignore_covered_err */
1868 120 ▶ if (hm_tls_wrap(c, lst->tls_ctx) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_tls_wrap(c, lst->tls_ctx) < 0) { 0 60 60
1869 0 hm_errlog("Hyperman: TLS setup failed for a new connection; closed\n"); /* # uncoverable statement */
1870 0 c->tls_failed = 1; /* hm_accept closes it, with aTHX */ /* # uncoverable statement */
1871 } else {
1872 60 loop->be->add_io(loop->be, fd, HM_EV_READ, 0);
1873 }
1874 }
1875 860 else hm_rearm_read(loop, c);
1876 /* append to LRU tail */
1877 934 c->lru_prev = loop->lru_tail;
1878 934 ▶ if (loop->lru_tail) loop->lru_tail->lru_next = c;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->lru_tail) loop->lru_tail->lru_next = c; 146 788 934
1879 934 loop->lru_tail = c;
1880 934 ▶ if (!loop->lru_head) loop->lru_head = c;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->lru_head) loop->lru_head = c; 788 146 934
1881 934 return c;
1882 }
1883  
1884 /* ---- HTTP parse ---------------------------------------------------------- */
1885  
1886 /* Find a request header's value in the header block (case-insensitive name).
1887 * Returns a pointer to the (trimmed) value and sets *vlen, or NULL. */
1888 417 static const char *hm_find_header(const char *head, size_t headlen,
1889 const char *name, size_t nlen, size_t *vlen) {
1890 417 const char *p = (const char *)memchr(head, '\n', headlen); /* skip req line */
1891 417 const char *hend = head + headlen;
1892 /*
1893 # uncoverable branch true
1894 # uncoverable condition left count:1 class:ignore_covered_err */
1895 417 ▶ if (!p) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return NULL; 0 417 417
1896 417 p++;
1897 1355 ▶ while (p < hend) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < hend) { 958 397 1355
1898 958 const char *eol = (const char *)memchr(p, '\r', hend - p);
1899 958 ▶ size_t len = eol ? (size_t)(eol - p) : (size_t)(hend - p);
Branch: 1 branch
BranchTrueFalseTotal
size_t len = eol ? (size_t)(eol - p) : (size_t)(hend - p); 554 404 958
1900 958 const char *colon = (const char *)memchr(p, ':', len);
1901 958 ▶ if (colon && (size_t)(colon - p) == nlen
Branch: 2 branches
BranchTrueFalseTotal
if (colon && (size_t)(colon - p) == nlen 958 0 958
if (colon && (size_t)(colon - p) == nlen 40 918 958
1902 40 ▶ && hm_strncasecmp(p, name, nlen) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(p, name, nlen) == 0) { 20 20 40
1903 20 const char *v = colon + 1;
1904 20 size_t vl = (size_t)((p + len) - v);
1905 /*
1906 # uncoverable condition right count:1 class:ignore_covered_err
1907 # uncoverable condition left count:3 class:ignore_covered_err */
1908 40 ▶ while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; }
Branch: 3 branches
BranchTrueFalseTotal
while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; } 40 0 40
while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; } 20 20 40
while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; } 0 20 20
1909 /*
1910 # uncoverable branch true
1911 # uncoverable condition left count:1 class:ignore_covered_err
1912 # uncoverable condition right count:1 class:ignore_covered_err
1913 # uncoverable condition left count:2 class:ignore_covered_err
1914 # uncoverable condition left count:3 class:ignore_covered_err */
1915 20 ▶ while (vl && (v[vl-1] == ' ' || v[vl-1] == '\t')) vl--;
Branch: 3 branches
BranchTrueFalseTotal
while (vl && (v[vl-1] == ' ' || v[vl-1] == '\t')) vl--; 20 0 20
while (vl && (v[vl-1] == ' ' || v[vl-1] == '\t')) vl--; 0 20 20
while (vl && (v[vl-1] == ' ' || v[vl-1] == '\t')) vl--; 0 20 20
1916 20 *vlen = vl;
1917 20 return v;
1918 }
1919 938 ▶ p = eol ? eol + 2 : hend;
Branch: 1 branch
BranchTrueFalseTotal
p = eol ? eol + 2 : hend; 541 397 938
1920 }
1921 397 return NULL;
1922 }
1923  
1924 /* case-insensitive substring search */
1925 9 static int hm_ci_contains(const char *hay, size_t hl, const char *needle) {
1926 9 size_t nl = strlen(needle), i;
1927 /*
1928 # uncoverable branch true
1929 # uncoverable condition left count:1 class:ignore_covered_err */
1930 9 ▶ if (nl > hl) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (nl > hl) return 0; 0 9 9
1931 36 ▶ for (i = 0; i + nl <= hl; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + nl <= hl; i++) 27 9 36
1932 27 ▶ if (hm_strncasecmp(hay + i, needle, nl) == 0) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_strncasecmp(hay + i, needle, nl) == 0) return 1; 0 27 27
1933 9 return 0;
1934 }
1935  
1936 /* ---- Expect: 100-continue (RFC 9110 10.1.1) -------------------------------
1937 * A client that expects to send a large body may ask permission first and
1938 * wait for an interim 100 before spending the upload. A server that never
1939 * answers does not break such a client - it stalls it, for however long the
1940 * client is prepared to wait (a second, in curl and in most of the Java
1941 * clients) on every request. So the answer is worth having for its own sake,
1942 * and the refusals are worth having more: a body over max_body is refused
1943 * here, on the headers, rather than after the client has sent it all.
1944 */
1945 #define HM_EXPECT_NONE 0
1946 #define HM_EXPECT_CONTINUE 1
1947 #define HM_EXPECT_OTHER 2
1948  
1949 /* The request line's HTTP version. Only "is it 1.1" is asked: 100-continue
1950 * is an HTTP/1.1 expectation and a 1.0 client's Expect MUST be ignored. */
1951 941 static int hm_req_is_11(const char *head, size_t headlen) {
1952 941 const char *eol = (const char *)memchr(head, '\r', headlen);
1953 941 ▶ size_t ll = eol ? (size_t)(eol - head) : headlen;
Branch: 1 branch
BranchTrueFalseTotal
size_t ll = eol ? (size_t)(eol - head) : headlen; 703 238 941
1954 941 ▶ return ll >= 8 && memcmp(head + ll - 8, "HTTP/1.1", 8) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
return ll >= 8 && memcmp(head + ll - 8, "HTTP/1.1", 8) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 941 0 941
return ll >= 8 && memcmp(head + ll - 8, "HTTP/1.1", 8) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 417 524 941
1955 }
1956  
1957 /* Classify the Expect field. The value is a list, and 100-continue is the
1958 * only member this server understands, so anything else - including
1959 * 100-continue with something else beside it - is an expectation it cannot
1960 * meet and earns a 417 rather than a silent promise it will not keep. */
1961 941 static int hm_expectation(const char *head, size_t headlen) {
1962 941 size_t vl = 0;
1963 const char *v;
1964 941 ▶ if (!hm_req_is_11(head, headlen)) return HM_EXPECT_NONE;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_req_is_11(head, headlen)) return HM_EXPECT_NONE; 524 417 941
1965 417 v = hm_find_header(head, headlen, "expect", 6, &vl);
1966 417 ▶ if (!v || !vl) return HM_EXPECT_NONE; /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!v || !vl) return HM_EXPECT_NONE; /* # uncoverable condition left count:2 class:ignore_covered_err */ 20 397 417
if (!v || !vl) return HM_EXPECT_NONE; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 20 20
1967 20 ▶ if (vl == 12 && hm_strncasecmp(v, "100-continue", 12) == 0) /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (vl == 12 && hm_strncasecmp(v, "100-continue", 12) == 0) /* # uncoverable condition right count:2 class:ignore_covered_err */ 18 2 20
if (vl == 12 && hm_strncasecmp(v, "100-continue", 12) == 0) /* # uncoverable condition right count:2 class:ignore_covered_err */ 18 0 18
1968 18 return HM_EXPECT_CONTINUE;
1969 2 return HM_EXPECT_OTHER;
1970 }
1971  
1972 /* Send the interim response, once per request. Called only where the headers
1973 * have been accepted AND the body is not all here yet: a request already
1974 * carrying its whole body is answered with its final status instead, which
1975 * RFC 9110 allows and every client handles, and a request that is going to
1976 * be refused is refused before this is ever reached. */
1977 47 static void hm_send_continue(hm_conn *c, int expect) {
1978 static const char cont[] = "HTTP/1.1 100 Continue\r\n\r\n";
1979 47 ▶ if (expect != HM_EXPECT_CONTINUE || c->cont_sent) return;
Branch: 2 branches
BranchTrueFalseTotal
if (expect != HM_EXPECT_CONTINUE || c->cont_sent) return; 10 37 47
if (expect != HM_EXPECT_CONTINUE || c->cont_sent) return; 5 5 10
1980 5 c->cont_sent = 1;
1981 5 hm_wb_put(c, cont, sizeof(cont) - 1);
1982 }
1983  
1984 /* Percent-decode a path once (RFC 3875 PATH_INFO): %XX only, no '+'. */
1985 879 static SV *hm_pct_decode(pTHX_ const char *p, STRLEN n) {
1986 879 SV *sv = newSV(n + 1);
1987 879 char *d = SvPVX(sv);
1988 879 STRLEN i = 0, o = 0;
1989 879 SvPOK_on(sv);
1990 3669 ▶ while (i < n) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < n) { 2790 879 3669
1991 2790 ▶ if (p[i] == '%' && i + 2 < n /* # uncoverable condition right count:4 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (p[i] == '%' && i + 2 < n /* # uncoverable condition right count:4 class:ignore_covered_err */ 11 2779 2790
if (p[i] == '%' && i + 2 < n /* # uncoverable condition right count:4 class:ignore_covered_err */ 10 1 11
1992 10 ▶ && isxdigit((unsigned char)p[i+1]) && isxdigit((unsigned char)p[i+2])) {
Branch: 2 branches
BranchTrueFalseTotal
&& isxdigit((unsigned char)p[i+1]) && isxdigit((unsigned char)p[i+2])) { 9 1 10
&& isxdigit((unsigned char)p[i+1]) && isxdigit((unsigned char)p[i+2])) { 9 0 9
1993 9 int hi = p[i+1], lo = p[i+2];
1994 9 ▶ hi = (hi <= '9') ? hi - '0' : (hi | 32) - 'a' + 10;
Branch: 1 branch
BranchTrueFalseTotal
hi = (hi <= '9') ? hi - '0' : (hi | 32) - 'a' + 10; 8 1 9
1995 9 ▶ lo = (lo <= '9') ? lo - '0' : (lo | 32) - 'a' + 10;
Branch: 1 branch
BranchTrueFalseTotal
lo = (lo <= '9') ? lo - '0' : (lo | 32) - 'a' + 10; 7 2 9
1996 9 d[o++] = (char)((hi << 4) | lo);
1997 9 i += 3;
1998 } else {
1999 2781 d[o++] = p[i++];
2000 }
2001 }
2002 879 d[o] = 0;
2003 879 SvCUR_set(sv, o);
2004 879 return sv;
2005 }
2006  
2007 /* ---- $env fast path ------------------------------------------------------
2008 * The fixed $env keys as shared-string SVs: the hash is computed once and
2009 * cached in the shared string table, so hv_store_ent skips both the hashing
2010 * and the key copy on every request. Values that never vary per process
2011 * ([1,1], the 0/1 flags, psgi.errors) are read-only singletons shared by
2012 * refcount; per-connection constants (REMOTE_*, SERVER_*) are cached on the
2013 * connection. Anything a middleware conventionally assigns in place
2014 * (psgi.url_scheme, SCRIPT_NAME, PATH_INFO) stays a fresh SV per request. */
2015  
2016 enum {
2017 HMK_REQUEST_METHOD, HMK_REQUEST_URI, HMK_PATH_INFO, HMK_QUERY_STRING,
2018 HMK_SERVER_PROTOCOL, HMK_SCRIPT_NAME, HMK_SERVER_NAME, HMK_SERVER_PORT,
2019 HMK_REMOTE_ADDR, HMK_REMOTE_HOST, HMK_REMOTE_PORT,
2020 HMK_PSGI_VERSION, HMK_PSGI_URL_SCHEME, HMK_PSGI_MULTITHREAD,
2021 HMK_PSGI_MULTIPROCESS, HMK_PSGI_RUN_ONCE, HMK_PSGI_STREAMING,
2022 HMK_PSGI_NONBLOCKING, HMK_PSGI_ERRORS, HMK_PSGIX_LOOP, HMK_PSGIX_IO,
2023 HMK_PSGI_INPUT, HMK_PSGIX_INPUT_BUFFERED, HMK_CONTENT_LENGTH,
2024 HMK_CONTENT_TYPE, HMK_PSGIX_HM_CONN, HMK_PSGIX_HM_STREAM, HMK_PSGIX_PROXY_ADDR,
2025 HMK_COUNT
2026 };
2027 static const char *const hm_env_key_name[HMK_COUNT] = {
2028 "REQUEST_METHOD", "REQUEST_URI", "PATH_INFO", "QUERY_STRING",
2029 "SERVER_PROTOCOL", "SCRIPT_NAME", "SERVER_NAME", "SERVER_PORT",
2030 "REMOTE_ADDR", "REMOTE_HOST", "REMOTE_PORT",
2031 "psgi.version", "psgi.url_scheme", "psgi.multithread",
2032 "psgi.multiprocess", "psgi.run_once", "psgi.streaming",
2033 "psgi.nonblocking", "psgi.errors", "psgix.loop", "psgix.io",
2034 "psgi.input", "psgix.input.buffered", "CONTENT_LENGTH",
2035 "CONTENT_TYPE", "psgix.hyperman.conn", "psgix.hyperman.stream",
2036 "psgix.proxy_addr"
2037 };
2038 static SV *hm_env_key[HMK_COUNT];
2039 static SV *hm_env_zero, *hm_env_one; /* read-only 0/1 flag values */
2040 static SV *hm_env_version; /* read-only [1,1] */
2041 static SV *hm_env_errors; /* read-only \*STDERR */
2042  
2043 /* The HTTP_* keys for the headers real traffic actually sends, as shared
2044 * key SVs made once. Storing with a plain char* key makes hv_common hash
2045 * the string and cut a fresh HEK against the shared string table on every
2046 * request, then release it again at env teardown; storing through a shared
2047 * SV reuses the precomputed hash and the one HEK for the process's life.
2048 * A browser request carries a dozen of these, so it pays per header, per
2049 * request. Anything not in this table just takes the char* path it always
2050 * took. Grouped by key length so the lookup is a couple of memcmps. */
2051 static const char *const hm_hdrk_name[] = {
2052 "HTTP_TE", /* 7 */
2053 "HTTP_DNT", /* 8 */
2054 "HTTP_HOST", /* 9 */
2055 "HTTP_RANGE", /* 10 */
2056 "HTTP_ACCEPT", "HTTP_COOKIE", "HTTP_ORIGIN", "HTTP_PRAGMA", /* 11 */
2057 "HTTP_REFERER", "HTTP_UPGRADE", /* 12 */
2058 "HTTP_USER_AGENT", "HTTP_CONNECTION", /* 15 */
2059 "HTTP_AUTHORIZATION", "HTTP_CACHE_CONTROL",
2060 "HTTP_IF_NONE_MATCH", /* 18 */
2061 "HTTP_ACCEPT_ENCODING", "HTTP_ACCEPT_LANGUAGE",
2062 "HTTP_X_FORWARDED_FOR", /* 20 */
2063 "HTTP_X_REQUESTED_WITH", /* 21 */
2064 "HTTP_IF_MODIFIED_SINCE", "HTTP_X_FORWARDED_PROTO",
2065 "HTTP_SEC_WEBSOCKET_KEY", /* 22 */
2066 "HTTP_SEC_WEBSOCKET_VERSION", /* 26 */
2067 NULL
2068 };
2069 #define HM_HDRK_MAXLEN 26
2070 #define HM_HDRK_PERLEN 5
2071 static SV *hm_hdrk_sv[sizeof(hm_hdrk_name) / sizeof(char *)];
2072 /* index+1 of each candidate, per key length; 0 ends the row */
2073 static unsigned char hm_hdrk_by_len[HM_HDRK_MAXLEN + 1][HM_HDRK_PERLEN];
2074  
2075 /* the cached key SV for keybuf/klen, or NULL for the char* fallback */
2076 1040 static SV *hm_hdrk_lookup(const char *keybuf, size_t klen) {
2077 const unsigned char *row;
2078 int i;
2079 /*
2080 # uncoverable branch true
2081 # uncoverable condition left count:1 class:ignore_covered_err */
2082 1040 ▶ if (klen > HM_HDRK_MAXLEN) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (klen > HM_HDRK_MAXLEN) return NULL; 0 1040 1040
2083 1040 row = hm_hdrk_by_len[klen];
2084 1347 ▶ for (i = 0; i < HM_HDRK_PERLEN && row[i]; i++) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < HM_HDRK_PERLEN && row[i]; i++) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 1347 0 1347
for (i = 0; i < HM_HDRK_PERLEN && row[i]; i++) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 1226 121 1347
2085 1226 int idx = row[i] - 1;
2086 1226 ▶ if (memcmp(keybuf, hm_hdrk_name[idx], klen) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (memcmp(keybuf, hm_hdrk_name[idx], klen) == 0) 919 307 1226
2087 919 return hm_hdrk_sv[idx];
2088 }
2089 121 return NULL;
2090 }
2091  
2092 /* The two bytes a repeated request header folds with. PSGI joins with the
2093 * comma of a list header (RFC 9110 5.3). Cookie is the one request header
2094 * whose list is "; " (RFC 6265 4.2.1), and an HTTP/2 client may send each
2095 * cookie as its own field (RFC 9113 8.2.3), which browsers do: folded with
2096 * a comma the session cookie's value grows a tail and its signature fails
2097 * on every request. The same fold serves HTTP/1.1, where a client that
2098 * splits Cookie is out of spec but the app is still owed one value. */
2099 1 static const char *hm_hdr_join_sep(const char *keybuf, size_t klen) {
2100 1 ▶ return (klen == 11 && memcmp(keybuf, "HTTP_COOKIE", 11) == 0) ? "; " : ", "; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
return (klen == 11 && memcmp(keybuf, "HTTP_COOKIE", 11) == 0) ? "; " : ", "; /* # uncoverable condition right count:2 class:ignore_covered_err */ 0 1 1
return (klen == 11 && memcmp(keybuf, "HTTP_COOKIE", 11) == 0) ? "; " : ", "; /* # uncoverable condition right count:2 class:ignore_covered_err */ 0 0 0
2101 }
2102  
2103 879 static void hm_env_init(pTHX) {
2104 int i;
2105 AV *ver;
2106 879 ▶ if (hm_env_key[0]) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_env_key[0]) return; 792 87 879
2107 2523 ▶ for (i = 0; i < HMK_COUNT; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < HMK_COUNT; i++) 2436 87 2523
2108 2436 hm_env_key[i] = newSVpvn_share(hm_env_key_name[i],
2109 strlen(hm_env_key_name[i]), 0);
2110 87 hm_env_zero = newSViv(0); SvREADONLY_on(hm_env_zero);
2111 87 hm_env_one = newSViv(1); SvREADONLY_on(hm_env_one);
2112 87 ver = newAV();
2113 87 av_push(ver, newSViv(1)); av_push(ver, newSViv(1));
2114 87 SvREADONLY_on((SV *)ver);
2115 87 hm_env_version = newRV_noinc((SV *)ver); SvREADONLY_on(hm_env_version);
2116 87 hm_env_errors = newRV_inc((SV *)PL_stderrgv); SvREADONLY_on(hm_env_errors);
2117  
2118 2088 ▶ for (i = 0; hm_hdrk_name[i]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; hm_hdrk_name[i]; i++) { 2001 87 2088
2119 2001 size_t l = strlen(hm_hdrk_name[i]);
2120 int j;
2121 2001 hm_hdrk_sv[i] = newSVpvn_share(hm_hdrk_name[i], (I32)l, 0);
2122 /*
2123 # uncoverable branch false class:ignore_covered_err
2124 # uncoverable condition right count:1 class:ignore_covered_err */
2125 3480 ▶ for (j = 0; j < HM_HDRK_PERLEN; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < HM_HDRK_PERLEN; j++) { 3480 0 3480
2126 3480 ▶ if (!hm_hdrk_by_len[l][j]) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_hdrk_by_len[l][j]) { 2001 1479 3480
2127 2001 hm_hdrk_by_len[l][j] = (unsigned char)(i + 1);
2128 2001 break;
2129 }
2130 }
2131 }
2132 }
2133  
2134 #define hm_env_store(env, k, val) \
2135 (void)hv_store_ent((env), hm_env_key[(k)], (val), 0)
2136  
2137 /* Build a full PSGI env from the request line, the header lines indexed by
2138 * idx (from hm_parse_index) and, if present, the request body. Sets
2139 * c->keepalive from the request. */
2140 879 static HV *hm_build_env(pTHX_ char *head, size_t headlen,
2141 const char *body, long clen, hm_conn *c,
2142 const hm_hline *idx, int nlines) {
2143 879 HV *env = newHV();
2144 879 hm_env_init(aTHX);
2145  
2146 /* A fresh HV starts with 8 buckets and this function stores 25-odd keys
2147 * before the app adds its own, so left alone every request pays two
2148 * bucket-split reallocs (8 -> 16 -> 32) plus the rehash walk each one
2149 * does. Ask for the final size up front. 64 rather than 32: a typical
2150 * browser request carries a dozen HTTP_* headers on top of ours, and
2151 * middleware adds more. */
2152 879 hv_ksplit(env, 64);
2153  
2154 /* request line */
2155 879 char *line_end = (char *)memchr(head, '\r', headlen);
2156 879 ▶ size_t ll = line_end ? (size_t)(line_end - head) : headlen;
Branch: 1 branch
BranchTrueFalseTotal
size_t ll = line_end ? (size_t)(line_end - head) : headlen; 641 238 879
2157 879 char *sp1 = (char *)memchr(head, ' ', ll);
2158 879 const char *method = head; STRLEN mlen = ll;
2159 879 const char *uri = "/"; STRLEN ulen = 1;
2160 879 const char *proto = "HTTP/1.0"; STRLEN plen = 8;
2161 /*
2162 # uncoverable branch false class:ignore_covered_err
2163 # uncoverable condition right count:1 class:ignore_covered_err */
2164 879 ▶ if (sp1) {
Branch: 1 branch
BranchTrueFalseTotal
if (sp1) { 879 0 879
2165 879 mlen = (STRLEN)(sp1 - head);
2166 879 char *u = sp1 + 1;
2167 879 char *sp2 = (char *)memchr(u, ' ', ll - (u - head));
2168 /*
2169 # uncoverable branch false
2170 # uncoverable condition right count:1 class:ignore_covered_err */
2171 879 ▶ if (sp2) {
Branch: 1 branch
BranchTrueFalseTotal
if (sp2) { 879 0 879
2172 879 uri = u; ulen = (STRLEN)(sp2 - u);
2173 879 proto = sp2 + 1; plen = (STRLEN)((head + ll) - (sp2 + 1));
2174 0 } else { uri = u; ulen = (STRLEN)((head + ll) - u); } /* # uncoverable statement class:ignore_covered_err */
2175 }
2176 879 const char *qmark = (const char *)memchr(uri, '?', ulen);
2177 879 const char *path = uri; STRLEN path_l = ulen;
2178 879 const char *qs = ""; STRLEN qs_l = 0;
2179 879 ▶ if (qmark) { path_l = (STRLEN)(qmark - uri); qs = qmark + 1; qs_l = ulen - path_l - 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (qmark) { path_l = (STRLEN)(qmark - uri); qs = qmark + 1; qs_l = ulen - path_l - 1; } 13 866 879
2180  
2181 879 hm_env_store(env, HMK_REQUEST_METHOD, newSVpvn(method, mlen));
2182 879 hm_env_store(env, HMK_REQUEST_URI, newSVpvn(uri, ulen));
2183 879 hm_env_store(env, HMK_PATH_INFO, hm_pct_decode(aTHX_ path, path_l));
2184 879 hm_env_store(env, HMK_QUERY_STRING, newSVpvn(qs, qs_l));
2185 879 hm_env_store(env, HMK_SERVER_PROTOCOL, newSVpvn(proto, plen));
2186 879 hm_env_store(env, HMK_SCRIPT_NAME, newSVpvs(""));
2187 879 ▶ c->is_head = (mlen == 4 && memcmp(method, "HEAD", 4) == 0);
Branch: 2 branches
BranchTrueFalseTotal
c->is_head = (mlen == 4 && memcmp(method, "HEAD", 4) == 0); 36 843 879
c->is_head = (mlen == 4 && memcmp(method, "HEAD", 4) == 0); 4 32 36
2188 879 ▶ if (!c->sname_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->sname_sv) { 812 67 879
2189 /*
2190 # uncoverable condition right count:1 class:ignore_covered_err
2191 # uncoverable condition right count:2 class:ignore_covered_err */
2192 812 ▶ c->sname_sv = newSVpv(c->lst && c->lst->host ? c->lst->host : "0.0.0.0", 0);
Branch: 2 branches
BranchTrueFalseTotal
c->sname_sv = newSVpv(c->lst && c->lst->host ? c->lst->host : "0.0.0.0", 0); 812 0 812
c->sname_sv = newSVpv(c->lst && c->lst->host ? c->lst->host : "0.0.0.0", 0); 812 0 812
2193 812 ▶ c->sport_sv = newSViv(c->lst ? c->lst->port : 0); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
c->sport_sv = newSViv(c->lst ? c->lst->port : 0); /* # uncoverable condition right count:1 class:ignore_covered_err */ 812 0 812
2194 }
2195 /* Copies, not the cached SVs themselves. `$env->{REMOTE_ADDR} = $ip`
2196 * - which is what a reverse-proxy middleware does - assigns INTO the
2197 * value SV, and a shared one would then carry the forwarded address
2198 * into every later request on this keep-alive connection, before any
2199 * middleware had run on them. newSVsv shares the buffer copy-on-write
2200 * on perls that can, so the copy costs an SV head and no string. */
2201 879 hm_env_store(env, HMK_SERVER_NAME, newSVsv(c->sname_sv));
2202 879 hm_env_store(env, HMK_SERVER_PORT, newSVsv(c->sport_sv));
2203 879 ▶ if (c->peer[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer[0]) { 877 2 879
2204 877 ▶ if (!c->peer_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->peer_sv) { 810 67 877
2205 810 c->peer_sv = newSVpv(c->peer, 0);
2206 810 c->peer_host_sv = newSVpv(c->peer, 0);
2207 }
2208 877 hm_env_store(env, HMK_REMOTE_ADDR, newSVsv(c->peer_sv));
2209 877 hm_env_store(env, HMK_REMOTE_HOST, newSVsv(c->peer_host_sv));
2210 }
2211 879 ▶ if (c->peer_port) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_port) { 877 2 879
2212 877 ▶ if (!c->peer_port_sv) c->peer_port_sv = newSViv(c->peer_port);
Branch: 1 branch
BranchTrueFalseTotal
if (!c->peer_port_sv) c->peer_port_sv = newSViv(c->peer_port); 810 67 877
2213 877 hm_env_store(env, HMK_REMOTE_PORT, newSVsv(c->peer_port_sv));
2214 }
2215 /* Per-request copies, not the shared read-only SVs: an assignment into
2216 * the slot writes INTO the SV there, and Plack::Middleware::BufferedStreaming
2217 * does `$env->{'psgi.streaming'} = 1`, which died "Modification of a
2218 * read-only value" and made every request a 500 under it. The version
2219 * copy is a fresh RV onto the one read-only array. */
2220 879 hm_env_store(env, HMK_PSGI_VERSION, newSVsv(hm_env_version));
2221 879 ▶ hm_env_store(env, HMK_PSGI_URL_SCHEME,
Branch: 1 branch
BranchTrueFalseTotal
hm_env_store(env, HMK_PSGI_URL_SCHEME, 47 832 879
2222 c->ssl ? newSVpvs("https") : newSVpvs("http"));
2223 879 hm_env_store(env, HMK_PSGI_MULTITHREAD, newSViv(0));
2224 879 hm_env_store(env, HMK_PSGI_MULTIPROCESS, newSViv(1));
2225 879 hm_env_store(env, HMK_PSGI_RUN_ONCE, newSViv(0));
2226 879 hm_env_store(env, HMK_PSGI_STREAMING, newSViv(1));
2227 879 hm_env_store(env, HMK_PSGI_NONBLOCKING, newSViv(1));
2228 /* A copy: `$env->{'psgi.errors'} = $fh` is an assignment INTO the slot's
2229 * SV, and the shared one is read-only, so an application redirecting
2230 * its errors died with "Modification of a read-only value". */
2231 879 hm_env_store(env, HMK_PSGI_ERRORS, newSVsv(hm_env_errors));
2232 879 ▶ if (c->loop->log_wants_t0) /* %D / %T in the log format */
Branch: 1 branch
BranchTrueFalseTotal
if (c->loop->log_wants_t0) /* %D / %T in the log format */ 53 826 879
2233 53 (void)hv_stores(env, "psgix.request_start", newSVnv((NV)hm_now_ns() / 1e9));
2234  
2235 /* psgix.loop: this worker's loop, so apps/clients can create loop
2236 * Futures; psgix.io: the client socket, dup'd so an app that
2237 * hijacks it keeps the socket alive after we close our fd. */
2238 879 hm_env_store(env, HMK_PSGIX_LOOP, hm_loop_to_sv(aTHX_ c->loop));
2239 879 ▶ if (!c->io_sv) c->io_sv = hm_fh_for_fd(aTHX_ c->fd);
Branch: 1 branch
BranchTrueFalseTotal
if (!c->io_sv) c->io_sv = hm_fh_for_fd(aTHX_ c->fd); 812 67 879
2240 879 hm_env_store(env, HMK_PSGIX_IO, SvREFCNT_inc(c->io_sv));
2241 /* psgix.hyperman.conn: [fd, generation id] - the ticket an app hands
2242 * back to Hyperman::detach (or the ABI's conn_detach) to take this
2243 * socket over for a protocol upgrade. HTTP/1 only; the generation id
2244 * makes a stale ticket a no-op rather than a wrong-connection hit. */
2245 879 ▶ if (!c->cid_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->cid_sv) { 812 67 879
2246 812 AV *cid = newAV();
2247 812 av_extend(cid, 2);
2248 812 av_store(cid, 0, newSViv(c->fd));
2249 812 av_store(cid, 1, newSVuv(c->id));
2250 /* The third element is the stream id, and -1 is "the whole
2251 * connection is the stream" - which is what HTTP/1.1 is. It rides on
2252 * the same cached arrayref rather than a second one, so
2253 * psgix.hyperman.stream costs a store and not an allocation. */
2254 812 av_store(cid, 2, newSViv(-1));
2255 812 c->cid_sv = newRV_noinc((SV *)cid);
2256 }
2257 879 hm_env_store(env, HMK_PSGIX_HM_CONN, SvREFCNT_inc(c->cid_sv));
2258 879 hm_env_store(env, HMK_PSGIX_HM_STREAM, SvREFCNT_inc(c->cid_sv));
2259 879 ▶ if (c->proxy_addr[0]) /* the address that connected */
Branch: 1 branch
BranchTrueFalseTotal
if (c->proxy_addr[0]) /* the address that connected */ 10 869 879
2260 10 hm_env_store(env, HMK_PSGIX_PROXY_ADDR, newSVpv(c->proxy_addr, 0));
2261 879 ▶ if (c->ssl) hm_tls_env(aTHX_ c, env);
Branch: 1 branch
BranchTrueFalseTotal
if (c->ssl) hm_tls_env(aTHX_ c, env); 47 832 879
2262  
2263 879 ▶ c->keepalive = (plen == 8 && memcmp(proto, "HTTP/1.1", 8) == 0); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
c->keepalive = (plen == 8 && memcmp(proto, "HTTP/1.1", 8) == 0); /* # uncoverable condition right count:1 class:ignore_covered_err */ 879 0 879
c->keepalive = (plen == 8 && memcmp(proto, "HTTP/1.1", 8) == 0); /* # uncoverable condition right count:1 class:ignore_covered_err */ 367 512 879
2264 879 c->req_11 = c->keepalive; /* before Connection: close can clear it */
2265 /* Per request, not per connection: a keep-alive connection may send a
2266 * different Accept-Encoding on its next request, and the response path
2267 * has no env to read by the time it needs this. One bit, set below. */
2268 879 c->accepts_gzip = 0;
2269  
2270 /* header lines, from the framing pass's index (no rescan) */
2271 char keybuf[300];
2272 879 int have_cl = 0;
2273 int li;
2274 1964 ▶ for (li = 0; li < nlines; li++) {
Branch: 1 branch
BranchTrueFalseTotal
for (li = 0; li < nlines; li++) { 1085 879 1964
2275 1085 const char *p = head + idx[li].off;
2276 1085 size_t nk = idx[li].klen;
2277 1085 const char *vp = head + idx[li].voff;
2278 1085 size_t nv = idx[li].vlen;
2279  
2280 /*
2281 # uncoverable branch true
2282 # uncoverable condition left count:1 class:ignore_covered_err */
2283 1085 ▶ if (nk + 5 >= sizeof(keybuf)) continue; /* absurd name: not a header
Branch: 1 branch
BranchTrueFalseTotal
if (nk + 5 >= sizeof(keybuf)) continue; /* absurd name: not a header 0 1085 1085
2284 we would have stored before
2285 either */
2286 /* Fold to the canonical HTTP_ form first, then every name test below
2287 * is a memcmp on known-case bytes rather than a strncasecmp on the
2288 * wire bytes - three case-blind scans per header gone. The fold maps
2289 * '-' to '_', which would let a literal "Content_Length" alias the
2290 * real thing, so the special names also check the wire byte at the
2291 * hyphen position, exactly as the old raw-name compare required. */
2292 {
2293 size_t i;
2294 1085 int underscore = 0;
2295 1085 memcpy(keybuf, "HTTP_", 5);
2296 7975 ▶ for (i = 0; i < nk; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nk; i++) { 6890 1085 7975
2297 6890 unsigned char ch = (unsigned char)p[i];
2298 6890 ▶ if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */ 5136 1754 6890
if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */ 5136 0 5136
2299 1754 ▶ else if (ch == '-') ch = '_';
Branch: 1 branch
BranchTrueFalseTotal
else if (ch == '-') ch = '_'; 266 1488 1754
2300 1488 ▶ else if (ch == '_') underscore = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (ch == '_') underscore = 1; 3 1485 1488
2301 6890 keybuf[5 + i] = (char)ch;
2302 }
2303 /* A wire name with an underscore folds to the same env key as
2304 * the hyphenated name, so "X_Forwarded_For" would land in
2305 * HTTP_X_FORWARDED_FOR beside - or instead of - the header a
2306 * proxy in front vetted. Proxies strip the hyphenated form and
2307 * pass the underscored one untouched, which is the whole
2308 * attack. Dropped, as nginx and Apache do. */
2309 1085 ▶ if (underscore) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (underscore) continue; 2 1083 1085
2310 }
2311 /* Accept-Encoding is answered on this one pass and remembered as a
2312 * bit on the connection: hm_queue_response has no env to consult by
2313 * the time it must decide. Not an arm of the chain below - the
2314 * header is still stored as HTTP_ACCEPT_ENCODING like any other. */
2315 /*
2316 # uncoverable condition right count:2 class:ignore_covered_err
2317 # uncoverable condition right count:3 class:ignore_covered_err
2318 # uncoverable condition right count:4 class:ignore_covered_err */
2319 1083 ▶ if (nk == 15 && p[6] == '-' && c->loop->compress
Branch: 3 branches
BranchTrueFalseTotal
if (nk == 15 && p[6] == '-' && c->loop->compress 17 1066 1083
if (nk == 15 && p[6] == '-' && c->loop->compress 17 0 17
if (nk == 15 && p[6] == '-' && c->loop->compress 17 0 17
2320 17 ▶ && memEQ(keybuf + 5, "ACCEPT_ENCODING", 15))
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(keybuf + 5, "ACCEPT_ENCODING", 15)) 17 0 17
2321 17 c->accepts_gzip = (unsigned char)hz_accepts_gzip(vp, nv);
2322  
2323 1083 ▶ if (nk == 14 && p[7] == '-' && memEQ(keybuf + 5, "CONTENT_LENGTH", 14)) { /* # uncoverable condition right count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (nk == 14 && p[7] == '-' && memEQ(keybuf + 5, "CONTENT_LENGTH", 14)) { /* # uncoverable condition right count:3 class:ignore_covered_err */ 22 1061 1083
if (nk == 14 && p[7] == '-' && memEQ(keybuf + 5, "CONTENT_LENGTH", 14)) { /* # uncoverable condition right count:3 class:ignore_covered_err */ 22 0 22
if (nk == 14 && p[7] == '-' && memEQ(keybuf + 5, "CONTENT_LENGTH", 14)) { /* # uncoverable condition right count:3 class:ignore_covered_err */ 22 0 22
2324 22 hm_env_store(env, HMK_CONTENT_LENGTH, newSVpvn(vp, nv));
2325 22 have_cl = 1;
2326 1061 ▶ } else if (nk == 12 && p[7] == '-' /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
} else if (nk == 12 && p[7] == '-' /* # uncoverable condition right count:2 class:ignore_covered_err */ 48 1013 1061
} else if (nk == 12 && p[7] == '-' /* # uncoverable condition right count:2 class:ignore_covered_err */ 48 0 48
2327 48 ▶ && memEQ(keybuf + 5, "CONTENT_TYPE", 12)) {
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(keybuf + 5, "CONTENT_TYPE", 12)) { 11 37 48
2328 11 hm_env_store(env, HMK_CONTENT_TYPE, newSVpvn(vp, nv));
2329 /*
2330 # uncoverable condition right count:2 class:ignore_covered_err
2331 # uncoverable condition right count:3 class:ignore_covered_err */
2332 1050 ▶ } else if (nk == 17 && p[8] == '-'
Branch: 2 branches
BranchTrueFalseTotal
} else if (nk == 17 && p[8] == '-' 10 1040 1050
} else if (nk == 17 && p[8] == '-' 10 0 10
2333 10 ▶ && memEQ(keybuf + 5, "TRANSFER_ENCODING", 17)) {
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(keybuf + 5, "TRANSFER_ENCODING", 17)) { 10 0 10
2334 /* consumed by framing (already dechunked); not exposed to the
2335 * app, whose psgi.input is the decoded body with CONTENT_LENGTH */
2336 } else {
2337 {
2338 /* repeated header: join values (hm_hdr_join_sep) */
2339 1040 SV *ksv = hm_hdrk_lookup(keybuf, nk + 5);
2340 1040 ▶ if (ksv) {
Branch: 1 branch
BranchTrueFalseTotal
if (ksv) { 919 121 1040
2341 /* a common header: the shared key SV carries its hash
2342 * and its HEK, so no hashing and no HEK churn */
2343 919 HE *he = hv_fetch_ent(env, ksv, 0, 0);
2344 919 ▶ if (he) {
Branch: 1 branch
BranchTrueFalseTotal
if (he) { 0 919 919
2345 0 sv_catpvn(HeVAL(he), hm_hdr_join_sep(keybuf, nk + 5), 2);
2346 0 sv_catpvn(HeVAL(he), vp, nv);
2347 } else {
2348 919 (void)hv_store_ent(env, ksv, newSVpvn(vp, nv), 0);
2349 }
2350 } else {
2351 121 SV **old = hv_fetch(env, keybuf, (I32)(nk + 5), 0);
2352 121 ▶ if (old) {
Branch: 1 branch
BranchTrueFalseTotal
if (old) { 1 120 121
2353 1 sv_catpvn(*old, hm_hdr_join_sep(keybuf, nk + 5), 2);
2354 1 sv_catpvn(*old, vp, nv);
2355 } else {
2356 120 hv_store(env, keybuf, (I32)(nk + 5), newSVpvn(vp, nv), 0);
2357 }
2358 }
2359 }
2360 /* the name is already canonical; only the value keeps wire case */
2361 1040 ▶ if (nk == 10 && memEQ(keybuf + 5, "CONNECTION", 10)) {
Branch: 2 branches
BranchTrueFalseTotal
if (nk == 10 && memEQ(keybuf + 5, "CONNECTION", 10)) { 243 797 1040
if (nk == 10 && memEQ(keybuf + 5, "CONNECTION", 10)) { 185 58 243
2362 185 ▶ if (nv >= 5 && hm_strncasecmp(vp, "close", 5) == 0) c->keepalive = 0; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (nv >= 5 && hm_strncasecmp(vp, "close", 5) == 0) c->keepalive = 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 185 0 185
if (nv >= 5 && hm_strncasecmp(vp, "close", 5) == 0) c->keepalive = 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 176 9 185
2363 /*
2364 # uncoverable branch true class:ignore_covered_err
2365 # uncoverable condition left count:1 class:ignore_covered_err
2366 # uncoverable condition left count:2 class:ignore_covered_err */
2367 9 ▶ else if (nv >= 10 && hm_strncasecmp(vp, "keep-alive", 10) == 0) c->keepalive = 1;
Branch: 2 branches
BranchTrueFalseTotal
else if (nv >= 10 && hm_strncasecmp(vp, "keep-alive", 10) == 0) c->keepalive = 1; 0 9 9
else if (nv >= 10 && hm_strncasecmp(vp, "keep-alive", 10) == 0) c->keepalive = 1; 0 0 0
2368 }
2369 }
2370 }
2371 /* dechunked request: no Content-Length header, but we know the decoded
2372 * length - present it so apps/middleware see the real body size */
2373 879 ▶ if (!have_cl && clen > 0)
Branch: 2 branches
BranchTrueFalseTotal
if (!have_cl && clen > 0) 857 22 879
if (!have_cl && clen > 0) 10 847 857
2374 10 hm_env_store(env, HMK_CONTENT_LENGTH, newSViv((IV)clen));
2375  
2376 883 ▶ if (c && c->spill_fd >= 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c && c->spill_fd >= 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 879 0 879
if (c && c->spill_fd >= 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 4 875 879
2377 /* The body was drained to a file as it arrived, so there is no body
2378 * pointer to copy from: the descriptor IS psgi.input. The handle owns
2379 * it from here, and the connection stops tracking it. */
2380 4 SV *in = hm_input_from_fd(aTHX_ c->spill_fd);
2381 4 c->spill_fd = -1;
2382 4 c->spill_got = 0;
2383 4 ▶ hm_env_store(env, HMK_PSGI_INPUT,
Branch: 1 branch
BranchTrueFalseTotal
hm_env_store(env, HMK_PSGI_INPUT, 0 4 4
2384 in ? in : hm_empty_input_sv(aTHX));
2385 }
2386 875 ▶ else if (clen > 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (clen > 0) 27 848 875
2387 27 hm_env_store(env, HMK_PSGI_INPUT, hm_new_input(aTHX_ body, (STRLEN)clen));
2388 else
2389 848 hm_env_store(env, HMK_PSGI_INPUT, hm_empty_input_sv(aTHX));
2390 879 hm_env_store(env, HMK_PSGIX_INPUT_BUFFERED, SvREFCNT_inc(hm_env_one));
2391  
2392 879 return env;
2393 }
2394  
2395 /* ---- app invocation ------------------------------------------------------ */
2396  
2397 /* Call the app with an env we keep alive (access_log needs it afterwards). */
2398 170 static SV *hm_call_app(pTHX_ hm_loop *loop, SV *env_rv) {
2399 170 dSP;
2400 170 SV *resp = NULL;
2401 int count;
2402 170 ENTER; SAVETMPS;
2403 170 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 170 170
2404 170 ▶ XPUSHs(sv_2mortal(SvREFCNT_inc(env_rv)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(SvREFCNT_inc(env_rv))); 0 170 170
2405 170 PUTBACK;
2406 170 count = call_sv(loop->app, G_SCALAR | G_EVAL);
2407 170 SPAGAIN;
2408 170 ▶ if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 170 0 170
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 169 1 170
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 169 0 169
2409 169 resp = POPs;
2410 169 SvREFCNT_inc(resp);
2411 /*
2412 # uncoverable branch false class:ignore_covered_err
2413 # uncoverable condition right count:1 class:ignore_covered_err */
2414 1 ▶ } else if (count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (count > 0) { 1 0 1
2415 1 (void)POPs;
2416 }
2417 170 hm_warn_died(aTHX_ "application");
2418 170 PUTBACK;
2419 170 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 170 0 170
2420 170 return resp;
2421 }
2422  
2423 /* No-logger fast path: the env is handed to the call and freed with it. */
2424 708 static SV *hm_call_app0(pTHX_ hm_loop *loop, HV *env) {
2425 708 dSP;
2426 708 SV *resp = NULL;
2427 int count;
2428 708 ENTER; SAVETMPS;
2429 708 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 708 708
2430 708 ▶ XPUSHs(sv_2mortal(newRV_noinc((SV *)env)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newRV_noinc((SV *)env))); 0 708 708
2431 708 PUTBACK;
2432 708 count = call_sv(loop->app, G_SCALAR | G_EVAL);
2433 708 SPAGAIN;
2434 708 ▶ if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 708 0 708
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 706 2 708
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 706 0 706
2435 706 resp = POPs;
2436 706 SvREFCNT_inc(resp);
2437 /*
2438 # uncoverable branch false class:ignore_covered_err
2439 # uncoverable condition right count:1 class:ignore_covered_err */
2440 2 ▶ } else if (count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (count > 0) { 2 0 2
2441 2 (void)POPs;
2442 }
2443 708 hm_warn_died(aTHX_ "application");
2444 708 PUTBACK;
2445 708 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 708 0 708
2446 708 return resp;
2447 }
2448  
2449 /* Is any access logging configured for this loop? Guards the (small) cost of
2450 * keeping the env alive past the response purely for the logger. */
2451 #define hm_logging(loop) ((loop)->log_cb || (loop)->log_fd >= 0)
2452  
2453 /* ---- fast default access-log writer (Combined Log Format) ----------------
2454 * When access_log is a path/handle rather than a coderef, log lines are
2455 * formatted and buffered in C and flushed once per loop wakeup - no Perl
2456 * call on the hot path. The fd is shared (inherited) across workers and
2457 * opened O_APPEND, so whole-line writes stay atomic between them. */
2458  
2459 #define HM_LOG_FLUSH_AT (32 * 1024) /* flush the buffer once it grows past */
2460  
2461 73 static void hm_log_flush(hm_loop *loop) {
2462 73 size_t off = 0;
2463 73 ▶ if (loop->log_fd < 0 || loop->log_len == 0) return; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (loop->log_fd < 0 || loop->log_len == 0) return; /* # uncoverable condition left count:1 class:ignore_covered_err */ 73 0 73
if (loop->log_fd < 0 || loop->log_len == 0) return; /* # uncoverable condition left count:1 class:ignore_covered_err */ 8 65 73
2464 130 ▶ while (off < loop->log_len) {
Branch: 1 branch
BranchTrueFalseTotal
while (off < loop->log_len) { 65 65 130
2465 65 ssize_t n = hm_os_write_file(loop->log_fd, loop->log_buf + off,
2466 loop->log_len - off);
2467 /*
2468 # uncoverable branch false
2469 # uncoverable condition right count:1 class:ignore_covered_err */
2470 65 ▶ if (n > 0) { off += (size_t)n; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { off += (size_t)n; continue; } 65 0 65
2471 /*
2472 # uncoverable statement
2473 # uncoverable branch true
2474 # uncoverable branch false
2475 # uncoverable condition left count:1
2476 # uncoverable condition right count:1
2477 # uncoverable condition left count:2
2478 # uncoverable condition right count:2 */
2479 0 ▶ if (n < 0 && errno == EINTR) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0 && errno == EINTR) continue; 0 0 0
if (n < 0 && errno == EINTR) continue; 0 0 0
2480 0 break; /* EAGAIN/error: keep the unwritten tail for the next flush */ /* # uncoverable statement */
2481 }
2482 /*
2483 # uncoverable branch true class:ignore_covered_err
2484 # uncoverable condition left count:1 class:ignore_covered_err
2485 # uncoverable condition right count:1 class:ignore_covered_err
2486 # uncoverable condition left count:2 class:ignore_covered_err */
2487 65 ▶ if (off && off < loop->log_len)
Branch: 2 branches
BranchTrueFalseTotal
if (off && off < loop->log_len) 65 0 65
if (off && off < loop->log_len) 0 65 65
2488 0 memmove(loop->log_buf, loop->log_buf + off, loop->log_len - off); /* # uncoverable statement */
2489 65 loop->log_len -= off;
2490 }
2491  
2492 1509 static void hm_log_raw(hm_loop *loop, const char *p, size_t n) {
2493 1509 ▶ if (loop->log_len + n > loop->log_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_len + n > loop->log_cap) { 8 1501 1509
2494 8 ▶ size_t ncap = loop->log_cap ? loop->log_cap : 8192; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
size_t ncap = loop->log_cap ? loop->log_cap : 8192; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 8 8
2495 /*
2496 # uncoverable branch true class:ignore_covered_err
2497 # uncoverable condition left count:1 class:ignore_covered_err */
2498 8 ▶ while (ncap < loop->log_len + n) ncap *= 2;
Branch: 1 branch
BranchTrueFalseTotal
while (ncap < loop->log_len + n) ncap *= 2; 0 8 8
2499 8 loop->log_buf = (char *)hm_xrealloc(loop->log_buf, ncap);
2500 8 loop->log_cap = ncap;
2501 }
2502 1509 memcpy(loop->log_buf + loop->log_len, p, n);
2503 1509 loop->log_len += n;
2504 1509 }
2505  
2506 /* A plain token: '-' when empty (CLF uses '-' for missing fields). */
2507 /*
2508 # uncoverable statement
2509 # uncoverable subroutine */
2510 0 static void hm_log_tok(hm_loop *loop, const char *p, size_t n) {
2511 /*
2512 # uncoverable statement
2513 # uncoverable branch true
2514 # uncoverable branch false
2515 # uncoverable condition left count:1
2516 # uncoverable condition right count:1
2517 # uncoverable condition left count:2
2518 # uncoverable condition right count:2 */
2519 0 ▶ if (!p || n == 0) { hm_log_raw(loop, "-", 1); return; }
Branch: 2 branches
BranchTrueFalseTotal
if (!p || n == 0) { hm_log_raw(loop, "-", 1); return; } 0 0 0
if (!p || n == 0) { hm_log_raw(loop, "-", 1); return; } 0 0 0
2520 0 hm_log_raw(loop, p, n); /* # uncoverable statement */
2521 }
2522  
2523 /* A value going inside "quotes": escape ", \ and control bytes \xHH so a
2524 * hostile URI or User-Agent cannot forge or split a log line. */
2525 80 static void hm_log_quoted(hm_loop *loop, const char *p, size_t n) {
2526 static const char hex[] = "0123456789abcdef";
2527 80 size_t i, run = 0;
2528 /*
2529 # uncoverable branch true
2530 # uncoverable condition left count:1 class:ignore_covered_err */
2531 80 ▶ if (!p) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return; 0 80 80
2532 690 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 610 80 690
2533 610 unsigned char ch = (unsigned char)p[i];
2534 /*
2535 # uncoverable condition left count:3 class:ignore_covered_err */
2536 615 ▶ if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) {
Branch: 4 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 607 3 610
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 606 1 607
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 606 0 606
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 1 605 606
2537 char e[4];
2538 /*
2539 # uncoverable branch false class:ignore_covered_err
2540 # uncoverable condition right count:1 class:ignore_covered_err */
2541 5 ▶ if (run) { hm_log_raw(loop, p + i - run, run); run = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (run) { hm_log_raw(loop, p + i - run, run); run = 0; } 5 0 5
2542 5 ▶ if (ch == '"' || ch == '\\') {
Branch: 2 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\') { 2 3 5
if (ch == '"' || ch == '\\') { 1 1 2
2543 4 e[0] = '\\'; e[1] = (char)ch; hm_log_raw(loop, e, 2);
2544 } else {
2545 1 e[0] = '\\'; e[1] = 'x'; e[2] = hex[ch >> 4]; e[3] = hex[ch & 0xf];
2546 1 hm_log_raw(loop, e, 4);
2547 }
2548 } else {
2549 605 run++;
2550 }
2551 }
2552 80 ▶ if (run) hm_log_raw(loop, p + n - run, run);
Branch: 1 branch
BranchTrueFalseTotal
if (run) hm_log_raw(loop, p + n - run, run); 79 1 80
2553 }
2554  
2555 /* The Date header (RFC 9110 6.6.1, IMF-fixdate), recomputed at most once a
2556 * second. Formatted by hand: strftime's %a and %b follow the locale, and
2557 * the wire wants English. 37 bytes, always: "Date: " + 29 + CRLF. */
2558 #define HM_DATE_LEN 37
2559 865 static const char *hm_date_header(hm_loop *loop) {
2560 865 ▶ if (loop->now != loop->date_sec) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->now != loop->date_sec) { 110 755 865
2561 static const char days[] = "SunMonTueWedThuFriSat";
2562 static const char mons[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2563 struct tm tm;
2564 110 time_t t = loop->now;
2565 110 char *d = loop->date_hdr;
2566 /*
2567 # uncoverable branch true
2568 # uncoverable condition left count:1 class:ignore_covered_err */
2569 110 ▶ if (!hm_gmtime_r(&t, &tm)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_gmtime_r(&t, &tm)) return NULL; 0 110 110
2570 110 memcpy(d, "Date: ", 6); d += 6;
2571 110 memcpy(d, days + tm.tm_wday * 3, 3); d += 3;
2572 110 *d++ = ','; *d++ = ' ';
2573 110 *d++ = (char)('0' + tm.tm_mday / 10); *d++ = (char)('0' + tm.tm_mday % 10);
2574 110 *d++ = ' ';
2575 110 memcpy(d, mons + tm.tm_mon * 3, 3); d += 3;
2576 110 *d++ = ' ';
2577 {
2578 110 int y = tm.tm_year + 1900;
2579 110 *d++ = (char)('0' + y / 1000 % 10); *d++ = (char)('0' + y / 100 % 10);
2580 110 *d++ = (char)('0' + y / 10 % 10); *d++ = (char)('0' + y % 10);
2581 }
2582 110 *d++ = ' ';
2583 110 *d++ = (char)('0' + tm.tm_hour / 10); *d++ = (char)('0' + tm.tm_hour % 10);
2584 110 *d++ = ':';
2585 110 *d++ = (char)('0' + tm.tm_min / 10); *d++ = (char)('0' + tm.tm_min % 10);
2586 110 *d++ = ':';
2587 110 *d++ = (char)('0' + tm.tm_sec / 10); *d++ = (char)('0' + tm.tm_sec % 10);
2588 110 memcpy(d, " GMT\r\n", 6);
2589 110 loop->date_sec = loop->now;
2590 }
2591 865 return loop->date_hdr;
2592 }
2593  
2594 /* Does an app-supplied header name or value carry a byte that would end
2595 * the field early? A CR, LF or NUL in either splits the response, so a
2596 * response carrying one is refused as a 500 rather than serialised: the
2597 * server is the last place the bug can be caught. */
2598 1874 static int hm_hdr_bytes_ok(const char *p, STRLEN n) {
2599 /*
2600 # uncoverable condition right count:2 class:ignore_covered_err
2601 # uncoverable condition right count:3 class:ignore_covered_err */
2602 1874 ▶ return !memchr(p, '\r', n) && !memchr(p, '\n', n) && !memchr(p, '\0', n);
Branch: 3 branches
BranchTrueFalseTotal
return !memchr(p, '\r', n) && !memchr(p, '\n', n) && !memchr(p, '\0', n); 1872 2 1874
return !memchr(p, '\r', n) && !memchr(p, '\n', n) && !memchr(p, '\0', n); 1872 0 1872
return !memchr(p, '\r', n) && !memchr(p, '\n', n) && !memchr(p, '\0', n); 1872 0 1872
2603 }
2604 869 static int hm_headers_ok(pTHX_ AV *hav) {
2605 SSize_t i, hn;
2606 /*
2607 # uncoverable branch true
2608 # uncoverable condition left count:1 class:ignore_covered_err */
2609 869 ▶ if (!hav) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!hav) return 1; 0 869 869
2610 869 hn = av_len(hav) + 1;
2611 2743 ▶ for (i = 0; i < hn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hn; i++) { 1876 867 2743
2612 1876 SV **e = av_fetch(hav, i, 0);
2613 STRLEN l;
2614 const char *p;
2615 1876 ▶ if (!e || !*e) continue; /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !*e) continue; /* # uncoverable condition left count:2 class:ignore_covered_err */ 1874 2 1876
if (!e || !*e) continue; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 1874 1874
2616 1874 p = SvPV(*e, l);
2617 1874 ▶ if (!hm_hdr_bytes_ok(p, l)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_hdr_bytes_ok(p, l)) return 0; 2 1872 1874
2618 }
2619 867 return 1;
2620 }
2621  
2622 /* The same escape, for a value inside a JSON string. */
2623 /* The length of a well-formed UTF-8 sequence starting at p (2..4), or 0 for
2624 * a byte that does not start one. Overlongs, surrogates and > U+10FFFF
2625 * are 0 too: the point is that what passes through is valid JSON text. */
2626 19 static size_t hm_utf8_seq(const unsigned char *p, size_t n) {
2627 19 unsigned char c = p[0];
2628 size_t len, i;
2629 19 ▶ if (c >= 0xc2 && c <= 0xdf) len = 2;
Branch: 2 branches
BranchTrueFalseTotal
if (c >= 0xc2 && c <= 0xdf) len = 2; 8 11 19
if (c >= 0xc2 && c <= 0xdf) len = 2; 2 6 8
2630 17 ▶ else if (c >= 0xe0 && c <= 0xef) len = 3;
Branch: 2 branches
BranchTrueFalseTotal
else if (c >= 0xe0 && c <= 0xef) len = 3; 6 11 17
else if (c >= 0xe0 && c <= 0xef) len = 3; 3 3 6
2631 14 ▶ else if (c >= 0xf0 && c <= 0xf4) len = 4; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
else if (c >= 0xf0 && c <= 0xf4) len = 4; /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 11 14
else if (c >= 0xf0 && c <= 0xf4) len = 4; /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 0 3
2632 11 else return 0;
2633 8 ▶ if (n < len) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n < len) return 0; 1 7 8
2634 /*
2635 # uncoverable branch true class:ignore_covered_err
2636 # uncoverable condition left count:1 class:ignore_covered_err */
2637 23 ▶ for (i = 1; i < len; i++) if ((p[i] & 0xc0) != 0x80) return 0;
Branch: 2 branches
BranchTrueFalseTotal
for (i = 1; i < len; i++) if ((p[i] & 0xc0) != 0x80) return 0; 0 16 16
for (i = 1; i < len; i++) if ((p[i] & 0xc0) != 0x80) return 0; 16 7 23
2638 7 ▶ if (len == 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (len == 3) { 3 4 7
2639 3 ▶ if (c == 0xe0 && p[1] < 0xa0) return 0; /* overlong */ /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c == 0xe0 && p[1] < 0xa0) return 0; /* overlong */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 2 3
if (c == 0xe0 && p[1] < 0xa0) return 0; /* overlong */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
2640 2 ▶ if (c == 0xed && p[1] >= 0xa0) return 0; /* surrogate */ /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c == 0xed && p[1] >= 0xa0) return 0; /* surrogate */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 1 2
if (c == 0xed && p[1] >= 0xa0) return 0; /* surrogate */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
2641 4 ▶ } else if (len == 4) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (len == 4) { 3 1 4
2642 3 ▶ if (c == 0xf0 && p[1] < 0x90) return 0; /* overlong */
Branch: 2 branches
BranchTrueFalseTotal
if (c == 0xf0 && p[1] < 0x90) return 0; /* overlong */ 2 1 3
if (c == 0xf0 && p[1] < 0x90) return 0; /* overlong */ 1 1 2
2643 2 ▶ if (c == 0xf4 && p[1] >= 0x90) return 0; /* > 10FFFF */ /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c == 0xf4 && p[1] >= 0x90) return 0; /* > 10FFFF */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 1 2
if (c == 0xf4 && p[1] >= 0x90) return 0; /* > 10FFFF */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
2644 }
2645 3 return len;
2646 }
2647  
2648 195 static void hm_log_json_esc(hm_loop *loop, const char *p, size_t n) {
2649 static const char hex[] = "0123456789abcdef";
2650 195 size_t i, run = 0;
2651 /*
2652 # uncoverable branch true
2653 # uncoverable condition left count:1 class:ignore_covered_err */
2654 195 ▶ if (!p) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return; 0 195 195
2655 1559 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 1364 195 1559
2656 1364 unsigned char ch = (unsigned char)p[i];
2657 1364 ▶ if (ch >= 0x80) {
Branch: 1 branch
BranchTrueFalseTotal
if (ch >= 0x80) { 19 1345 1364
2658 /* Valid UTF-8 passes; a stray high byte (a URI or User-Agent
2659 * that is not UTF-8) is escaped, so the line stays valid JSON
2660 * and a strict pipeline does not drop it - which was a way to
2661 * keep one's requests out of the log. */
2662 19 size_t sl = hm_utf8_seq((const unsigned char *)p + i, n - i);
2663 19 ▶ if (sl) { run += sl; i += sl - 1; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (sl) { run += sl; i += sl - 1; continue; } 3 16 19
2664 }
2665 1382 ▶ if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) {
Branch: 4 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 1358 3 1361
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 1357 1 1358
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 1356 1 1357
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 16 1340 1356
2666 char e[6];
2667 21 ▶ if (run) { hm_log_raw(loop, p + i - run, run); run = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (run) { hm_log_raw(loop, p + i - run, run); run = 0; } 11 10 21
2668 21 ▶ if (ch == '"' || ch == '\\') {
Branch: 2 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\') { 18 3 21
if (ch == '"' || ch == '\\') { 1 17 18
2669 4 e[0] = '\\'; e[1] = (char)ch; hm_log_raw(loop, e, 2);
2670 } else {
2671 17 e[0] = '\\'; e[1] = 'u'; e[2] = '0'; e[3] = '0';
2672 17 e[4] = hex[ch >> 4]; e[5] = hex[ch & 0xf];
2673 17 hm_log_raw(loop, e, 6);
2674 }
2675 } else {
2676 1340 run++;
2677 }
2678 }
2679 195 ▶ if (run) hm_log_raw(loop, p + n - run, run);
Branch: 1 branch
BranchTrueFalseTotal
if (run) hm_log_raw(loop, p + n - run, run); 194 1 195
2680 }
2681  
2682 /* A value from $env, escaped the way this log's format wants. */
2683 275 static void hm_log_esc(hm_loop *loop, const char *p, size_t n) {
2684 275 ▶ if (loop->log_json) hm_log_json_esc(loop, p, n);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_json) hm_log_json_esc(loop, p, n); 195 80 275
2685 80 else hm_log_quoted(loop, p, n);
2686 275 }
2687  
2688 /* Cached apache-style timestamp, recomputed at most once per second. */
2689 14 static const char *hm_log_time(hm_loop *loop) {
2690 14 ▶ if (loop->now != loop->log_ts_sec) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->now != loop->log_ts_sec) { 4 10 14
2691 struct tm tm;
2692 4 time_t t = loop->now;
2693 4 hm_localtime_r(&t, &tm);
2694 4 strftime(loop->log_ts, sizeof(loop->log_ts), "%d/%b/%Y:%H:%M:%S %z", &tm);
2695 4 loop->log_ts_sec = loop->now;
2696 }
2697 14 return loop->log_ts;
2698 }
2699  
2700 /* The ISO 8601 stamp the JSON format carries, cached the same way. */
2701 48 static const char *hm_log_time_iso(hm_loop *loop) {
2702 48 ▶ if (loop->now != loop->log_iso_sec) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->now != loop->log_iso_sec) { 3 45 48
2703 struct tm tm;
2704 3 time_t t = loop->now;
2705 3 hm_localtime_r(&t, &tm);
2706 3 strftime(loop->log_iso, sizeof(loop->log_iso), "%Y-%m-%dT%H:%M:%S%z", &tm);
2707 3 loop->log_iso_sec = loop->now;
2708 }
2709 48 return loop->log_iso;
2710 }
2711  
2712 /* ---- the access-log format compiler ----------------------------------------
2713 * Apache's directives, the ones a PSGI server can honour:
2714 * %h %a REMOTE_ADDR %l "-" %u REMOTE_USER %t [time]
2715 * %r request line %s %>s status %b bytes or "-" %B bytes or 0
2716 * %D microseconds %T seconds %p SERVER_PORT %m METHOD
2717 * %U PATH_INFO %q ?query %H SERVER_PROTOCOL %v SERVER_NAME
2718 * %P pid %{Name}i request header %{Name}e any $env key
2719 * %% a literal percent sign
2720 * Returns 0, or -1 with the offending directive in err. Every value is
2721 * escaped (CLF or JSON), so no directive is a way to forge a line. */
2722 #define HM_LOG_COMBINED "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""
2723  
2724 1624 static void hm_logtok_push(hm_logtok **toks, int *n, int *cap, hm_logtok t) {
2725 1624 ▶ if (*n == *cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (*n == *cap) { 179 1445 1624
2726 179 ▶ *cap = *cap ? *cap * 2 : 16;
Branch: 1 branch
BranchTrueFalseTotal
*cap = *cap ? *cap * 2 : 16; 89 90 179
2727 179 *toks = (hm_logtok *)hm_xrealloc(*toks, (size_t)*cap * sizeof(hm_logtok));
2728 }
2729 1624 (*toks)[(*n)++] = t;
2730 1624 }
2731 906 static void hm_logtok_lit(hm_logtok **toks, int *n, int *cap, const char *p, size_t l) {
2732 hm_logtok t;
2733 907 ▶ if (!l) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!l) return; 92 814 906
2734 814 ▶ if (*n && (*toks)[*n - 1].kind == HM_LT_LIT) { /* extend the last run */
Branch: 2 branches
BranchTrueFalseTotal
if (*n && (*toks)[*n - 1].kind == HM_LT_LIT) { /* extend the last run */ 811 3 814
if (*n && (*toks)[*n - 1].kind == HM_LT_LIT) { /* extend the last run */ 1 810 811
2735 1 hm_logtok *last = &(*toks)[*n - 1];
2736 1 last->lit = (char *)hm_xrealloc(last->lit, last->litlen + l);
2737 1 memcpy(last->lit + last->litlen, p, l);
2738 1 last->litlen += l;
2739 1 return;
2740 }
2741 813 t.kind = HM_LT_LIT; t.lit = (char *)hm_xmalloc(l); memcpy(t.lit, p, l);
2742 813 t.litlen = l; t.key = NULL;
2743 813 hm_logtok_push(toks, n, cap, t);
2744 }
2745 368 static void hm_logtok_env(pTHX_ hm_logtok **toks, int *n, int *cap,
2746 const char *key, size_t klen) {
2747 hm_logtok t;
2748 368 t.kind = HM_LT_ENV; t.lit = NULL; t.litlen = 0;
2749 368 t.key = newSVpvn_share(key, (I32)klen, 0); /* hash computed once */
2750 368 hm_logtok_push(toks, n, cap, t);
2751 368 }
2752 443 static void hm_logtok_kind(hm_logtok **toks, int *n, int *cap, int kind) {
2753 hm_logtok t;
2754 443 t.kind = kind; t.lit = NULL; t.litlen = 0; t.key = NULL;
2755 443 hm_logtok_push(toks, n, cap, t);
2756 443 }
2757  
2758 90 static int hm_logfmt_compile(pTHX_ const char *fmt, hm_logtok **out, int *nout,
2759 int *wants_t0, char *err, size_t errlen) {
2760 90 hm_logtok *toks = NULL;
2761 90 int n = 0, cap = 0;
2762 90 const char *p = fmt, *lit = fmt;
2763 90 *wants_t0 = 0;
2764 2070 ▶ while (*p) {
Branch: 1 branch
BranchTrueFalseTotal
while (*p) { 1984 86 2070
2765 char d;
2766 1984 ▶ if (*p != '%') { p++; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (*p != '%') { p++; continue; } 1201 783 1984
2767 783 hm_logtok_lit(&toks, &n, &cap, lit, (size_t)(p - lit));
2768 783 p++;
2769 783 ▶ if (*p == '>') p++; /* %>s is %s */
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '>') p++; /* %>s is %s */ 86 697 783
2770 783 ▶ if (*p == '{') {
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '{') { 175 608 783
2771 175 const char *name = p + 1, *end = strchr(name, '}');
2772 char key[300];
2773 size_t nl, i;
2774 175 ▶ if (!end || (end[1] != 'i' && end[1] != 'e')) {
Branch: 3 branches
BranchTrueFalseTotal
if (!end || (end[1] != 'i' && end[1] != 'e')) { 174 1 175
if (!end || (end[1] != 'i' && end[1] != 'e')) { 2 172 174
if (!end || (end[1] != 'i' && end[1] != 'e')) { 1 1 2
2775 2 ▶ snprintf(err, errlen, "%%{...}%c", end ? end[1] : '?');
Branch: 1 branch
BranchTrueFalseTotal
snprintf(err, errlen, "%%{...}%c", end ? end[1] : '?'); 1 1 2
2776 3 goto bad;
2777 }
2778 173 nl = (size_t)(end - name);
2779 173 ▶ if (nl == 0 || nl + 6 > sizeof(key)) { snprintf(err, errlen, "%%{%.*s}", (int)nl, name); goto bad; } /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (nl == 0 || nl + 6 > sizeof(key)) { snprintf(err, errlen, "%%{%.*s}", (int)nl, name); goto bad; } /* # uncoverable condition left count:2 class:ignore_covered_err */ 172 1 173
if (nl == 0 || nl + 6 > sizeof(key)) { snprintf(err, errlen, "%%{%.*s}", (int)nl, name); goto bad; } /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 172 172
2780 172 ▶ if (end[1] == 'i') {
Branch: 1 branch
BranchTrueFalseTotal
if (end[1] == 'i') { 171 1 172
2781 171 memcpy(key, "HTTP_", 5);
2782 1624 ▶ for (i = 0; i < nl; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nl; i++) { 1453 171 1624
2783 1453 unsigned char ch = (unsigned char)name[i];
2784 1453 ▶ if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1108 345 1453
if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1108 0 1108
2785 345 ▶ else if (ch == '-') ch = '_';
Branch: 1 branch
BranchTrueFalseTotal
else if (ch == '-') ch = '_'; 87 258 345
2786 1453 key[5 + i] = (char)ch;
2787 }
2788 171 hm_logtok_env(aTHX_ &toks, &n, &cap, key, nl + 5);
2789 } else {
2790 1 hm_logtok_env(aTHX_ &toks, &n, &cap, name, nl);
2791 }
2792 172 p = end + 2;
2793 172 lit = p;
2794 172 continue;
2795 }
2796 608 d = *p;
2797 /*
2798 # uncoverable branch true count:11 class:ignore_covered_err
2799 # uncoverable branch true count:12 class:ignore_covered_err */
2800 608 switch (d) {
2801 1 case '%': hm_logtok_lit(&toks, &n, &cap, "%", 1); break;
2802 87 case 'h': case 'a': hm_logtok_env(aTHX_ &toks, &n, &cap, "REMOTE_ADDR", 11); break;
2803 84 case 'l': hm_logtok_kind(&toks, &n, &cap, HM_LT_DASH); break;
2804 84 case 'u': hm_logtok_env(aTHX_ &toks, &n, &cap, "REMOTE_USER", 11); break;
2805 84 case 't': hm_logtok_kind(&toks, &n, &cap, HM_LT_TIME); break;
2806 84 case 'r': hm_logtok_kind(&toks, &n, &cap, HM_LT_REQLINE); break;
2807 86 case 's': hm_logtok_kind(&toks, &n, &cap, HM_LT_STATUS); break;
2808 86 case 'b': hm_logtok_kind(&toks, &n, &cap, HM_LT_BYTES); break;
2809 1 case 'B': hm_logtok_kind(&toks, &n, &cap, HM_LT_BYTES0); break;
2810 2 case 'D': hm_logtok_kind(&toks, &n, &cap, HM_LT_DUR_US); *wants_t0 = 1; break;
2811 1 case 'T': hm_logtok_kind(&toks, &n, &cap, HM_LT_DUR_S); *wants_t0 = 1; break;
2812 0 case 'p': hm_logtok_env(aTHX_ &toks, &n, &cap, "SERVER_PORT", 11); break; /* # uncoverable statement */
2813 1 case 'm': hm_logtok_env(aTHX_ &toks, &n, &cap, "REQUEST_METHOD", 14); break;
2814 1 case 'U': hm_logtok_env(aTHX_ &toks, &n, &cap, "PATH_INFO", 9); break;
2815 1 case 'q': hm_logtok_kind(&toks, &n, &cap, HM_LT_QUERY); break;
2816 1 case 'H': hm_logtok_env(aTHX_ &toks, &n, &cap, "SERVER_PROTOCOL", 15); break;
2817 1 case 'v': hm_logtok_env(aTHX_ &toks, &n, &cap, "SERVER_NAME", 11); break;
2818 2 case 'P': hm_logtok_kind(&toks, &n, &cap, HM_LT_PID); break;
2819 1 default:
2820 1 ▶ snprintf(err, errlen, "%%%c", d ? d : '?'); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
snprintf(err, errlen, "%%%c", d ? d : '?'); /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 0 1
2821 1 goto bad;
2822 }
2823 607 p++;
2824 607 lit = p;
2825 }
2826 86 hm_logtok_lit(&toks, &n, &cap, lit, (size_t)(p - lit));
2827 86 *out = toks; *nout = n;
2828 86 return 0;
2829 4 bad:
2830 {
2831 int i;
2832 6 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 2 4 6
2833 2 ▶ if (toks[i].lit) free(toks[i].lit);
Branch: 1 branch
BranchTrueFalseTotal
if (toks[i].lit) free(toks[i].lit); 1 1 2
2834 2 ▶ if (toks[i].key) SvREFCNT_dec(toks[i].key);
Branch: 1 branch
BranchTrueFalseTotal
if (toks[i].key) SvREFCNT_dec(toks[i].key); 1 1 2
2835 }
2836 4 ▶ if (toks) free(toks);
Branch: 1 branch
BranchTrueFalseTotal
if (toks) free(toks); 1 3 4
2837 }
2838 4 return -1;
2839 }
2840  
2841 /* The JSON shape: one object per line, fixed keys, numbers unquoted. */
2842 3 static void hm_logfmt_json(pTHX_ hm_logtok **out, int *nout) {
2843 3 hm_logtok *toks = NULL;
2844 3 int n = 0, cap = 0;
2845 #define HM_JL(s) hm_logtok_lit(&toks, &n, &cap, s, sizeof(s) - 1)
2846 #define HM_JE(k) hm_logtok_env(aTHX_ &toks, &n, &cap, k, sizeof(k) - 1)
2847 3 HM_JL("{\"time\":\""); hm_logtok_kind(&toks, &n, &cap, HM_LT_TIME_ISO);
2848 3 HM_JL("\",\"remote_addr\":\""); HM_JE("REMOTE_ADDR");
2849 3 HM_JL("\",\"user\":\""); HM_JE("REMOTE_USER");
2850 3 HM_JL("\",\"method\":\""); HM_JE("REQUEST_METHOD");
2851 3 HM_JL("\",\"uri\":\""); HM_JE("REQUEST_URI");
2852 3 HM_JL("\",\"protocol\":\""); HM_JE("SERVER_PROTOCOL");
2853 3 HM_JL("\",\"status\":"); hm_logtok_kind(&toks, &n, &cap, HM_LT_STATUS);
2854 3 HM_JL(",\"bytes\":"); hm_logtok_kind(&toks, &n, &cap, HM_LT_BYTES);
2855 3 HM_JL(",\"referer\":\""); HM_JE("HTTP_REFERER");
2856 3 HM_JL("\",\"user_agent\":\""); HM_JE("HTTP_USER_AGENT");
2857 3 HM_JL("\",\"duration_us\":"); hm_logtok_kind(&toks, &n, &cap, HM_LT_DUR_US);
2858 3 HM_JL("}");
2859 #undef HM_JL
2860 #undef HM_JE
2861 3 *out = toks; *nout = n;
2862 3 }
2863  
2864 46 static const char *hm_env_str(pTHX_ HV *env, const char *key, I32 klen, STRLEN *lenp) {
2865 46 SV **s = hv_fetch(env, key, klen, 0);
2866 /*
2867 # uncoverable branch false class:ignore_covered_err
2868 # uncoverable condition right count:1 class:ignore_covered_err
2869 # uncoverable condition right count:2 class:ignore_covered_err
2870 # uncoverable condition right count:3 class:ignore_covered_err */
2871 92 ▶ if (s && *s && SvOK(*s)) return SvPV(*s, *lenp);
Branch: 3 branches
BranchTrueFalseTotal
if (s && *s && SvOK(*s)) return SvPV(*s, *lenp); 46 0 46
if (s && *s && SvOK(*s)) return SvPV(*s, *lenp); 46 0 46
if (s && *s && SvOK(*s)) return SvPV(*s, *lenp); 46 0 46
2872 0 *lenp = 0; /* # uncoverable statement */
2873 0 return NULL; /* # uncoverable statement */
2874 }
2875  
2876 /* One $env value into the line, escaped; the "absent" spelling differs
2877 * between the two shapes ("-" in CLF, an empty string in JSON). */
2878 417 static void hm_log_env_val(pTHX_ hm_loop *loop, HV *env, const hm_logtok *t) {
2879 417 HE *he = hv_fetch_ent(env, t->key, 0, 0);
2880 417 ▶ SV *v = he ? HeVAL(he) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *v = he ? HeVAL(he) : NULL; 232 185 417
2881 417 ▶ if (v && SvOK(v)) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (v && SvOK(v)) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 232 185 417
if (v && SvOK(v)) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 232 0 232
2882 STRLEN n;
2883 232 const char *s = SvPV(v, n);
2884 /*
2885 # uncoverable branch false
2886 # uncoverable condition right count:1 class:ignore_covered_err */
2887 232 ▶ if (n) { hm_log_esc(loop, s, n); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (n) { hm_log_esc(loop, s, n); return; } 232 0 232
2888 }
2889 185 ▶ if (!loop->log_json) hm_log_raw(loop, "-", 1);
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->log_json) hm_log_raw(loop, "-", 1); 44 141 185
2890 }
2891  
2892 /* Build one access-log line into the loop's log buffer by walking the
2893 * compiled format. The default compiles to Combined:
2894 * host - user [time] "METHOD URI PROTO" status bytes "referer" "ua" */
2895 67 static void hm_log_line(pTHX_ hm_loop *loop, SV *env_rv, int status, ssize_t blen) {
2896 HV *env;
2897 char num[32];
2898 int ln, i;
2899  
2900 /*
2901 # uncoverable branch true class:ignore_covered_err
2902 # uncoverable condition left count:1 class:ignore_covered_err
2903 # uncoverable condition left count:2 class:ignore_covered_err
2904 # uncoverable condition left count:3 class:ignore_covered_err */
2905 67 ▶ if (!(env_rv && SvROK(env_rv) && SvTYPE(SvRV(env_rv)) == SVt_PVHV)) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!(env_rv && SvROK(env_rv) && SvTYPE(SvRV(env_rv)) == SVt_PVHV)) return; 67 0 67
if (!(env_rv && SvROK(env_rv) && SvTYPE(SvRV(env_rv)) == SVt_PVHV)) return; 67 0 67
if (!(env_rv && SvROK(env_rv) && SvTYPE(SvRV(env_rv)) == SVt_PVHV)) return; 0 67 67
2906 67 env = (HV *)SvRV(env_rv);
2907  
2908 1526 ▶ for (i = 0; i < loop->nlogtok; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlogtok; i++) { 1459 67 1526
2909 1459 const hm_logtok *t = &loop->logtok[i];
2910 1459 switch (t->kind) { /* # uncoverable branch true count:13 class:ignore_covered_err */
2911 752 case HM_LT_LIT: hm_log_raw(loop, t->lit, t->litlen); break;
2912 417 case HM_LT_ENV: hm_log_env_val(aTHX_ loop, env, t); break;
2913 14 case HM_LT_DASH: hm_log_raw(loop, "-", 1); break;
2914 67 case HM_LT_STATUS:
2915 67 ln = (int)hm_itoa(num, (long)status); hm_log_raw(loop, num, (size_t)ln);
2916 67 break;
2917 67 case HM_LT_BYTES:
2918 67 ▶ if (blen >= 0) { ln = (int)hm_utoa(num, (unsigned long)blen);
Branch: 1 branch
BranchTrueFalseTotal
if (blen >= 0) { ln = (int)hm_utoa(num, (unsigned long)blen); 55 12 67
2919 55 hm_log_raw(loop, num, (size_t)ln); }
2920 12 ▶ else if (loop->log_json) hm_log_raw(loop, "null", 4);
Branch: 1 branch
BranchTrueFalseTotal
else if (loop->log_json) hm_log_raw(loop, "null", 4); 7 5 12
2921 5 else hm_log_raw(loop, "-", 1);
2922 67 break;
2923 3 case HM_LT_BYTES0:
2924 3 ln = (int)hm_utoa(num, blen >= 0 ? (unsigned long)blen : 0UL);
2925 3 hm_log_raw(loop, num, (size_t)ln);
2926 3 break;
2927 14 case HM_LT_TIME: {
2928 14 const char *ts = hm_log_time(loop);
2929 14 hm_log_raw(loop, "[", 1); hm_log_raw(loop, ts, strlen(ts)); hm_log_raw(loop, "]", 1);
2930 14 break;
2931 }
2932 48 case HM_LT_TIME_ISO: {
2933 48 const char *ts = hm_log_time_iso(loop);
2934 48 hm_log_raw(loop, ts, strlen(ts));
2935 48 break;
2936 }
2937 14 case HM_LT_REQLINE: {
2938 const char *s; STRLEN n;
2939 14 s = hm_env_str(aTHX_ env, "REQUEST_METHOD", 14, &n);
2940 /*
2941 # uncoverable condition right count:1 class:ignore_covered_err
2942 # uncoverable condition right count:2 class:ignore_covered_err */
2943 14 ▶ if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1);
Branch: 2 branches
BranchTrueFalseTotal
if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1); 14 0 14
if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1); 14 0 14
2944 14 hm_log_raw(loop, " ", 1);
2945 14 s = hm_env_str(aTHX_ env, "REQUEST_URI", 11, &n);
2946 /*
2947 # uncoverable condition right count:1 class:ignore_covered_err
2948 # uncoverable condition right count:2 class:ignore_covered_err */
2949 14 ▶ if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1);
Branch: 2 branches
BranchTrueFalseTotal
if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1); 14 0 14
if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1); 14 0 14
2950 14 hm_log_raw(loop, " ", 1);
2951 14 s = hm_env_str(aTHX_ env, "SERVER_PROTOCOL", 15, &n);
2952 /*
2953 # uncoverable condition right count:1 class:ignore_covered_err
2954 # uncoverable condition right count:2 class:ignore_covered_err */
2955 14 ▶ if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1);
Branch: 2 branches
BranchTrueFalseTotal
if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1); 14 0 14
if (s && n) hm_log_esc(loop, s, n); else hm_log_raw(loop, "-", 1); 14 0 14
2956 14 break;
2957 }
2958 2 case HM_LT_QUERY: {
2959 const char *s; STRLEN n;
2960 2 s = hm_env_str(aTHX_ env, "QUERY_STRING", 12, &n);
2961 2 ▶ if (s && n) { hm_log_raw(loop, "?", 1); hm_log_esc(loop, s, n); } /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (s && n) { hm_log_raw(loop, "?", 1); hm_log_esc(loop, s, n); } /* # uncoverable condition right count:1 class:ignore_covered_err */ 2 0 2
if (s && n) { hm_log_raw(loop, "?", 1); hm_log_esc(loop, s, n); } /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 1 2
2962 2 break;
2963 }
2964 5 case HM_LT_PID:
2965 5 ln = (int)hm_itoa(num, (long)hm_os_getpid()); hm_log_raw(loop, num, (size_t)ln);
2966 5 break;
2967 56 case HM_LT_DUR_US:
2968 case HM_LT_DUR_S: {
2969 56 SV **t0 = hv_fetch(env, "psgix.request_start", 19, 0);
2970 /*
2971 # uncoverable branch false class:ignore_covered_err
2972 # uncoverable condition right count:1 class:ignore_covered_err
2973 # uncoverable condition right count:2 class:ignore_covered_err
2974 # uncoverable condition right count:3 class:ignore_covered_err */
2975 112 ▶ if (t0 && *t0 && SvOK(*t0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (t0 && *t0 && SvOK(*t0)) { 56 0 56
if (t0 && *t0 && SvOK(*t0)) { 56 0 56
if (t0 && *t0 && SvOK(*t0)) { 56 0 56
2976 56 double el = (double)hm_now_ns() / 1e9 - SvNV(*t0);
2977 56 unsigned long v = el < 0 ? 0UL
2978 56 ▶ : (unsigned long)(t->kind == HM_LT_DUR_US ? el * 1e6 : el); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
: (unsigned long)(t->kind == HM_LT_DUR_US ? el * 1e6 : el); /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 56 56
: (unsigned long)(t->kind == HM_LT_DUR_US ? el * 1e6 : el); /* # uncoverable condition left count:1 class:ignore_covered_err */ 53 3 56
2979 56 ln = (int)hm_utoa(num, v); hm_log_raw(loop, num, (size_t)ln);
2980 }
2981 /*
2982 # uncoverable statement
2983 # uncoverable branch true
2984 # uncoverable branch false
2985 # uncoverable condition left count:1
2986 # uncoverable condition right count:1 */
2987 0 ▶ else if (loop->log_json) hm_log_raw(loop, "null", 4);
Branch: 1 branch
BranchTrueFalseTotal
else if (loop->log_json) hm_log_raw(loop, "null", 4); 0 0 0
2988 0 else hm_log_raw(loop, "-", 1); /* # uncoverable statement */
2989 56 break;
2990 }
2991 }
2992 }
2993 67 hm_log_raw(loop, "\n", 1);
2994  
2995 /*
2996 # uncoverable branch true class:ignore_covered_err
2997 # uncoverable condition left count:1 class:ignore_covered_err */
2998 67 ▶ if (loop->log_len >= HM_LOG_FLUSH_AT) hm_log_flush(loop);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_len >= HM_LOG_FLUSH_AT) hm_log_flush(loop); 0 67 67
2999 }
3000  
3001 /* Record one response. Fast path: format in C to the access-log fd. Else, if
3002 * a coderef was given, call $cb->($env, $status, $bytes); errors in the logger
3003 * are swallowed so they cannot take the loop down. */
3004 170 static void hm_access_log(pTHX_ hm_loop *loop, SV *env_rv, int status, ssize_t blen) {
3005 170 dSP;
3006 170 ▶ if (loop->log_fd >= 0) { hm_log_line(aTHX_ loop, env_rv, status, blen); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_fd >= 0) { hm_log_line(aTHX_ loop, env_rv, status, blen); return; } 67 103 170
3007 /*
3008 # uncoverable branch true
3009 # uncoverable condition left count:1 class:ignore_covered_err */
3010 103 ▶ if (!loop->log_cb) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->log_cb) return; 0 103 103
3011 103 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 103 103
3012 103 ▶ XPUSHs(env_rv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(env_rv); 0 103 103
3013 103 ▶ XPUSHs(sv_2mortal(newSViv(status)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSViv(status))); 0 103 103
3014 /*
3015 # uncoverable condition left count:1 class:ignore_covered_err
3016 # uncoverable condition right count:2 class:ignore_covered_err */
3017 103 ▶ XPUSHs(blen >= 0 ? sv_2mortal(newSViv((IV)blen)) : &PL_sv_undef);
Branch: 2 branches
BranchTrueFalseTotal
XPUSHs(blen >= 0 ? sv_2mortal(newSViv((IV)blen)) : &PL_sv_undef); 0 103 103
XPUSHs(blen >= 0 ? sv_2mortal(newSViv((IV)blen)) : &PL_sv_undef); 103 0 103
3018 103 PUTBACK;
3019 103 call_sv(loop->log_cb, G_DISCARD | G_EVAL);
3020 103 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 103 0 103
3021 }
3022  
3023 /* ---- response serialization ---------------------------------------------- */
3024  
3025 /* Reusable per-connection write buffer: keep capacity across requests so the
3026 * steady-state response path does no malloc/free. */
3027 9988 static void hm_wb_reserve(hm_conn *c, size_t need) {
3028 9988 ▶ if (c->wlen + need > c->wcap) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->wlen + need > c->wcap) { 142 9846 9988
3029 142 ▶ size_t ncap = c->wcap ? c->wcap : 4096;
Branch: 1 branch
BranchTrueFalseTotal
size_t ncap = c->wcap ? c->wcap : 4096; 19 123 142
3030 208 ▶ while (ncap < c->wlen + need) ncap *= 2;
Branch: 1 branch
BranchTrueFalseTotal
while (ncap < c->wlen + need) ncap *= 2; 66 142 208
3031 142 c->wbuf = (char *)hm_xrealloc(c->wbuf, ncap);
3032 142 c->wcap = ncap;
3033 }
3034 9988 }
3035 9987 static void hm_wb_put(hm_conn *c, const char *p, size_t n) {
3036 9987 hm_wb_reserve(c, n);
3037 9987 memcpy(c->wbuf + c->wlen, p, n);
3038 9987 c->wlen += n;
3039 9987 }
3040  
3041 static const char HM_ERR500[] =
3042 "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n"
3043 "Content-Length: 21\r\nConnection: close\r\n\r\nInternal Server Error";
3044  
3045 /* Serialize $resp: headers into c->wbuf, then try an immediate writev of
3046 * header + body chunks (zero-copy body). Whatever the kernel doesn't take
3047 * is buffered; a write watcher resumes it (backpressure). Falls back to
3048 * copy-into-buffer when bytes are already queued (pipelining) or the body
3049 * is a filehandle. Returns 0, or -1 if the connection was closed. */
3050 829 static int hm_queue_response(pTHX_ hm_conn *c, SV *resp) {
3051 829 hm_loop *loop = c->loop;
3052 829 AV *rav, *hav = NULL;
3053 SV **s0, **s1, **s2;
3054 829 SV *fh_body = NULL;
3055 829 AV *bav = NULL;
3056 829 int status = 500, has_len = 0, has_conn = 0, has_date = 0;
3057 829 int gz_out = 0;
3058 829 size_t blen = 0;
3059 829 size_t hdr_start = c->wlen;
3060 829 SSize_t bn = 0;
3061 char line[64];
3062 int ln;
3063  
3064 /*
3065 # uncoverable branch true class:ignore_covered_err
3066 # uncoverable condition left count:1 class:ignore_covered_err */
3067 829 ▶ if (loop->stopping) c->keepalive = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stopping) c->keepalive = 0; 0 829 829
3068  
3069 /*
3070 # uncoverable condition left count:2 class:ignore_covered_err
3071 # uncoverable condition left count:3 class:ignore_covered_err */
3072 829 ▶ if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) {
Branch: 3 branches
BranchTrueFalseTotal
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) { 826 3 829
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) { 826 0 826
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) { 0 826 826
3073 3 hm_wb_put(c, HM_ERR500, sizeof(HM_ERR500) - 1);
3074 3 c->keepalive = 0;
3075 3 c->last_status = 500;
3076 3 c->last_blen = 21;
3077 3 return 0;
3078 }
3079 826 rav = (AV *)SvRV(resp);
3080 826 s0 = av_fetch(rav, 0, 0);
3081 826 s1 = av_fetch(rav, 1, 0);
3082 826 s2 = av_fetch(rav, 2, 0);
3083 /*
3084 # uncoverable branch false class:ignore_covered_err
3085 # uncoverable condition right count:1 class:ignore_covered_err
3086 # uncoverable condition right count:2 class:ignore_covered_err */
3087 826 ▶ if (s0 && *s0) status = (int)SvIV(*s0);
Branch: 2 branches
BranchTrueFalseTotal
if (s0 && *s0) status = (int)SvIV(*s0); 826 0 826
if (s0 && *s0) status = (int)SvIV(*s0); 826 0 826
3088 /*
3089 # uncoverable branch false class:ignore_covered_err
3090 # uncoverable condition right count:1 class:ignore_covered_err
3091 # uncoverable condition right count:2 class:ignore_covered_err
3092 # uncoverable condition right count:3 class:ignore_covered_err
3093 # uncoverable condition right count:4 class:ignore_covered_err */
3094 826 ▶ if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1);
Branch: 4 branches
BranchTrueFalseTotal
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 826 0 826
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 826 0 826
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 826 0 826
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 826 0 826
3095 826 ▶ if (!hm_headers_ok(aTHX_ hav)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_headers_ok(aTHX_ hav)) { 1 825 826
3096 1 hm_errlog("Hyperman: response header carries CR, LF or NUL; refused\n");
3097 1 hm_wb_put(c, HM_ERR500, sizeof(HM_ERR500) - 1);
3098 1 c->keepalive = 0;
3099 1 c->last_status = 500;
3100 1 c->last_blen = 21;
3101 1 return 0;
3102 }
3103 /*
3104 # uncoverable branch true class:ignore_covered_err
3105 # uncoverable condition left count:1 class:ignore_covered_err
3106 # uncoverable condition right count:1 class:ignore_covered_err
3107 # uncoverable condition left count:2 class:ignore_covered_err */
3108 825 ▶ if (s2 && !*s2) s2 = NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (s2 && !*s2) s2 = NULL; 825 0 825
if (s2 && !*s2) s2 = NULL; 0 825 825
3109  
3110 /* body length (first pass, no copy) */
3111 /*
3112 # uncoverable condition right count:1 class:ignore_covered_err
3113 # uncoverable condition right count:2 class:ignore_covered_err */
3114 1632 ▶ if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) {
Branch: 3 branches
BranchTrueFalseTotal
if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) { 825 0 825
if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) { 825 0 825
if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) { 807 18 825
3115 SSize_t i;
3116 807 bav = (AV *)SvRV(*s2);
3117 807 bn = av_len(bav) + 1;
3118 1609 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 802 807 1609
3119 802 SV **e = av_fetch(bav, i, 0);
3120 /*
3121 # uncoverable branch false class:ignore_covered_err
3122 # uncoverable condition right count:1 class:ignore_covered_err */
3123 1604 ▶ if (e) { STRLEN l; (void)SvPV(*e, l); blen += l; }
Branch: 1 branch
BranchTrueFalseTotal
if (e) { STRLEN l; (void)SvPV(*e, l); blen += l; } 802 0 802
3124 }
3125 /*
3126 # uncoverable branch false class:ignore_covered_err
3127 # uncoverable condition right count:1 class:ignore_covered_err
3128 # uncoverable condition right count:2 class:ignore_covered_err */
3129 18 ▶ } else if (s2 && SvROK(*s2)) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (s2 && SvROK(*s2)) { 18 0 18
} else if (s2 && SvROK(*s2)) { 18 0 18
3130 /* filehandle or IO::Handle-like body: stream it when it lifts to
3131 * a byte-countable source, else slurp exactly as before */
3132 18 UV clv = 0;
3133 18 int cl_seen = hm_hav_clen(aTHX_ hav, &clv);
3134 18 ▶ if (!c->bsrc.kind && hm_bsrc_lift(aTHX_ *s2, &c->bsrc, cl_seen, clv)) /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!c->bsrc.kind && hm_bsrc_lift(aTHX_ *s2, &c->bsrc, cl_seen, clv)) /* # uncoverable condition right count:1 class:ignore_covered_err */ 18 0 18
if (!c->bsrc.kind && hm_bsrc_lift(aTHX_ *s2, &c->bsrc, cl_seen, clv)) /* # uncoverable condition right count:1 class:ignore_covered_err */ 14 4 18
3135 14 blen = (size_t)c->bsrc.remaining;
3136 else {
3137 4 fh_body = hm_slurp_body(aTHX_ *s2);
3138 4 { STRLEN l; (void)SvPV(fh_body, l); blen = l; }
3139 }
3140 }
3141  
3142 /* ---- compression decision, before a byte of the response is written --
3143 * Cheapest test first, and the whole block is skipped on a server that
3144 * did not ask for it. The rules, in order:
3145 * 1. enabled, and this request accepted gzip
3146 * 2. the response carries NO Content-Encoding. This one rule covers
3147 * every hands-off case at once - a framework's precompressed file
3148 * already says `gzip`, an opted-out route says `identity` (which
3149 * we strip below), and anything else was encoded deliberately.
3150 * 3. a plain in-memory body, not a glob/reader/streamed source:
3151 * compressing those would undo the 0.20 sendfile and drip paths.
3152 * 4. big enough to be worth a gzip member's header and trailer
3153 * 5. a status that carries an entity, and never 206 (a range
3154 * describes offsets into the UNCOMPRESSED representation)
3155 * 6. a compressible media type, from an allowlist */
3156 /*
3157 # uncoverable condition right count:3 class:ignore_covered_err
3158 # uncoverable condition right count:4 class:ignore_covered_err
3159 # uncoverable condition right count:5 class:ignore_covered_err
3160 # uncoverable condition left count:8 class:ignore_covered_err */
3161 825 ▶ if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body
Branch: 5 branches
BranchTrueFalseTotal
if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body 78 747 825
if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body 15 63 78
if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body 15 0 15
if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body 15 0 15
if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body 15 0 15
3162 15 ▶ && blen >= loop->compress_min
Branch: 1 branch
BranchTrueFalseTotal
&& blen >= loop->compress_min 13 2 15
3163 13 ▶ && (status == 200 || status == 203)) {
Branch: 2 branches
BranchTrueFalseTotal
&& (status == 200 || status == 203)) { 1 12 13
&& (status == 200 || status == 203)) { 0 1 1
3164 12 const char *ct = NULL;
3165 12 STRLEN ctl = 0;
3166 12 int enc_seen = 0;
3167 12 ▶ SSize_t i, hn = hav ? av_len(hav) + 1 : 0; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
SSize_t i, hn = hav ? av_len(hav) + 1 : 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 12 0 12
3168 30 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 22 8 30
3169 22 SV **k = av_fetch(hav, i, 0);
3170 STRLEN kl;
3171 const char *ks;
3172 /*
3173 # uncoverable condition left count:1 class:ignore_covered_err
3174 # uncoverable condition left count:2 class:ignore_covered_err */
3175 26 ▶ if (!k || !*k) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!k || !*k) continue; 22 0 22
if (!k || !*k) continue; 0 22 22
3176 22 ks = SvPV(*k, kl);
3177 /* A response that sets a cookie is one a BREACH-style attacker
3178 * would want compressed beside a reflected input; left alone,
3179 * as the no-transform contract for a Set-Cookie response. */
3180 /*
3181 # uncoverable condition right count:2 class:ignore_covered_err
3182 # uncoverable condition right count:3 class:ignore_covered_err */
3183 22 ▶ if (kl == 10 && (ks[0] | 32) == 's'
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 10 && (ks[0] | 32) == 's' 1 21 22
if (kl == 10 && (ks[0] | 32) == 's' 1 0 1
3184 1 ▶ && hm_strncasecmp(ks, "Set-Cookie", 10) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Set-Cookie", 10) == 0) { 1 0 1
3185 1 enc_seen = 1;
3186 4 break;
3187 }
3188 21 ▶ if ((ks[0] | 32) != 'c') continue;
Branch: 1 branch
BranchTrueFalseTotal
if ((ks[0] | 32) != 'c') continue; 4 17 21
3189 17 ▶ if (kl == 16 && hm_strncasecmp(ks, "Content-Encoding", 16) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 16 && hm_strncasecmp(ks, "Content-Encoding", 16) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 14 17
if (kl == 16 && hm_strncasecmp(ks, "Content-Encoding", 16) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 0 3
3190 3 enc_seen = 1;
3191 3 break;
3192 }
3193 14 ▶ if (kl == 12 && hm_strncasecmp(ks, "Content-Type", 12) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 12 && hm_strncasecmp(ks, "Content-Type", 12) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 12 2 14
if (kl == 12 && hm_strncasecmp(ks, "Content-Type", 12) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 12 0 12
3194 12 SV **v = av_fetch(hav, i + 1, 0);
3195 /*
3196 # uncoverable branch false class:ignore_covered_err
3197 # uncoverable condition right count:1 class:ignore_covered_err
3198 # uncoverable condition right count:2 class:ignore_covered_err */
3199 24 ▶ if (v && *v) ct = SvPV(*v, ctl);
Branch: 2 branches
BranchTrueFalseTotal
if (v && *v) ct = SvPV(*v, ctl); 12 0 12
if (v && *v) ct = SvPV(*v, ctl); 12 0 12
3200 }
3201 }
3202 12 ▶ if (!enc_seen && hz_type_ok(ct, ctl)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!enc_seen && hz_type_ok(ct, ctl)) { 8 4 12
if (!enc_seen && hz_type_ok(ct, ctl)) { 7 1 8
3203 /* one contiguous copy of the body, then one deflate */
3204 7 char *flat, *gz = NULL;
3205 7 size_t gzl = 0, off = 0;
3206 SSize_t j;
3207 7 ▶ Newx(flat, blen ? blen : 1, char); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
Newx(flat, blen ? blen : 1, char); /* # uncoverable condition right count:1 class:ignore_covered_err */ 7 0 7
3208 14 ▶ for (j = 0; j < bn; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < bn; j++) { 7 7 14
3209 7 SV **e = av_fetch(bav, j, 0);
3210 /*
3211 # uncoverable branch false class:ignore_covered_err
3212 # uncoverable condition right count:1 class:ignore_covered_err */
3213 7 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 7 0 7
3214 STRLEN l;
3215 7 const char *p = SvPV(*e, l);
3216 /* Bounded by the length the first pass measured: an
3217 * overloaded or tied element whose stringification grew
3218 * between the two calls would otherwise run past flat. */
3219 /*
3220 # uncoverable branch true class:ignore_covered_err
3221 # uncoverable condition left count:1 class:ignore_covered_err */
3222 7 ▶ if (l > blen - off) l = blen - off;
Branch: 1 branch
BranchTrueFalseTotal
if (l > blen - off) l = blen - off; 0 7 7
3223 /*
3224 # uncoverable branch false class:ignore_covered_err
3225 # uncoverable condition right count:1 class:ignore_covered_err */
3226 7 ▶ if (l) { memcpy(flat + off, p, l); off += l; }
Branch: 1 branch
BranchTrueFalseTotal
if (l) { memcpy(flat + off, p, l); off += l; } 7 0 7
3227 }
3228 }
3229 /*
3230 # uncoverable branch false class:ignore_covered_err
3231 # uncoverable condition right count:1 class:ignore_covered_err */
3232 7 ▶ if (hz_gzip(flat, off, loop->compress_level, &gz, &gzl)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hz_gzip(flat, off, loop->compress_level, &gz, &gzl)) { 7 0 7
3233 /* route it down the fh_body path: one SV, one copy into the
3234 * write buffer. A response that just paid a deflate is not
3235 * the one to spend the writev fast path on. */
3236 7 fh_body = newSVpvn(gz, gzl);
3237 7 Safefree(gz);
3238 7 bav = NULL; bn = 0;
3239 7 blen = gzl;
3240 7 c->last_blen = blen;
3241 7 gz_out = 1;
3242 }
3243 7 Safefree(flat);
3244 }
3245 }
3246  
3247 /* status line + headers */
3248 825 c->last_status = status;
3249 825 c->last_blen = blen;
3250 {
3251 size_t sll;
3252 825 const char *sl = hm_status_line(status, &sll, line);
3253 825 hm_wb_put(c, sl, sll);
3254 }
3255 /*
3256 # uncoverable branch false class:ignore_covered_err
3257 # uncoverable condition right count:1 class:ignore_covered_err */
3258 825 ▶ if (hav) {
Branch: 1 branch
BranchTrueFalseTotal
if (hav) { 825 0 825
3259 825 SSize_t i, hn = av_len(hav) + 1;
3260 1708 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 883 825 1708
3261 883 SV **k = av_fetch(hav, i, 0);
3262 883 SV **v = av_fetch(hav, i + 1, 0);
3263 STRLEN kl, vl;
3264 const char *ks, *vs;
3265 /*
3266 # uncoverable condition left count:2 class:ignore_covered_err
3267 # uncoverable condition left count:3 class:ignore_covered_err
3268 # uncoverable condition left count:4 class:ignore_covered_err */
3269 890 ▶ if (!k || !*k || !v || !*v) continue; /* a hole in the array */
Branch: 4 branches
BranchTrueFalseTotal
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 882 1 883
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 882 0 882
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 882 0 882
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 0 882 882
3270 882 ks = SvPV(*k, kl);
3271 882 ▶ vs = SvPV(*v, vl);
Branch: 1 branch
BranchTrueFalseTotal
vs = SvPV(*v, vl); 626 256 882
3272 882 ▶ if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) /* # uncoverable condition right count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) /* # uncoverable condition right count:3 class:ignore_covered_err */ 6 876 882
if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 5 6
if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 0 1
3273 1 has_date = 1;
3274 /* both interesting names start with 'c', so one folded-byte test
3275 * skips the case-blind scans for every other header */
3276 882 ▶ if ((ks[0] | 32) == 'c') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ks[0] | 32) == 'c') { 868 14 882
3277 868 ▶ if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 254 614 868
if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 254 0 254
3278 254 has_len = 1;
3279 /* the app's length describes the bytes we just replaced */
3280 254 ▶ if (gz_out) { has_len = 0; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (gz_out) { has_len = 0; continue; } 2 252 254
3281 }
3282 866 ▶ if (kl == 10 && hm_strncasecmp(ks, "Connection", 10) == 0) has_conn = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 10 && hm_strncasecmp(ks, "Connection", 10) == 0) has_conn = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 865 866
if (kl == 10 && hm_strncasecmp(ks, "Connection", 10) == 0) has_conn = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
3283 /* `identity` is the documented way for anything above to opt
3284 * a response out (see hm_compress.h). It has done its job by
3285 * now; sending it on would be noise. */
3286 /*
3287 # uncoverable condition right count:3 class:ignore_covered_err
3288 # uncoverable condition right count:4 class:ignore_covered_err
3289 # uncoverable condition right count:5 class:ignore_covered_err */
3290 866 ▶ if (kl == 16 && vl == 8 && loop->compress
Branch: 3 branches
BranchTrueFalseTotal
if (kl == 16 && vl == 8 && loop->compress 3 863 866
if (kl == 16 && vl == 8 && loop->compress 2 1 3
if (kl == 16 && vl == 8 && loop->compress 2 0 2
3291 2 ▶ && hm_strncasecmp(ks, "Content-Encoding", 16) == 0
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Content-Encoding", 16) == 0 2 0 2
3292 2 ▶ && hm_strncasecmp(vs, "identity", 8) == 0)
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(vs, "identity", 8) == 0) 2 0 2
3293 2 continue;
3294 }
3295 /* The layer that compressed must be the layer that fixes the
3296 * validator, or a cache serves these bytes to a client that
3297 * asked for none. nginx does the same; it is in the POD because
3298 * an app author will otherwise find it by debugging. */
3299 878 ▶ if (gz_out && kl == 4 && hm_strncasecmp(ks, "ETag", 4) == 0) { /* # uncoverable condition right count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (gz_out && kl == 4 && hm_strncasecmp(ks, "ETag", 4) == 0) { /* # uncoverable condition right count:3 class:ignore_covered_err */ 10 868 878
if (gz_out && kl == 4 && hm_strncasecmp(ks, "ETag", 4) == 0) { /* # uncoverable condition right count:3 class:ignore_covered_err */ 3 7 10
if (gz_out && kl == 4 && hm_strncasecmp(ks, "ETag", 4) == 0) { /* # uncoverable condition right count:3 class:ignore_covered_err */ 3 0 3
3300 3 hm_wb_put(c, ks, kl);
3301 3 hm_wb_put(c, ": ", 2);
3302 /*
3303 # uncoverable condition right count:1 class:ignore_covered_err */
3304 3 ▶ if (vl > 1 && vs[vl - 1] == '"') {
Branch: 2 branches
BranchTrueFalseTotal
if (vl > 1 && vs[vl - 1] == '"') { 3 0 3
if (vl > 1 && vs[vl - 1] == '"') { 2 1 3
3305 2 hm_wb_put(c, vs, vl - 1);
3306 2 hm_wb_put(c, "-gzip\"", 6);
3307 } else {
3308 1 hm_wb_put(c, vs, vl);
3309 1 hm_wb_put(c, "-gzip", 5);
3310 }
3311 3 hm_wb_put(c, "\r\n", 2);
3312 3 continue;
3313 }
3314 875 hm_wb_put(c, ks, kl);
3315 875 hm_wb_put(c, ": ", 2);
3316 875 hm_wb_put(c, vs, vl);
3317 875 hm_wb_put(c, "\r\n", 2);
3318 }
3319 }
3320 825 ▶ if (gz_out) {
Branch: 1 branch
BranchTrueFalseTotal
if (gz_out) { 7 818 825
3321 7 hm_wb_put(c, "Content-Encoding: gzip\r\n", 24);
3322 7 hm_wb_put(c, "Vary: Accept-Encoding\r\n", 23);
3323 }
3324 /* Alt-Svc: how a client finds out this origin also speaks HTTP/3. It is
3325 * advertised on the HTTP/1.1 and HTTP/2 responses and never on an h3 one,
3326 * where it would be telling a client what it is already using. The value
3327 * is precomputed per listener in hm_worker_listeners - never built from a
3328 * client-supplied Host, which would let a request choose the header. */
3329 /*
3330 # uncoverable branch true class:ignore_covered_err
3331 # uncoverable condition left count:1 class:ignore_covered_err
3332 # uncoverable condition right count:1 class:ignore_covered_err
3333 # uncoverable condition left count:2 class:ignore_covered_err */
3334 825 ▶ if (c->lst && c->lst->altsvc) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->lst && c->lst->altsvc) { 825 0 825
if (c->lst && c->lst->altsvc) { 0 825 825
3335 0 hm_wb_put(c, "Alt-Svc: ", 9); /* # uncoverable statement class:ignore_covered_err */
3336 0 hm_wb_put(c, c->lst->altsvc, strlen(c->lst->altsvc)); /* # uncoverable statement class:ignore_covered_err */
3337 0 hm_wb_put(c, "\r\n", 2); /* # uncoverable statement class:ignore_covered_err */
3338 }
3339 /* 1xx/204/304 carry no entity: no Content-Length, no body (RFC 7230) */
3340 {
3341 825 ▶ int no_entity = (status < 200 || status == 204 || status == 304);
Branch: 3 branches
BranchTrueFalseTotal
int no_entity = (status < 200 || status == 204 || status == 304); 822 3 825
int no_entity = (status < 200 || status == 204 || status == 304); 819 3 822
int no_entity = (status < 200 || status == 204 || status == 304); 3 816 819
3342 825 ▶ if (no_entity) {
Branch: 1 branch
BranchTrueFalseTotal
if (no_entity) { 9 816 825
3343 /*
3344 # uncoverable branch true class:ignore_covered_err
3345 # uncoverable condition left count:1 class:ignore_covered_err */
3346 9 ▶ if (fh_body) { SvREFCNT_dec(fh_body); fh_body = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (fh_body) { SvREFCNT_dec(fh_body); fh_body = NULL; } 0 9 9
3347 9 ▶ if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc);
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc); 1 8 9
3348 9 bav = NULL; bn = 0; blen = 0;
3349 816 ▶ } else if (!has_len) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!has_len) { 564 252 816
3350 564 memcpy(line, "Content-Length: ", 16);
3351 564 ln = 16 + (int)hm_utoa(line + 16, (unsigned long)blen);
3352 564 line[ln++] = '\r'; line[ln++] = '\n';
3353 564 hm_wb_put(c, line, (size_t)ln);
3354 }
3355 /* HEAD: the headers of the GET, including its Content-Length, and
3356 * not one body byte - which the app, like most apps, produced
3357 * anyway. Sending it would be read as the start of the next
3358 * response on this connection. */
3359 825 ▶ if (!no_entity && c->is_head) {
Branch: 2 branches
BranchTrueFalseTotal
if (!no_entity && c->is_head) { 816 9 825
if (!no_entity && c->is_head) { 3 813 816
3360 /*
3361 # uncoverable branch true class:ignore_covered_err
3362 # uncoverable condition left count:1 class:ignore_covered_err */
3363 3 ▶ if (fh_body) { SvREFCNT_dec(fh_body); fh_body = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (fh_body) { SvREFCNT_dec(fh_body); fh_body = NULL; } 0 3 3
3364 3 ▶ if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc);
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.kind) hm_bsrc_release(aTHX_ &c->bsrc); 1 2 3
3365 3 bav = NULL; bn = 0; blen = 0;
3366 3 c->last_blen = 0;
3367 }
3368 }
3369 825 ▶ if (!has_date) {
Branch: 1 branch
BranchTrueFalseTotal
if (!has_date) { 824 1 825
3370 824 const char *dh = hm_date_header(loop);
3371 /*
3372 # uncoverable branch false class:ignore_covered_err
3373 # uncoverable condition right count:1 class:ignore_covered_err */
3374 824 ▶ if (dh) hm_wb_put(c, dh, HM_DATE_LEN);
Branch: 1 branch
BranchTrueFalseTotal
if (dh) hm_wb_put(c, dh, HM_DATE_LEN); 824 0 824
3375 }
3376 825 ▶ if (!has_conn)
Branch: 1 branch
BranchTrueFalseTotal
if (!has_conn) 824 1 825
3377 824 ▶ hm_wb_put(c, c->keepalive ? "Connection: keep-alive\r\n" : "Connection: close\r\n",
Branch: 1 branch
BranchTrueFalseTotal
hm_wb_put(c, c->keepalive ? "Connection: keep-alive\r\n" : "Connection: close\r\n", 160 664 824
3378 824 ▶ c->keepalive ? 24 : 19);
Branch: 1 branch
BranchTrueFalseTotal
c->keepalive ? 24 : 19); 160 664 824
3379 825 hm_wb_put(c, "\r\n", 2);
3380  
3381 825 loop->bytes_out += (c->wlen - hdr_start) + blen;
3382  
3383 /* fast path: nothing queued before this response -> writev header+body
3384 * straight from the response SVs, no body copy */
3385 /*
3386 # uncoverable condition right count:2 class:ignore_covered_err
3387 # uncoverable condition right count:3 class:ignore_covered_err
3388 # uncoverable condition left count:6 class:ignore_covered_err
3389 # uncoverable condition right count:9 class:ignore_covered_err
3390 # uncoverable condition right count:10 class:ignore_covered_err */
3391 825 ▶ if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body
Branch: 4 branches
BranchTrueFalseTotal
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 824 1 825
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 824 0 824
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 824 0 824
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 813 11 824
3392 813 ▶ && (!c->ssl || hm_ktls_tx(c))
Branch: 2 branches
BranchTrueFalseTotal
&& (!c->ssl || hm_ktls_tx(c)) 43 770 813
&& (!c->ssl || hm_ktls_tx(c)) 43 0 43
3393 813 ▶ && !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) {
Branch: 4 branches
BranchTrueFalseTotal
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 801 12 813
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 789 12 801
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 789 0 789
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 789 0 789
3394 hm_iovec iov[HM_IOV_MAX];
3395 789 size_t total = c->wlen;
3396 789 int niov = 1;
3397 SSize_t i;
3398 ssize_t n;
3399 789 HM_IOV_SET(iov, 0, c->wbuf, c->wlen);
3400 1577 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 788 789 1577
3401 788 SV **e = av_fetch(bav, i, 0);
3402 /*
3403 # uncoverable branch false class:ignore_covered_err
3404 # uncoverable condition right count:1 class:ignore_covered_err */
3405 788 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 788 0 788
3406 788 STRLEN l; const char *p = SvPV(*e, l);
3407 /*
3408 # uncoverable branch false class:ignore_covered_err
3409 # uncoverable condition right count:1 class:ignore_covered_err */
3410 788 ▶ if (l) {
Branch: 1 branch
BranchTrueFalseTotal
if (l) { 788 0 788
3411 788 HM_IOV_SET(iov, niov, p, l);
3412 788 niov++;
3413 788 total += l;
3414 }
3415 }
3416 }
3417 789 n = hm_os_writev(c->fd, iov, niov);
3418 /*
3419 # uncoverable branch true class:ignore_covered_err
3420 # uncoverable condition left count:1 class:ignore_covered_err */
3421 789 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 0 789 789
3422 /*
3423 # uncoverable statement
3424 # uncoverable branch true
3425 # uncoverable branch false
3426 # uncoverable condition left count:1
3427 # uncoverable condition right count:1
3428 # uncoverable condition left count:2
3429 # uncoverable condition right count:2 */
3430 0 ▶ if (errno != EAGAIN && errno != EWOULDBLOCK) { hm_close(aTHX_ loop, c); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (errno != EAGAIN && errno != EWOULDBLOCK) { hm_close(aTHX_ loop, c); return -1; } 0 0 0
if (errno != EAGAIN && errno != EWOULDBLOCK) { hm_close(aTHX_ loop, c); return -1; } 0 0 0
3431 0 n = 0; /* # uncoverable statement */
3432 }
3433 /*
3434 # uncoverable branch false class:ignore_covered_err
3435 # uncoverable condition right count:1 class:ignore_covered_err */
3436 789 ▶ if ((size_t)n >= total) { c->wlen = 0; return 0; } /* all written */
Branch: 1 branch
BranchTrueFalseTotal
if ((size_t)n >= total) { c->wlen = 0; return 0; } /* all written */ 786 3 789
3437 /* partial: keep the unwritten remainder in wbuf */
3438 {
3439 3 size_t skip = (size_t)n; /* # uncoverable statement class:ignore_covered_err */
3440 3 size_t hdrlen = c->wlen; /* # uncoverable statement class:ignore_covered_err */
3441 /*
3442 # uncoverable branch true class:ignore_covered_err
3443 # uncoverable statement class:ignore_covered_err
3444 # uncoverable branch false class:ignore_covered_err
3445 # uncoverable condition left count:1 class:ignore_covered_err
3446 # uncoverable condition right count:1 class:ignore_covered_err */
3447 3 ▶ if (skip < hdrlen) {
Branch: 1 branch
BranchTrueFalseTotal
if (skip < hdrlen) { 0 3 3
3448 0 memmove(c->wbuf, c->wbuf + skip, hdrlen - skip); /* # uncoverable statement */
3449 0 c->wlen = hdrlen - skip; /* # uncoverable statement */
3450 0 skip = 0; /* # uncoverable statement */
3451 } else {
3452 3 skip -= hdrlen; /* # uncoverable statement class:ignore_covered_err */
3453 3 c->wlen = 0; /* # uncoverable statement class:ignore_covered_err */
3454 }
3455 /*
3456 # uncoverable statement class:ignore_covered_err
3457 # uncoverable branch true class:ignore_covered_err
3458 # uncoverable branch false class:ignore_covered_err
3459 # uncoverable condition left count:1 class:ignore_covered_err
3460 # uncoverable condition right count:1 class:ignore_covered_err */
3461 6 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 3 3 6
3462 3 SV **e = av_fetch(bav, i, 0); /* # uncoverable statement class:ignore_covered_err */
3463 /*
3464 # uncoverable statement class:ignore_covered_err
3465 # uncoverable branch true class:ignore_covered_err
3466 # uncoverable branch false class:ignore_covered_err
3467 # uncoverable condition left count:1 class:ignore_covered_err
3468 # uncoverable condition right count:1 class:ignore_covered_err */
3469 3 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 3 0 3
3470 3 STRLEN l; const char *p = SvPV(*e, l); /* # uncoverable statement class:ignore_covered_err */
3471 /*
3472 # uncoverable branch true class:ignore_covered_err
3473 # uncoverable statement class:ignore_covered_err
3474 # uncoverable branch false class:ignore_covered_err
3475 # uncoverable condition left count:1 class:ignore_covered_err
3476 # uncoverable condition right count:1 class:ignore_covered_err */
3477 3 ▶ if (skip >= l) { skip -= l; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (skip >= l) { skip -= l; continue; } 0 3 3
3478 3 hm_wb_put(c, p + skip, l - skip); /* # uncoverable statement class:ignore_covered_err */
3479 3 skip = 0; /* # uncoverable statement class:ignore_covered_err */
3480 }
3481 }
3482 }
3483 3 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0); /* # uncoverable statement class:ignore_covered_err */
3484 3 c->writing = 1; /* # uncoverable statement class:ignore_covered_err */
3485 3 return 0; /* # uncoverable statement class:ignore_covered_err */
3486 }
3487  
3488 /* slow path: copy the body into the write buffer */
3489 36 ▶ if (fh_body) {
Branch: 1 branch
BranchTrueFalseTotal
if (fh_body) { 11 25 36
3490 11 STRLEN l; const char *p = SvPV(fh_body, l);
3491 11 hm_wb_put(c, p, l);
3492 11 SvREFCNT_dec(fh_body);
3493 25 ▶ } else if (bav) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (bav) { 1 24 25
3494 SSize_t i;
3495 2 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 1 1 2
3496 1 SV **e = av_fetch(bav, i, 0);
3497 /*
3498 # uncoverable branch false class:ignore_covered_err
3499 # uncoverable condition right count:1 class:ignore_covered_err */
3500 2 ▶ if (e) { STRLEN l; const char *p = SvPV(*e, l); hm_wb_put(c, p, l); }
Branch: 1 branch
BranchTrueFalseTotal
if (e) { STRLEN l; const char *p = SvPV(*e, l); hm_wb_put(c, p, l); } 1 0 1
3501 }
3502 }
3503 36 return 0;
3504 }
3505  
3506 /* Flush c->wbuf; on EAGAIN arm a write watcher. Returns 0 to keep the
3507 * connection, -1 if it was closed. A streaming body source (c->bsrc) is
3508 * drained here: buffer empties, source refills it a chunk at a time - or
3509 * skips the buffer entirely via sendfile(2) on a plaintext socket - so a
3510 * large file response never holds more than one chunk in memory. */
3511 3161 static int hm_flush(pTHX_ hm_conn *c) {
3512 3161 hm_loop *loop = c->loop;
3513 3161 int src_done = 0;
3514 3161 ▶ if (c->wlen == 0 && !c->bsrc.kind) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->wlen == 0 && !c->bsrc.kind) { 2241 920 3161
if (c->wlen == 0 && !c->bsrc.kind) { 8 912 920
3515 912 ▶ if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; } 689 223 912
if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; } 670 19 689
3516 242 ▶ if (c->stream_done) { /* a streamed body ended
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_done) { /* a streamed body ended 1 241 242
3517 * with nothing to flush */
3518 1 c->stream_done = 0;
3519 /*
3520 # uncoverable branch false class:ignore_covered_err
3521 # uncoverable condition right count:1 class:ignore_covered_err
3522 # uncoverable condition left count:2 class:ignore_covered_err
3523 # uncoverable condition right count:2 class:ignore_covered_err */
3524 1 ▶ if (c->rlen > 0 || loop->completion) hm_again_push(loop, c);
Branch: 2 branches
BranchTrueFalseTotal
if (c->rlen > 0 || loop->completion) hm_again_push(loop, c); 0 1 1
if (c->rlen > 0 || loop->completion) hm_again_push(loop, c); 0 0 0
3525 }
3526 242 return 0;
3527 }
3528 for (;;) {
3529 4343 ▶ while (c->woff < c->wlen) {
Branch: 1 branch
BranchTrueFalseTotal
while (c->woff < c->wlen) { 3292 1051 4343
3530 3292 ssize_t n = hm_cwrite(c, c->wbuf + c->woff, c->wlen - c->woff);
3531 3292 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 2027 1265 3292
3532 2027 c->woff += (size_t)n;
3533 /*
3534 # uncoverable condition right count:1 class:ignore_covered_err
3535 # uncoverable condition left count:3 class:ignore_covered_err */
3536 1265 ▶ } else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
Branch: 3 branches
BranchTrueFalseTotal
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { 1265 0 1265
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { 2 1263 1265
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { 0 2 2
3537 /* arm a write watcher, unless the TLS engine is blocked
3538 * wanting a read (the always-armed read watcher re-drives
3539 * us then) */
3540 1263 ▶ if (!c->writing && !c->tls_w_wants_r) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!c->writing && !c->tls_w_wants_r) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 5 1258 1263
if (!c->writing && !c->tls_w_wants_r) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 5 0 5
3541 5 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0);
3542 5 c->writing = 1;
3543 }
3544 1263 return 0;
3545 } else {
3546 2 hm_close(aTHX_ loop, c);
3547 2 return -1;
3548 }
3549 }
3550 /* buffer drained; keep the capacity for the next round */
3551 1051 c->wlen = c->woff = 0;
3552 1051 ▶ if (!c->bsrc.kind) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->bsrc.kind) break; 965 86 1051
3553  
3554 #if defined(HM_HAVE_SENDFILE_LINUX) || defined(HM_HAVE_SENDFILE_FREEBSD) \
3555 || defined(HM_HAVE_SENDFILE_MACOS)
3556 /* file straight to a plaintext socket, no copy through userspace */
3557 /*
3558 # uncoverable condition left count:3 class:ignore_covered_err
3559 # uncoverable condition right count:4 class:ignore_covered_err */
3560 86 ▶ if (c->bsrc.kind == 1 && (!c->ssl || hm_ktls_tx(c)) && !c->bsrc.nosf) {
Branch: 4 branches
BranchTrueFalseTotal
if (c->bsrc.kind == 1 && (!c->ssl || hm_ktls_tx(c)) && !c->bsrc.nosf) { 42 44 86
if (c->bsrc.kind == 1 && (!c->ssl || hm_ktls_tx(c)) && !c->bsrc.nosf) { 1 41 42
if (c->bsrc.kind == 1 && (!c->ssl || hm_ktls_tx(c)) && !c->bsrc.nosf) { 1 0 1
if (c->bsrc.kind == 1 && (!c->ssl || hm_ktls_tx(c)) && !c->bsrc.nosf) { 42 0 42
3561 42 size_t want = c->bsrc.remaining < HM_SENDFILE_MAX
3562 ? (size_t)c->bsrc.remaining : HM_SENDFILE_MAX;
3563 42 ssize_t sent = -1;
3564 42 int again = 0;
3565 #if defined(HM_HAVE_SENDFILE_LINUX)
3566 42 off_t off = c->bsrc.off;
3567 42 sent = sendfile(c->fd, c->bsrc.fd, &off, want);
3568 /*
3569 # uncoverable condition right count:2 class:ignore_covered_err
3570 # uncoverable condition left count:3 class:ignore_covered_err
3571 # uncoverable condition right count:3 class:ignore_covered_err */
3572 42 ▶ again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
Branch: 3 branches
BranchTrueFalseTotal
again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)); 9 33 42
again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)); 1 8 9
again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)); 0 1 1
3573 #elif defined(HM_HAVE_SENDFILE_FREEBSD)
3574 off_t sbytes = 0;
3575 int r = sendfile(c->bsrc.fd, c->fd, c->bsrc.off, want,
3576 NULL, &sbytes, 0);
3577 if (r == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
3578 sent = (ssize_t)sbytes;
3579 again = (r != 0);
3580 }
3581 #elif defined(HM_HAVE_SENDFILE_MACOS)
3582 off_t len = (off_t)want;
3583 int r = sendfile(c->bsrc.fd, c->fd, c->bsrc.off, &len, NULL, 0);
3584 if (r == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
3585 sent = (ssize_t)len;
3586 again = (r != 0);
3587 }
3588 #endif
3589 42 ▶ if (sent > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent > 0) { 33 9 42
3590 33 c->bsrc.off += sent;
3591 33 c->bsrc.remaining -= (UV)sent;
3592 }
3593 42 ▶ if (c->bsrc.remaining == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.remaining == 0) { 10 32 42
3594 10 hm_bsrc_release(aTHX_ &c->bsrc);
3595 10 src_done = 1;
3596 10 break;
3597 }
3598 /*
3599 # uncoverable branch false class:ignore_covered_err
3600 # uncoverable condition right count:1 class:ignore_covered_err
3601 # uncoverable condition right count:2 class:ignore_covered_err */
3602 32 ▶ if (again || sent > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (again || sent > 0) { 24 8 32
if (again || sent > 0) { 23 1 24
3603 31 ▶ if (again) {
Branch: 1 branch
BranchTrueFalseTotal
if (again) { 8 23 31
3604 8 ▶ if (!c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->writing) { 1 7 8
3605 1 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0);
3606 1 c->writing = 1;
3607 }
3608 8 return 0;
3609 }
3610 23 continue; /* kernel took it all; try more */
3611 }
3612 /* sendfile refused this pairing (filesystem, socket state):
3613 * fall back to the read path for the rest of this body */
3614 1 c->bsrc.nosf = 1; /* # uncoverable statement class:ignore_covered_err */
3615 }
3616 #endif
3617 {
3618 45 ssize_t n = hm_bsrc_fill(aTHX_ c);
3619 45 ▶ if (n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { 1 44 45
3620 /* spent (0), or ended early (-1, keepalive already off) */
3621 1 hm_bsrc_release(aTHX_ &c->bsrc);
3622 1 src_done = 1;
3623 /*
3624 # uncoverable branch true
3625 # uncoverable condition left count:1 class:ignore_covered_err */
3626 1 ▶ if (c->wlen) continue; /* write what the fill added */
Branch: 1 branch
BranchTrueFalseTotal
if (c->wlen) continue; /* write what the fill added */ 0 1 1
3627 1 break;
3628 }
3629 }
3630 }
3631 /* fully written; keep the buffer + capacity for the next response */
3632 976 c->wlen = c->woff = 0;
3633 976 ▶ if (c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->writing) { 8 968 976
3634 8 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE);
3635 8 c->writing = 0;
3636 }
3637 /* A stream handle that was told to stop producing can start again. The
3638 * callback may write, and writing calls back in here, so re-read the
3639 * connection afterwards rather than deciding on what was true before. */
3640 976 ▶ if (hm_stream_paused_n) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_stream_paused_n) { 1 975 976
3641 1 int fd = c->fd;
3642 1 hm_stream_drained(aTHX_ c);
3643 /*
3644 # uncoverable branch true
3645 # uncoverable condition left count:1 class:ignore_covered_err */
3646 1 ▶ if (loop->conns[fd] != c) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return -1; 0 1 1
3647 1 ▶ if (c->wlen || c->bsrc.kind) return 0; /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c->wlen || c->bsrc.kind) return 0; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 1 1
if (c->wlen || c->bsrc.kind) return 0; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 0 0
3648 }
3649 /* hm_process stopped on a full write buffer with requests still in the
3650 * read buffer: the client has now read, so serve the next of them. */
3651 975 ▶ if (c->backlogged) { c->backlogged = 0; hm_again_push(loop, c); }
Branch: 1 branch
BranchTrueFalseTotal
if (c->backlogged) { c->backlogged = 0; hm_again_push(loop, c); } 1 974 975
3652 975 ▶ if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; } 915 60 975
if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; } 54 861 915
3653 /* requests that pipelined in behind the stream were parked; pick them
3654 * up on the next loop turn */
3655 /* Pipelined requests behind the stream are picked up next turn - and in
3656 * completion mode the SAME push is what re-arms the read, which is why
3657 * an empty buffer is scheduled too. Without that a connection that
3658 * streamed a body would never be read from again. */
3659 921 ▶ if (c->stream_done) { c->stream_done = 0; src_done = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_done) { c->stream_done = 0; src_done = 1; } 8 913 921
3660 921 ▶ if (src_done && (c->rlen > 0 || loop->completion)) hm_again_push(loop, c); /* # uncoverable condition left count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (src_done && (c->rlen > 0 || loop->completion)) hm_again_push(loop, c); /* # uncoverable condition left count:3 class:ignore_covered_err */ 18 903 921
if (src_done && (c->rlen > 0 || loop->completion)) hm_again_push(loop, c); /* # uncoverable condition left count:3 class:ignore_covered_err */ 15 3 18
if (src_done && (c->rlen > 0 || loop->completion)) hm_again_push(loop, c); /* # uncoverable condition left count:3 class:ignore_covered_err */ 0 15 15
3661 921 return 0;
3662 }
3663  
3664 /* ---- async delivery (Future + streaming) --------------------------------- */
3665  
3666 /* Deliver an async response to a parked connection. No-op if the
3667 * connection is gone or the fd was reused. */
3668 12 static void hm_deliver(pTHX_ int fd, UV id, SV *resp) {
3669 12 hm_loop *loop = hm_cur_loop;
3670 /*
3671 # uncoverable condition right count:1 class:ignore_covered_err
3672 # uncoverable condition right count:2 class:ignore_covered_err
3673 # uncoverable condition right count:3 class:ignore_covered_err */
3674 12 ▶ hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL;
Branch: 3 branches
BranchTrueFalseTotal
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 12 0 12
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 12 0 12
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 12 0 12
3675 12 ▶ if (!(c && c->id == id)) return; /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!(c && c->id == id)) return; /* # uncoverable condition left count:2 class:ignore_covered_err */ 10 2 12
if (!(c && c->id == id)) return; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 10 10
3676 /* Only a parked connection is owed a response. A responder called a
3677 * second time, or the 500 for a streaming handler that died AFTER it
3678 * had already answered, would otherwise be serialised onto a live
3679 * keep-alive connection as the reply to its next request. */
3680 10 ▶ if (!c->awaiting) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->awaiting) return; 1 9 10
3681 /* A streamed response is open on this connection: a stream handle
3682 * opened after the handler parked (the documented pattern), whose
3683 * Future has now resolved with a value that is not a response, or a
3684 * second response for one request. Serialising it here put a status
3685 * line inside a chunked body. The handle owns the response; this one
3686 * is dropped. (A handler that DIED with a writer alive is the other
3687 * case, and hm_delayed closes the connection for that.) */
3688 /*
3689 # uncoverable branch true
3690 # uncoverable condition left count:1 class:ignore_covered_err */
3691 9 ▶ if (c->stream_open) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_open) { 0 9 9
3692 /*
3693 # uncoverable statement
3694 # uncoverable branch true
3695 # uncoverable branch false
3696 # uncoverable condition left count:1
3697 # uncoverable condition right count:1 */
3698 0 ▶ if (c->resp_f) { SvREFCNT_dec(c->resp_f); c->resp_f = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->resp_f) { SvREFCNT_dec(c->resp_f); c->resp_f = NULL; } 0 0 0
3699 0 return; /* # uncoverable statement */
3700 }
3701 /* detached from inside a Future continuation (async work before an
3702 * upgrade): the app owns the socket, so drop the response it resolved
3703 * with and forget the connection */
3704 /*
3705 # uncoverable branch true
3706 # uncoverable condition left count:1 class:ignore_covered_err */
3707 9 ▶ if (c->detached) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->detached) { 0 9 9
3708 0 c->awaiting = 0; /* # uncoverable statement */
3709 /*
3710 # uncoverable statement
3711 # uncoverable branch true
3712 # uncoverable branch false
3713 # uncoverable condition left count:1
3714 # uncoverable condition right count:1 */
3715 0 ▶ if (c->env_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { 0 0 0
3716 0 hm_access_log(aTHX_ loop, c->env_sv, 101, -1); /* # uncoverable statement */
3717 0 SvREFCNT_dec(c->env_sv); /* # uncoverable statement */
3718 0 c->env_sv = NULL; /* # uncoverable statement */
3719 }
3720 0 hm_conn_release(aTHX_ loop, c); /* # uncoverable statement */
3721 0 return; /* # uncoverable statement */
3722 }
3723 9 c->awaiting = 0;
3724 9 ▶ if (c->resp_f) { SvREFCNT_dec(c->resp_f); c->resp_f = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->resp_f) { SvREFCNT_dec(c->resp_f); c->resp_f = NULL; } 6 3 9
3725 9 ▶ if (c->env_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { 2 7 9
3726 2 SV *env_rv = c->env_sv;
3727 2 c->env_sv = NULL;
3728 /*
3729 # uncoverable branch false class:ignore_covered_err
3730 # uncoverable condition right count:1 class:ignore_covered_err
3731 # uncoverable condition right count:2 class:ignore_covered_err */
3732 2 ▶ if (hm_queue_response(aTHX_ c, resp) == 0 && loop->conns[fd] == c) {
Branch: 2 branches
BranchTrueFalseTotal
if (hm_queue_response(aTHX_ c, resp) == 0 && loop->conns[fd] == c) { 2 0 2
if (hm_queue_response(aTHX_ c, resp) == 0 && loop->conns[fd] == c) { 2 0 2
3733 2 hm_access_log(aTHX_ loop, env_rv, c->last_status,
3734 2 (ssize_t)c->last_blen);
3735 2 SvREFCNT_dec(env_rv);
3736 /*
3737 # uncoverable condition left count:1 class:ignore_covered_err
3738 # uncoverable condition left count:2 class:ignore_covered_err
3739 # uncoverable condition right count:2 class:ignore_covered_err */
3740 2 ▶ if (hm_flush(aTHX_ c) == 0 && loop->conns[fd] == c) {
Branch: 2 branches
BranchTrueFalseTotal
if (hm_flush(aTHX_ c) == 0 && loop->conns[fd] == c) { 0 2 2
if (hm_flush(aTHX_ c) == 0 && loop->conns[fd] == c) { 0 0 0
3741 0 hm_process(aTHX_ c); /* # uncoverable statement */
3742 /*
3743 # uncoverable statement
3744 # uncoverable branch true
3745 # uncoverable branch false
3746 # uncoverable condition left count:1
3747 # uncoverable condition right count:1 */
3748 0 ▶ if (loop->conns[fd] == c) hm_flush(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] == c) hm_flush(aTHX_ c); 0 0 0
3749 }
3750 } else {
3751 0 SvREFCNT_dec(env_rv); /* # uncoverable statement */
3752 }
3753 /* Parked connections have no read outstanding - the completion
3754 * handler skipped arming one while the response was being made - so
3755 * the re-arm is scheduled here, for the top of the next turn. */
3756 /*
3757 # uncoverable branch true class:ignore_covered_err
3758 # uncoverable condition left count:1 class:ignore_covered_err
3759 # uncoverable condition left count:2 class:ignore_covered_err
3760 # uncoverable condition right count:2 class:ignore_covered_err
3761 # uncoverable condition left count:3 class:ignore_covered_err
3762 # uncoverable condition right count:3 class:ignore_covered_err */
3763 2 ▶ if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind)
Branch: 3 branches
BranchTrueFalseTotal
if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind) 0 2 2
if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind) 0 0 0
if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind) 0 0 0
3764 0 hm_again_push(loop, c); /* # uncoverable statement */
3765 2 return;
3766 }
3767 /*
3768 # uncoverable branch false class:ignore_covered_err
3769 # uncoverable condition right count:1 class:ignore_covered_err
3770 # uncoverable condition right count:2 class:ignore_covered_err
3771 # uncoverable condition right count:3 class:ignore_covered_err
3772 # uncoverable condition right count:4 class:ignore_covered_err */
3773 7 ▶ if (hm_queue_response(aTHX_ c, resp) == 0
Branch: 1 branch
BranchTrueFalseTotal
if (hm_queue_response(aTHX_ c, resp) == 0 7 0 7
3774 7 ▶ && loop->conns[fd] == c
Branch: 1 branch
BranchTrueFalseTotal
&& loop->conns[fd] == c 7 0 7
3775 7 ▶ && hm_flush(aTHX_ c) == 0
Branch: 1 branch
BranchTrueFalseTotal
&& hm_flush(aTHX_ c) == 0 7 0 7
3776 7 ▶ && loop->conns[fd] == c) {
Branch: 1 branch
BranchTrueFalseTotal
&& loop->conns[fd] == c) { 7 0 7
3777 7 hm_process(aTHX_ c);
3778 /*
3779 # uncoverable branch false class:ignore_covered_err
3780 # uncoverable condition right count:1 class:ignore_covered_err */
3781 7 ▶ if (loop->conns[fd] == c) hm_flush(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] == c) hm_flush(aTHX_ c); 7 0 7
3782 }
3783 /*
3784 # uncoverable condition right count:2 class:ignore_covered_err
3785 # uncoverable condition right count:3 class:ignore_covered_err */
3786 7 ▶ if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind)
Branch: 3 branches
BranchTrueFalseTotal
if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind) 5 2 7
if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind) 5 0 5
if (loop->conns[fd] == c && !c->awaiting && !c->bsrc.kind) 5 0 5
3787 5 hm_again_push(loop, c);
3788 }
3789  
3790 /* How a streamed HTTP/1.1 body is framed, decided once in hm_start_stream:
3791 * EOF - Connection: close, the body ends when the connection does. The
3792 * only framing there was before 0.57, and still the one for
3793 * HTTP/1.0, a request that asked to close, a 101 tunnel, an app
3794 * that wrote its own Transfer-Encoding, and a draining server.
3795 * CHUNKED - Transfer-Encoding: chunked, keep-alive kept. Every write is one
3796 * chunk, close sends the last one, and the pipeline resumes.
3797 * LENGTH - the app gave Content-Length: bytes are counted; an overrun or
3798 * a short body breaks the framing, so the connection closes.
3799 * NOBODY - 1xx, 204, 304: headers only, keep-alive kept. */
3800 #define HM_SM_EOF 0
3801 #define HM_SM_CHUNKED 1
3802 #define HM_SM_LENGTH 2
3803 #define HM_SM_NOBODY 3
3804  
3805 /* Send status+headers for a streaming response; body follows via
3806 * hm_stream_write/hm_stream_close. */
3807 /* 1 when the response was begun; 0 when it was refused because this
3808 * connection is not parked on a response, or one has already begun; -1
3809 * when the headers were refused (a 500 went out instead). Only a PARKED
3810 * connection with no response begun: a second responder call, or a stale
3811 * responder kept from an earlier request on this keep-alive connection,
3812 * otherwise wrote a status line and headers into the body being streamed,
3813 * or into the next request's response. */
3814 45 static int hm_start_stream(pTHX_ int fd, UV id, int status, SV *headers) {
3815 45 hm_loop *loop = hm_cur_loop;
3816 /*
3817 # uncoverable condition right count:1 class:ignore_covered_err
3818 # uncoverable condition right count:2 class:ignore_covered_err
3819 # uncoverable condition right count:3 class:ignore_covered_err */
3820 45 ▶ hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL;
Branch: 3 branches
BranchTrueFalseTotal
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 45 0 45
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 45 0 45
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 45 0 45
3821 char line[64];
3822 45 AV *hav = NULL;
3823 45 int has_date = 0, has_conn = 0, conn_close = 0, has_te = 0, has_len = 0;
3824 45 UV clen = 0;
3825 /*
3826 # uncoverable branch true class:ignore_covered_err
3827 # uncoverable condition left count:1 class:ignore_covered_err
3828 # uncoverable condition left count:2 class:ignore_covered_err */
3829 45 ▶ if (!(c && c->id == id)) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!(c && c->id == id)) return 0; 45 0 45
if (!(c && c->id == id)) return 0; 0 45 45
3830 45 ▶ if (!c->awaiting || c->stream_open) return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!c->awaiting || c->stream_open) return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 45 0 45
if (!c->awaiting || c->stream_open) return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 2 43 45
3831 43 c->stream_open = 1;
3832 43 c->stream_serial++;
3833 43 c->stream_mode = HM_SM_EOF;
3834 43 c->stream_left = 0;
3835 43 c->stream_done = 0;
3836 43 ▶ if (c->env_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { 11 32 43
3837 11 hm_access_log(aTHX_ loop, c->env_sv, status, -1);
3838 11 SvREFCNT_dec(c->env_sv);
3839 11 c->env_sv = NULL;
3840 }
3841 /*
3842 # uncoverable branch false class:ignore_covered_err
3843 # uncoverable condition right count:1 class:ignore_covered_err
3844 # uncoverable condition right count:2 class:ignore_covered_err
3845 # uncoverable condition right count:3 class:ignore_covered_err */
3846 43 ▶ if (headers && SvROK(headers) && SvTYPE(SvRV(headers)) == SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (headers && SvROK(headers) && SvTYPE(SvRV(headers)) == SVt_PVAV) 43 0 43
if (headers && SvROK(headers) && SvTYPE(SvRV(headers)) == SVt_PVAV) 43 0 43
if (headers && SvROK(headers) && SvTYPE(SvRV(headers)) == SVt_PVAV) 43 0 43
3847 43 hav = (AV *)SvRV(headers);
3848 43 ▶ if (!hm_headers_ok(aTHX_ hav)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_headers_ok(aTHX_ hav)) { 1 42 43
3849 1 hm_errlog("Hyperman: response header carries CR, LF or NUL; refused\n");
3850 1 hm_wb_put(c, HM_ERR500, sizeof(HM_ERR500) - 1);
3851 1 c->last_status = 500;
3852 1 c->last_blen = 21;
3853 1 c->awaiting = 0; /* nothing more is owed on this connection */
3854 1 c->stream_open = 0;
3855 1 hm_flush(aTHX_ c);
3856 1 return -1;
3857 }
3858 {
3859 size_t sll;
3860 42 const char *sl = hm_status_line(status, &sll, line);
3861 42 hm_wb_put(c, sl, sll);
3862 }
3863 /*
3864 # uncoverable branch false class:ignore_covered_err
3865 # uncoverable condition right count:1 class:ignore_covered_err */
3866 42 ▶ if (hav) {
Branch: 1 branch
BranchTrueFalseTotal
if (hav) { 42 0 42
3867 42 SSize_t i, hn = av_len(hav) + 1;
3868 94 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 52 42 94
3869 52 SV **k = av_fetch(hav, i, 0);
3870 52 SV **v = av_fetch(hav, i + 1, 0);
3871 STRLEN kl, vl;
3872 const char *ks, *vs;
3873 /*
3874 # uncoverable branch true class:ignore_covered_err
3875 # uncoverable condition left count:1 class:ignore_covered_err
3876 # uncoverable condition left count:2 class:ignore_covered_err
3877 # uncoverable condition left count:3 class:ignore_covered_err
3878 # uncoverable condition left count:4 class:ignore_covered_err */
3879 52 ▶ if (!k || !*k || !v || !*v) continue;
Branch: 4 branches
BranchTrueFalseTotal
if (!k || !*k || !v || !*v) continue; 52 0 52
if (!k || !*k || !v || !*v) continue; 52 0 52
if (!k || !*k || !v || !*v) continue; 52 0 52
if (!k || !*k || !v || !*v) continue; 0 52 52
3880 52 ks = SvPV(*k, kl);
3881 52 ▶ vs = SvPV(*v, vl);
Branch: 1 branch
BranchTrueFalseTotal
vs = SvPV(*v, vl); 50 2 52
3882 /*
3883 # uncoverable condition right count:2 class:ignore_covered_err
3884 # uncoverable condition right count:3 class:ignore_covered_err */
3885 52 ▶ if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0)
Branch: 3 branches
BranchTrueFalseTotal
if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) 1 51 52
if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) 1 0 1
if (kl == 4 && (ks[0] | 32) == 'd' && hm_strncasecmp(ks, "Date", 4) == 0) 1 0 1
3886 1 has_date = 1;
3887 /*
3888 # uncoverable condition right count:2 class:ignore_covered_err
3889 # uncoverable condition right count:3 class:ignore_covered_err */
3890 51 ▶ else if (kl == 10 && (ks[0] | 32) == 'c'
Branch: 2 branches
BranchTrueFalseTotal
else if (kl == 10 && (ks[0] | 32) == 'c' 9 42 51
else if (kl == 10 && (ks[0] | 32) == 'c' 9 0 9
3891 9 ▶ && hm_strncasecmp(ks, "Connection", 10) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Connection", 10) == 0) { 9 0 9
3892 9 has_conn = 1;
3893 9 ▶ if (hm_ci_contains(vs, vl, "close")) conn_close = 1; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
if (hm_ci_contains(vs, vl, "close")) conn_close = 1; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 9 9
3894 }
3895 /*
3896 # uncoverable condition right count:2 class:ignore_covered_err
3897 # uncoverable condition right count:3 class:ignore_covered_err */
3898 42 ▶ else if (kl == 14 && (ks[0] | 32) == 'c'
Branch: 2 branches
BranchTrueFalseTotal
else if (kl == 14 && (ks[0] | 32) == 'c' 3 39 42
else if (kl == 14 && (ks[0] | 32) == 'c' 3 0 3
3899 3 ▶ && hm_strncasecmp(ks, "Content-Length", 14) == 0)
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Content-Length", 14) == 0) 3 0 3
3900 3 has_len = 1;
3901 /*
3902 # uncoverable condition right count:2 class:ignore_covered_err
3903 # uncoverable condition right count:3 class:ignore_covered_err */
3904 39 ▶ else if (kl == 17 && (ks[0] | 32) == 't'
Branch: 2 branches
BranchTrueFalseTotal
else if (kl == 17 && (ks[0] | 32) == 't' 1 38 39
else if (kl == 17 && (ks[0] | 32) == 't' 1 0 1
3905 1 ▶ && hm_strncasecmp(ks, "Transfer-Encoding", 17) == 0)
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Transfer-Encoding", 17) == 0) 1 0 1
3906 1 has_te = 1;
3907 52 hm_wb_put(c, ks, kl);
3908 52 hm_wb_put(c, ": ", 2);
3909 52 hm_wb_put(c, vs, vl);
3910 52 hm_wb_put(c, "\r\n", 2);
3911 }
3912 }
3913 42 ▶ if (!has_date) {
Branch: 1 branch
BranchTrueFalseTotal
if (!has_date) { 41 1 42
3914 41 const char *dh = hm_date_header(loop);
3915 /*
3916 # uncoverable branch false class:ignore_covered_err
3917 # uncoverable condition right count:1 class:ignore_covered_err */
3918 41 ▶ if (dh) hm_wb_put(c, dh, HM_DATE_LEN);
Branch: 1 branch
BranchTrueFalseTotal
if (dh) hm_wb_put(c, dh, HM_DATE_LEN); 41 0 41
3919 }
3920 42 ▶ if (has_len && !hm_hav_clen(aTHX_ hav, &clen)) has_len = 0; /* unparseable */
Branch: 2 branches
BranchTrueFalseTotal
if (has_len && !hm_hav_clen(aTHX_ hav, &clen)) has_len = 0; /* unparseable */ 3 39 42
if (has_len && !hm_hav_clen(aTHX_ hav, &clen)) has_len = 0; /* unparseable */ 1 2 3
3921 {
3922 42 ▶ int no_entity = (status < 200 || status == 204 || status == 304); /* # uncoverable condition left count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
int no_entity = (status < 200 || status == 204 || status == 304); /* # uncoverable condition left count:3 class:ignore_covered_err */ 33 9 42
int no_entity = (status < 200 || status == 204 || status == 304); /* # uncoverable condition left count:3 class:ignore_covered_err */ 32 1 33
int no_entity = (status < 200 || status == 204 || status == 304); /* # uncoverable condition left count:3 class:ignore_covered_err */ 0 32 32
3923 /*
3924 # uncoverable condition left count:2 class:ignore_covered_err
3925 # uncoverable condition left count:5 class:ignore_covered_err
3926 # uncoverable condition left count:6 class:ignore_covered_err */
3927 42 ▶ if (status == 101 || loop->stopping || !c->req_11 || !c->keepalive
Branch: 4 branches
BranchTrueFalseTotal
if (status == 101 || loop->stopping || !c->req_11 || !c->keepalive 33 9 42
if (status == 101 || loop->stopping || !c->req_11 || !c->keepalive 33 0 33
if (status == 101 || loop->stopping || !c->req_11 || !c->keepalive 32 1 33
if (status == 101 || loop->stopping || !c->req_11 || !c->keepalive 13 19 32
3928 13 ▶ || conn_close || has_te) {
Branch: 2 branches
BranchTrueFalseTotal
|| conn_close || has_te) { 13 0 13
|| conn_close || has_te) { 0 13 13
3929 29 c->stream_mode = HM_SM_EOF;
3930 29 c->keepalive = 0;
3931 /*
3932 # uncoverable branch true
3933 # uncoverable condition left count:1 class:ignore_covered_err */
3934 13 ▶ } else if (no_entity) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (no_entity) { 0 13 13
3935 0 c->stream_mode = HM_SM_NOBODY; /* # uncoverable statement */
3936 13 ▶ } else if (has_len) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (has_len) { 2 11 13
3937 2 c->stream_mode = HM_SM_LENGTH;
3938 2 c->stream_left = clen;
3939 } else {
3940 11 c->stream_mode = HM_SM_CHUNKED;
3941 11 hm_wb_put(c, "Transfer-Encoding: chunked\r\n", 28);
3942 }
3943 }
3944 /* A 101 is an upgrade: the caller's own Upgrade and Connection headers
3945 * are the response, and "close" would contradict them. The connection
3946 * still ends when the handle closes - keepalive is off above. */
3947 42 ▶ if (status == 101) hm_wb_put(c, "\r\n", 2);
Branch: 1 branch
BranchTrueFalseTotal
if (status == 101) hm_wb_put(c, "\r\n", 2); 9 33 42
3948 33 ▶ else if (c->stream_mode == HM_SM_EOF) hm_wb_put(c, "Connection: close\r\n\r\n", 21);
Branch: 1 branch
BranchTrueFalseTotal
else if (c->stream_mode == HM_SM_EOF) hm_wb_put(c, "Connection: close\r\n\r\n", 21); 20 13 33
3949 else {
3950 /*
3951 # uncoverable branch false class:ignore_covered_err
3952 # uncoverable condition right count:1 class:ignore_covered_err */
3953 13 ▶ if (!has_conn) hm_wb_put(c, "Connection: keep-alive\r\n", 24);
Branch: 1 branch
BranchTrueFalseTotal
if (!has_conn) hm_wb_put(c, "Connection: keep-alive\r\n", 24); 13 0 13
3954 13 hm_wb_put(c, "\r\n", 2);
3955 }
3956 42 hm_flush(aTHX_ c);
3957 42 return 1;
3958 }
3959  
3960 /* `serial` names the streamed response a Writer was handed out for; 0 skips
3961 * the check (the ABI stream handle has a registry of its own for that). A
3962 * writer kept past its response, or closed twice, must not touch the
3963 * response that followed on the same keep-alive connection. */
3964 /* Queue body bytes on a streamed HTTP/1.1 response, framed as the mode says.
3965 * Shared by the Writer (hm_stream_write) and the ABI stream handle
3966 * (hm_stream.h), so the two cannot disagree about the framing. Returns the
3967 * octets queued: 0 when nothing was (HEAD, no body, past the end), and the
3968 * caller then has nothing to flush. */
3969 2111 static STRLEN hm_stream_body_put(pTHX_ hm_conn *c, const char *p, STRLEN l) {
3970 /*
3971 # uncoverable branch true class:ignore_covered_err
3972 # uncoverable condition left count:1 class:ignore_covered_err
3973 # uncoverable condition left count:2 class:ignore_covered_err
3974 # uncoverable condition right count:2 class:ignore_covered_err */
3975 2111 ▶ if (!c->awaiting && !c->tunnel) return 0; /* the body has ended */
Branch: 2 branches
BranchTrueFalseTotal
if (!c->awaiting && !c->tunnel) return 0; /* the body has ended */ 0 2111 2111
if (!c->awaiting && !c->tunnel) return 0; /* the body has ended */ 0 0 0
3976 2111 ▶ if (c->is_head && !c->tunnel) return 0; /* HEAD: headers only */ /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c->is_head && !c->tunnel) return 0; /* HEAD: headers only */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 2107 2111
if (c->is_head && !c->tunnel) return 0; /* HEAD: headers only */ /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 0 4
3977 /*
3978 # uncoverable branch true
3979 # uncoverable condition left count:1 class:ignore_covered_err */
3980 2107 ▶ if (c->stream_mode == HM_SM_NOBODY) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_mode == HM_SM_NOBODY) return 0; 0 2107 2107
3981 2107 ▶ if (c->stream_mode == HM_SM_LENGTH) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_mode == HM_SM_LENGTH) { 3 2104 2107
3982 3 ▶ if (l > c->stream_left) { /* overrun: the framing is
Branch: 1 branch
BranchTrueFalseTotal
if (l > c->stream_left) { /* overrun: the framing is 1 2 3
3983 * broken, end the conn */
3984 1 l = (STRLEN)c->stream_left;
3985 1 c->keepalive = 0;
3986 }
3987 3 c->stream_left -= l;
3988 }
3989 2107 ▶ if (!l) return 0; /* a zero chunk ends a body */
Branch: 1 branch
BranchTrueFalseTotal
if (!l) return 0; /* a zero chunk ends a body */ 3 2104 2107
3990 2104 ▶ if (c->stream_mode == HM_SM_CHUNKED) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_mode == HM_SM_CHUNKED) { 17 2087 2104
3991 char sz[24];
3992 17 int n = snprintf(sz, sizeof(sz), "%" UVxf "\r\n", (UV)l);
3993 17 hm_wb_put(c, sz, (size_t)n);
3994 17 hm_wb_put(c, p, l);
3995 17 hm_wb_put(c, "\r\n", 2);
3996 } else {
3997 2087 hm_wb_put(c, p, l);
3998 }
3999 2104 c->loop->bytes_out += l;
4000 2104 return l;
4001 }
4002  
4003 /* 1: queued, and the connection holds less than HM_WB_HIWAT unwritten.
4004 * 0: queued, but the connection is holding more than that - the producer
4005 * should wait for a later write to answer 1 again before writing more
4006 * (the Perl Writer's ->write hands this back; before 0.62 it returned
4007 * nothing, and a producer feeding a slow reader grew the buffer without
4008 * bound).
4009 * -1: not written: the writer is stale (closed, or from an earlier
4010 * request on this connection). */
4011 43 static int hm_stream_write(pTHX_ int fd, UV id, UV serial, SV *data) {
4012 43 hm_loop *loop = hm_cur_loop;
4013 /*
4014 # uncoverable condition right count:2 class:ignore_covered_err
4015 # uncoverable condition right count:3 class:ignore_covered_err */
4016 43 ▶ hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL;
Branch: 3 branches
BranchTrueFalseTotal
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 41 2 43
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 41 0 41
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 41 0 41
4017 STRLEN l;
4018 const char *p;
4019 43 ▶ if (!(c && c->id == id)) return -1; /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!(c && c->id == id)) return -1; /* # uncoverable condition left count:2 class:ignore_covered_err */ 40 3 43
if (!(c && c->id == id)) return -1; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 40 40
4020 /*
4021 # uncoverable branch true class:ignore_covered_err
4022 # uncoverable condition left count:1 class:ignore_covered_err
4023 # uncoverable condition left count:2 class:ignore_covered_err */
4024 40 ▶ if (serial && c->stream_serial != serial) return -1;
Branch: 2 branches
BranchTrueFalseTotal
if (serial && c->stream_serial != serial) return -1; 38 2 40
if (serial && c->stream_serial != serial) return -1; 0 38 38
4025 40 ▶ if (!c->awaiting && !c->tunnel) return -1; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!c->awaiting && !c->tunnel) return -1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 37 40
if (!c->awaiting && !c->tunnel) return -1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 0 3
4026 37 p = SvPV(data, l);
4027 37 ▶ if (hm_stream_body_put(aTHX_ c, p, l)) hm_flush(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (hm_stream_body_put(aTHX_ c, p, l)) hm_flush(aTHX_ c); 30 7 37
4028 /*
4029 # uncoverable branch true
4030 # uncoverable condition left count:1 class:ignore_covered_err */
4031 37 ▶ if (loop->conns[fd] != c) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return -1; 0 37 37
4032 37 return (c->wlen - c->woff) > HM_WB_HIWAT ? 0 : 1;
4033 }
4034  
4035 62 static void hm_stream_close(pTHX_ int fd, UV id, UV serial) {
4036 62 hm_loop *loop = hm_cur_loop;
4037 /*
4038 # uncoverable condition right count:1 class:ignore_covered_err
4039 # uncoverable condition right count:2 class:ignore_covered_err
4040 # uncoverable condition right count:3 class:ignore_covered_err */
4041 62 ▶ hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL;
Branch: 3 branches
BranchTrueFalseTotal
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 62 0 62
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 62 0 62
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 62 0 62
4042 62 ▶ if (!(c && c->id == id)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!(c && c->id == id)) return; 47 15 62
if (!(c && c->id == id)) return; 2 45 47
4043 /*
4044 # uncoverable branch true class:ignore_covered_err
4045 # uncoverable condition left count:1 class:ignore_covered_err
4046 # uncoverable condition left count:2 class:ignore_covered_err */
4047 45 ▶ if (serial && c->stream_serial != serial) return;
Branch: 2 branches
BranchTrueFalseTotal
if (serial && c->stream_serial != serial) return; 27 18 45
if (serial && c->stream_serial != serial) return; 0 27 27
4048 45 ▶ if (!c->awaiting) return; /* closed already */
Branch: 1 branch
BranchTrueFalseTotal
if (!c->awaiting) return; /* closed already */ 8 37 45
4049 37 c->stream_open = 0;
4050 37 ▶ if (c->stream_mode == HM_SM_CHUNKED && !c->is_head)
Branch: 2 branches
BranchTrueFalseTotal
if (c->stream_mode == HM_SM_CHUNKED && !c->is_head) 9 28 37
if (c->stream_mode == HM_SM_CHUNKED && !c->is_head) 8 1 9
4051 8 hm_wb_put(c, "0\r\n\r\n", 5);
4052 29 ▶ else if (c->stream_mode == HM_SM_LENGTH && c->stream_left && !c->is_head) /* # uncoverable condition right count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
else if (c->stream_mode == HM_SM_LENGTH && c->stream_left && !c->is_head) /* # uncoverable condition right count:3 class:ignore_covered_err */ 2 27 29
else if (c->stream_mode == HM_SM_LENGTH && c->stream_left && !c->is_head) /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 1 2
else if (c->stream_mode == HM_SM_LENGTH && c->stream_left && !c->is_head) /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 0 1
4053 1 c->keepalive = 0; /* short body: cannot keep
4054 * the connection in frame */
4055 37 c->stream_mode = HM_SM_EOF;
4056 37 c->stream_left = 0;
4057 37 c->awaiting = 0;
4058 37 ▶ if (c->keepalive) c->stream_done = 1; /* hm_flush: serve the
Branch: 1 branch
BranchTrueFalseTotal
if (c->keepalive) c->stream_done = 1; /* hm_flush: serve the 9 28 37
4059 * pipeline when drained */
4060 37 hm_flush(aTHX_ c); /* closes when drained if keepalive is off */
4061 }
4062  
4063 /* The parked-Future continuation: when the response Future resolves,
4064 * deliver its result (or a 500 on failure, logged to psgi.errors). */
4065 XS_INTERNAL(hm_xs_park_cb);
4066 7 XS_INTERNAL(hm_xs_park_cb) {
4067 7 dXSARGS;
4068 7 hm_clos *cl = hm_clos_of(aTHX_ cv);
4069 7 SV *f, *resp = NULL;
4070 IV st;
4071 int fd;
4072 UV id;
4073 /*
4074 # uncoverable branch true class:ignore_covered_err
4075 # uncoverable condition left count:1 class:ignore_covered_err
4076 # uncoverable condition left count:2 class:ignore_covered_err */
4077 7 ▶ if (!cl || items < 1) XSRETURN_EMPTY;
Branch: 2 branches
BranchTrueFalseTotal
if (!cl || items < 1) XSRETURN_EMPTY; 7 0 7
if (!cl || items < 1) XSRETURN_EMPTY; 0 7 7
4078 7 f = ST(0);
4079 7 fd = (int)cl->i;
4080 7 id = cl->u;
4081 7 st = hm_any_state(aTHX_ f);
4082 7 ▶ if (st == HMF_DONE) {
Branch: 1 branch
BranchTrueFalseTotal
if (st == HMF_DONE) { 5 2 7
4083 5 ▶ if (hmf_is_future(aTHX_ f)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hmf_is_future(aTHX_ f)) { 5 0 5
4084 5 AV *vals = hmf_values_av(aTHX_ f);
4085 /*
4086 # uncoverable condition right count:1 class:ignore_covered_err
4087 # uncoverable condition right count:2 class:ignore_covered_err */
4088 5 ▶ SV **e = (vals && av_len(vals) >= 0) ? av_fetch(vals, 0, 0) : NULL;
Branch: 2 branches
BranchTrueFalseTotal
SV **e = (vals && av_len(vals) >= 0) ? av_fetch(vals, 0, 0) : NULL; 5 0 5
SV **e = (vals && av_len(vals) >= 0) ? av_fetch(vals, 0, 0) : NULL; 5 0 5
4089 5 ▶ resp = e ? sv_mortalcopy(*e) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
resp = e ? sv_mortalcopy(*e) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 5 0 5
4090 } else {
4091 0 dSP;
4092 0 SV *got = NULL;
4093 int n;
4094 0 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 0 0
4095 0 ▶ XPUSHs(f);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(f); 0 0 0
4096 0 PUTBACK;
4097 0 n = call_method("get", G_SCALAR | G_EVAL);
4098 0 SPAGAIN;
4099 /*
4100 # uncoverable branch false class:ignore_covered_err
4101 # uncoverable condition right count:1 class:ignore_covered_err
4102 # uncoverable condition right count:2 class:ignore_covered_err */
4103 0 ▶ if (n && !SvTRUE(ERRSV)) got = newSVsv(POPs);
Branch: 3 branches
BranchTrueFalseTotal
if (n && !SvTRUE(ERRSV)) got = newSVsv(POPs); 0 0 0
if (n && !SvTRUE(ERRSV)) got = newSVsv(POPs); 0 0 0
if (n && !SvTRUE(ERRSV)) got = newSVsv(POPs); 0 0 0
4104 /*
4105 # uncoverable statement
4106 # uncoverable branch true
4107 # uncoverable branch false
4108 # uncoverable condition left count:1
4109 # uncoverable condition right count:1 */
4110 0 ▶ else if (n) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
else if (n) (void)POPs; 0 0 0
4111 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
4112 /*
4113 # uncoverable branch false class:ignore_covered_err
4114 # uncoverable condition right count:1 class:ignore_covered_err */
4115 0 ▶ if (got) resp = sv_2mortal(got); /* mortal in the outer frame */
Branch: 1 branch
BranchTrueFalseTotal
if (got) resp = sv_2mortal(got); /* mortal in the outer frame */ 0 0 0
4116 }
4117 2 ▶ } else if (st == HMF_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (st == HMF_FAILED) { 1 1 2
4118 1 AV *errs = newAV();
4119 SV **e;
4120 STRLEN l;
4121 1 const char *msg = "unknown error";
4122 1 hm_any_values(aTHX_ f, st, errs);
4123 1 ▶ e = av_len(errs) >= 0 ? av_fetch(errs, 0, 0) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
e = av_len(errs) >= 0 ? av_fetch(errs, 0, 0) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 0 1
4124 /*
4125 # uncoverable branch false class:ignore_covered_err
4126 # uncoverable condition right count:1 class:ignore_covered_err
4127 # uncoverable condition right count:2 class:ignore_covered_err */
4128 2 ▶ if (e && SvOK(*e)) msg = SvPV(*e, l);
Branch: 2 branches
BranchTrueFalseTotal
if (e && SvOK(*e)) msg = SvPV(*e, l); 1 0 1
if (e && SvOK(*e)) msg = SvPV(*e, l); 1 0 1
4129 1 hm_errlog("Hyperman: async response failed: %s%s",
4130 /*
4131 # uncoverable condition right count:1 class:ignore_covered_err
4132 # uncoverable condition right count:2 class:ignore_covered_err */
4133 1 ▶ msg, (*msg && msg[strlen(msg)-1] == '\n') ? "" : "\n");
Branch: 2 branches
BranchTrueFalseTotal
msg, (*msg && msg[strlen(msg)-1] == '\n') ? "" : "\n"); 1 0 1
msg, (*msg && msg[strlen(msg)-1] == '\n') ? "" : "\n"); 1 0 1
4134 1 SvREFCNT_dec((SV *)errs);
4135 }
4136 /*
4137 # uncoverable condition left count:2 class:ignore_covered_err
4138 # uncoverable condition left count:3 class:ignore_covered_err */
4139 7 ▶ if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV))
Branch: 3 branches
BranchTrueFalseTotal
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) 5 2 7
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) 5 0 5
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) 0 5 5
4140 2 ▶ resp = hm_500_resp(aTHX_ st == HMF_DONE
Branch: 1 branch
BranchTrueFalseTotal
resp = hm_500_resp(aTHX_ st == HMF_DONE 0 2 2
4141 ? "Bad async response" : "Internal Server Error");
4142 7 hm_deliver(aTHX_ fd, id, resp);
4143 7 XSRETURN_EMPTY;
4144 }
4145  
4146 /* Park a connection awaiting a pending Future. */
4147 8 static void hm_park(pTHX_ hm_conn *c, SV *future) {
4148 8 SV *cb = hm_closure(aTHX_ hm_xs_park_cb, NULL, NULL, NULL, NULL,
4149 8 (IV)c->fd, c->id);
4150 8 hm_any_on_ready(aTHX_ future, cb);
4151 8 SvREFCNT_dec(cb);
4152 8 }
4153  
4154 /* psgi.streaming responder: [$s,$h,$b] delivers now; [$s,$h] starts a
4155 * stream and returns a Hyperman::Writer. */
4156 XS_INTERNAL(hm_xs_responder);
4157 30 XS_INTERNAL(hm_xs_responder) {
4158 30 dXSARGS;
4159 30 hm_clos *cl = hm_clos_of(aTHX_ cv);
4160 SV *r;
4161 AV *rav;
4162 SSize_t n;
4163 int fd;
4164 UV id;
4165 /*
4166 # uncoverable branch true class:ignore_covered_err
4167 # uncoverable condition left count:1 class:ignore_covered_err */
4168 30 ▶ if (!cl) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!cl) XSRETURN_EMPTY; 0 30 30
4169 30 fd = (int)cl->i;
4170 30 id = cl->u;
4171 /*
4172 # uncoverable condition left count:1 class:ignore_covered_err
4173 # uncoverable condition left count:3 class:ignore_covered_err */
4174 30 ▶ if (items < 1 || !(SvROK(ST(0)) && SvTYPE(SvRV(ST(0))) == SVt_PVAV))
Branch: 3 branches
BranchTrueFalseTotal
if (items < 1 || !(SvROK(ST(0)) && SvTYPE(SvRV(ST(0))) == SVt_PVAV)) 30 0 30
if (items < 1 || !(SvROK(ST(0)) && SvTYPE(SvRV(ST(0))) == SVt_PVAV)) 29 1 30
if (items < 1 || !(SvROK(ST(0)) && SvTYPE(SvRV(ST(0))) == SVt_PVAV)) 0 29 29
4175 1 croak("Hyperman responder expects an array reference");
4176 29 r = ST(0);
4177 29 rav = (AV *)SvRV(r);
4178 29 n = av_len(rav) + 1;
4179 29 ▶ if (n >= 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (n >= 3) { 2 27 29
4180 2 ▶ hm_conn *c = (hm_cur_loop && fd >= 0 && fd < HM_MAXFD)
Branch: 2 branches
BranchTrueFalseTotal
hm_conn *c = (hm_cur_loop && fd >= 0 && fd < HM_MAXFD) 2 0 2
hm_conn *c = (hm_cur_loop && fd >= 0 && fd < HM_MAXFD) 2 0 2
4181 4 ▶ ? hm_cur_loop->conns[fd] : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? hm_cur_loop->conns[fd] : NULL; 2 0 2
4182 /*
4183 # uncoverable condition right count:1 class:ignore_covered_err
4184 # uncoverable condition right count:2 class:ignore_covered_err */
4185 2 ▶ if (c && c->id == id && c->stream_open)
Branch: 3 branches
BranchTrueFalseTotal
if (c && c->id == id && c->stream_open) 2 0 2
if (c && c->id == id && c->stream_open) 2 0 2
if (c && c->id == id && c->stream_open) 1 1 2
4186 1 croak("Hyperman responder: a response has already been started "
4187 "on this connection");
4188 1 hm_deliver(aTHX_ fd, id, r);
4189 1 XSRETURN_EMPTY;
4190 }
4191 27 ▶ if (n == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 2) { 26 1 27
4192 26 SV **s0 = av_fetch(rav, 0, 0);
4193 26 SV **s1 = av_fetch(rav, 1, 0);
4194 26 AV *w = newAV();
4195 SV *wrv;
4196 /*
4197 # uncoverable condition right count:1 class:ignore_covered_err
4198 # uncoverable condition right count:2 class:ignore_covered_err */
4199 26 ▶ int began = hm_start_stream(aTHX_ fd, id, s0 ? (int)SvIV(*s0) : 200,
Branch: 2 branches
BranchTrueFalseTotal
int began = hm_start_stream(aTHX_ fd, id, s0 ? (int)SvIV(*s0) : 200, 26 0 26
int began = hm_start_stream(aTHX_ fd, id, s0 ? (int)SvIV(*s0) : 200, 26 0 26
4200 s1 ? *s1 : NULL);
4201 26 ▶ if (began == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (began == 0) { 2 24 26
4202 2 SvREFCNT_dec((SV *)w);
4203 2 croak("Hyperman responder: a response has already been started "
4204 "on this connection");
4205 }
4206 24 ▶ if (began < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (began < 0) { 1 23 24
4207 1 SvREFCNT_dec((SV *)w);
4208 1 croak("Hyperman responder: a response header carries CR, LF or NUL");
4209 }
4210 23 av_push(w, newSViv(fd));
4211 23 av_push(w, newSVuv(id));
4212 /* the serial of the response just begun, read back from the conn
4213 * (hm_start_stream is a no-op on a stale ticket, so 0 then) */
4214 {
4215 23 ▶ hm_conn *c = (hm_cur_loop && fd >= 0 && fd < HM_MAXFD)
Branch: 2 branches
BranchTrueFalseTotal
hm_conn *c = (hm_cur_loop && fd >= 0 && fd < HM_MAXFD) 23 0 23
hm_conn *c = (hm_cur_loop && fd >= 0 && fd < HM_MAXFD) 23 0 23
4216 46 ▶ ? hm_cur_loop->conns[fd] : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? hm_cur_loop->conns[fd] : NULL; 23 0 23
4217 /*
4218 # uncoverable condition right count:1 class:ignore_covered_err
4219 # uncoverable condition right count:2 class:ignore_covered_err */
4220 23 ▶ av_push(w, newSVuv(c && c->id == id ? c->stream_serial : 0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(w, newSVuv(c && c->id == id ? c->stream_serial : 0)); 23 0 23
av_push(w, newSVuv(c && c->id == id ? c->stream_serial : 0)); 23 0 23
4221 }
4222 23 av_push(w, newSVpvs("h1"));
4223 23 wrv = newRV_noinc((SV *)w);
4224 23 sv_bless(wrv, gv_stashpv("Hyperman::Writer", GV_ADD));
4225 23 ST(0) = sv_2mortal(wrv);
4226 23 XSRETURN(1);
4227 }
4228 1 croak("Hyperman responder expects [status, headers, body] or [status, headers]");
4229 }
4230  
4231 /* psgi.streaming: run the app's coderef with a responder. */
4232 40 static void hm_delayed(pTHX_ hm_conn *c, SV *code) {
4233 40 SV *responder = hm_closure(aTHX_ hm_xs_responder, NULL, NULL, NULL, NULL,
4234 40 (IV)c->fd, c->id);
4235 40 int fd = c->fd;
4236 40 UV id = c->id;
4237 40 dSP;
4238 40 ENTER; SAVETMPS;
4239 40 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 40 40
4240 40 ▶ XPUSHs(responder);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(responder); 0 40 40
4241 40 PUTBACK;
4242 40 call_sv(code, G_DISCARD | G_EVAL);
4243 40 ▶ if (SvTRUE(ERRSV)) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 40 0 40
if (SvTRUE(ERRSV)) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 6 34 40
4244 6 hm_loop *loop = hm_cur_loop;
4245 /*
4246 # uncoverable condition right count:1 class:ignore_covered_err
4247 # uncoverable condition right count:2 class:ignore_covered_err
4248 # uncoverable condition right count:3 class:ignore_covered_err */
4249 6 ▶ hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL;
Branch: 3 branches
BranchTrueFalseTotal
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 6 0 6
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 6 0 6
hm_conn *c = (loop && fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 6 0 6
4250 6 ▶ if (c && c->id == id && c->awaiting && c->stream_open) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 4 branches
BranchTrueFalseTotal
if (c && c->id == id && c->awaiting && c->stream_open) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 5 1 6
if (c && c->id == id && c->awaiting && c->stream_open) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 5 0 5
if (c && c->id == id && c->awaiting && c->stream_open) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 1 5
if (c && c->id == id && c->awaiting && c->stream_open) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 2 2 4
4251 /* It answered through the responder, kept the writer alive, and
4252 * died with the body part written. A 500 cannot follow a status
4253 * line already sent, and ending the body as if complete would
4254 * hand the client a cut body it may cache: the connection ends
4255 * once what was written has drained, WITHOUT the terminating
4256 * chunk. (A writer that was a lexical has already been
4257 * destroyed by the unwind and ended the body itself, the
4258 * promise a dropped writer keeps.) */
4259 2 hm_warn_died(aTHX_ "streaming handler");
4260 2 c->stream_open = 0;
4261 2 c->stream_mode = HM_SM_EOF;
4262 2 c->stream_done = 0;
4263 2 c->keepalive = 0;
4264 2 c->awaiting = 0;
4265 /*
4266 # uncoverable branch true class:ignore_covered_err
4267 # uncoverable condition left count:1 class:ignore_covered_err */
4268 2 ▶ if (c->resp_f) { SvREFCNT_dec(c->resp_f); c->resp_f = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->resp_f) { SvREFCNT_dec(c->resp_f); c->resp_f = NULL; } 0 2 2
4269 2 hm_flush(aTHX_ c);
4270 } else {
4271 4 hm_deliver(aTHX_ fd, id, hm_500_resp(aTHX_ "Internal Server Error"));
4272 }
4273 }
4274 40 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 4 36 40
4275 40 SvREFCNT_dec(responder);
4276 40 }
4277  
4278 /* ---- HTTP/2 (h2c via nghttp2), reusing the helpers above ----------------- */
4279  
4280 #include "hm_http2.h"
4281  
4282 /* ---- ABI v6 stream handles, over both halves above ---------------------- */
4283  
4284 #include "hm_stream.h"
4285  
4286 /* ---- HTTP/3 over QUIC: the transport, then the semantics ---------------- */
4287  
4288 #include "hm_quic.h"
4289 #include "hm_http3.h"
4290  
4291 /* ---- request processing -------------------------------------------------- */
4292  
4293 12 static void hm_again_push(hm_loop *loop, hm_conn *c) {
4294 12 ▶ if (loop->again_n == loop->again_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->again_n == loop->again_cap) { 8 4 12
4295 8 ▶ loop->again_cap = loop->again_cap ? loop->again_cap * 2 : 64; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
loop->again_cap = loop->again_cap ? loop->again_cap * 2 : 64; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 8 8
4296 8 loop->again = (hm_again *)hm_xrealloc(loop->again,
4297 8 loop->again_cap * sizeof(hm_again));
4298 }
4299 12 loop->again[loop->again_n].fd = c->fd;
4300 12 loop->again[loop->again_n].id = c->id;
4301 12 loop->again_n++;
4302 12 c->again_queued = 1;
4303 12 }
4304  
4305 /* Built-in https redirect: synthesize a 301 to the same host and target on
4306 * the https port, so a plain :80 listener can bounce browsers to :443 without
4307 * ever touching the app. Host comes from the request (its :port is stripped);
4308 * the target port is omitted when it is the standard 443. */
4309 1 static SV *hm_redirect_response(pTHX_ HV *env, int https_port) {
4310 const char *host, *uri;
4311 STRLEN hlen, ulen;
4312 SV *loc;
4313 AV *rav, *hav, *bav;
4314 1 host = hm_env_str(aTHX_ env, "HTTP_HOST", 9, &hlen);
4315 1 uri = hm_env_str(aTHX_ env, "REQUEST_URI", 11, &ulen);
4316 /*
4317 # uncoverable branch true class:ignore_covered_err
4318 # uncoverable condition left count:1 class:ignore_covered_err */
4319 1 ▶ if (!uri) { uri = "/"; ulen = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (!uri) { uri = "/"; ulen = 1; } 0 1 1
4320 1 loc = newSVpvs("https://");
4321 /* Host and request-target are reflected into a response header, so stop at
4322 * the first control or space byte: a header value is only \r-delimited, so
4323 * a bare LF could otherwise smuggle a CRLF and inject/split the response.
4324 * A valid host[:port] / request-target contains no CTL or SP anyway. */
4325 /*
4326 # uncoverable branch false class:ignore_covered_err
4327 # uncoverable condition right count:1 class:ignore_covered_err */
4328 1 ▶ if (host) {
Branch: 1 branch
BranchTrueFalseTotal
if (host) { 1 0 1
4329 1 STRLEN i = 0; /* host, up to :port */
4330 1 ▶ if (hlen && host[0] == '[') { /* [v6]:port: whole */ /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (hlen && host[0] == '[') { /* [v6]:port: whole */ /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 0 1
if (hlen && host[0] == '[') { /* [v6]:port: whole */ /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 0 1
4331 /*
4332 # uncoverable condition right count:1 class:ignore_covered_err
4333 # uncoverable condition right count:2 class:ignore_covered_err */
4334 5 ▶ while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ']') i++;
Branch: 3 branches
BranchTrueFalseTotal
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ']') i++; 5 0 5
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ']') i++; 5 0 5
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ']') i++; 4 1 5
4335 /*
4336 # uncoverable branch false class:ignore_covered_err
4337 # uncoverable condition right count:1 class:ignore_covered_err
4338 # uncoverable condition right count:2 class:ignore_covered_err */
4339 1 ▶ if (i < hlen && host[i] == ']') i++;
Branch: 2 branches
BranchTrueFalseTotal
if (i < hlen && host[i] == ']') i++; 1 0 1
if (i < hlen && host[i] == ']') i++; 1 0 1
4340 } else {
4341 /*
4342 # uncoverable condition right count:1 class:ignore_covered_err
4343 # uncoverable condition right count:2 class:ignore_covered_err */
4344 0 ▶ while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++;
Branch: 3 branches
BranchTrueFalseTotal
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++; 0 0 0
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++; 0 0 0
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++; 0 0 0
4345 }
4346 1 sv_catpvn(loc, host, i);
4347 }
4348 /*
4349 # uncoverable branch false class:ignore_covered_err
4350 # uncoverable condition right count:1 class:ignore_covered_err */
4351 1 ▶ if (https_port != 443) sv_catpvf(loc, ":%d", https_port);
Branch: 1 branch
BranchTrueFalseTotal
if (https_port != 443) sv_catpvf(loc, ":%d", https_port); 1 0 1
4352 {
4353 1 STRLEN i = 0; /* request-target */
4354 7 ▶ while (i < ulen && (unsigned char)uri[i] > ' ') i++; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
while (i < ulen && (unsigned char)uri[i] > ' ') i++; /* # uncoverable condition right count:2 class:ignore_covered_err */ 6 1 7
while (i < ulen && (unsigned char)uri[i] > ' ') i++; /* # uncoverable condition right count:2 class:ignore_covered_err */ 6 0 6
4355 1 sv_catpvn(loc, uri, i);
4356 }
4357  
4358 1 hav = newAV();
4359 1 av_push(hav, newSVpvs("Location")); av_push(hav, loc);
4360 1 av_push(hav, newSVpvs("Content-Length")); av_push(hav, newSVpvs("0"));
4361 1 bav = newAV();
4362 1 rav = newAV();
4363 1 av_push(rav, newSViv(301));
4364 1 av_push(rav, newRV_noinc((SV *)hav));
4365 1 av_push(rav, newRV_noinc((SV *)bav));
4366 1 return newRV_noinc((SV *)rav);
4367 }
4368  
4369 /* Process complete requests buffered in c->rbuf, capped per wakeup so one
4370 * pipelined connection can't starve the others (fairness). */
4371 966 static void hm_process(pTHX_ hm_conn *c) {
4372 966 hm_loop *loop = c->loop;
4373 966 int served = 0;
4374  
4375 /* HTTP/2: once a connection is in h2 mode, all bytes go to nghttp2.
4376 * On a fresh connection with http2 enabled, sniff the h2 preface. */
4377 966 ▶ if (c->h2) { hm_h2_input(aTHX_ c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) { hm_h2_input(aTHX_ c); return; } 0 966 966
4378 966 ▶ if (c->lst && c->lst->http2 && c->nreqs == 0 && c->rlen > 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 4 branches
BranchTrueFalseTotal
if (c->lst && c->lst->http2 && c->nreqs == 0 && c->rlen > 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 0 966 966
if (c->lst && c->lst->http2 && c->nreqs == 0 && c->rlen > 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 966 0 966
if (c->lst && c->lst->http2 && c->nreqs == 0 && c->rlen > 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 0 0 0
if (c->lst && c->lst->http2 && c->nreqs == 0 && c->rlen > 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 0 0 0
4379 0 ▶ if (hm_h2_detect(aTHX_ c) != 0) return; /* started, or need more */
Branch: 1 branch
BranchTrueFalseTotal
if (hm_h2_detect(aTHX_ c) != 0) return; /* started, or need more */ 0 0 0
4380 }
4381  
4382 153 for (;;) {
4383 /*
4384 # uncoverable branch true
4385 # uncoverable condition left count:1 class:ignore_covered_err */
4386 1119 ▶ if (c->awaiting) break; /* parked; resumes via hm_deliver */
Branch: 1 branch
BranchTrueFalseTotal
if (c->awaiting) break; /* parked; resumes via hm_deliver */ 0 1119 1119
4387 1119 ▶ if (c->bsrc.kind) break; /* a body is still streaming out; the
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.kind) break; /* a body is still streaming out; the 11 1108 1119
4388 flush that finishes it re-queues us */
4389 /* Responses the client has not read yet. A pipeline that never
4390 * reads would otherwise have every request in the read buffer
4391 * answered into a write buffer that only grows: hold the rest until
4392 * the drain re-queues this connection (hm_flush, backlogged). */
4393 /*
4394 # uncoverable branch true class:ignore_covered_err
4395 # uncoverable condition left count:1 class:ignore_covered_err */
4396 1108 ▶ if (c->wlen - c->woff > HM_WB_HIWAT) { c->backlogged = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->wlen - c->woff > HM_WB_HIWAT) { c->backlogged = 1; break; } 1 1107 1108
4397  
4398 /* RFC 9112 2.2: at least one empty line before the request line is
4399 * ignored. Stripped here so the request line is the first line and
4400 * not an empty one with the real request line read as a header. */
4401 1107 ▶ if (c->rlen >= 2 && c->rbuf[0] == '\r' && c->rbuf[1] == '\n') { /* # uncoverable condition right count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (c->rlen >= 2 && c->rbuf[0] == '\r' && c->rbuf[1] == '\n') { /* # uncoverable condition right count:3 class:ignore_covered_err */ 961 146 1107
if (c->rlen >= 2 && c->rbuf[0] == '\r' && c->rbuf[1] == '\n') { /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 960 961
if (c->rlen >= 2 && c->rbuf[0] == '\r' && c->rbuf[1] == '\n') { /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 0 1
4402 1 size_t k = 0;
4403 /*
4404 # uncoverable condition right count:1 class:ignore_covered_err
4405 # uncoverable condition right count:3 class:ignore_covered_err */
4406 3 ▶ while (k + 1 < c->rlen && c->rbuf[k] == '\r' && c->rbuf[k + 1] == '\n') k += 2;
Branch: 3 branches
BranchTrueFalseTotal
while (k + 1 < c->rlen && c->rbuf[k] == '\r' && c->rbuf[k + 1] == '\n') k += 2; 3 0 3
while (k + 1 < c->rlen && c->rbuf[k] == '\r' && c->rbuf[k + 1] == '\n') k += 2; 2 1 3
while (k + 1 < c->rlen && c->rbuf[k] == '\r' && c->rbuf[k + 1] == '\n') k += 2; 2 0 2
4407 1 memmove(c->rbuf, c->rbuf + k, c->rlen - k);
4408 1 c->rlen -= k;
4409 /*
4410 # uncoverable branch true
4411 # uncoverable condition left count:1 class:ignore_covered_err */
4412 1 ▶ if (c->rlen == 0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen == 0) break; 0 1 1
4413 }
4414  
4415 1107 char *end = (char *)hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4);
4416 1107 ▶ if (!end) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!end) break; 155 952 1107
4417  
4418 952 ▶ if (served >= loop->max_pipeline) { /* yield to other conns */
Branch: 1 branch
BranchTrueFalseTotal
if (served >= loop->max_pipeline) { /* yield to other conns */ 2 950 952
4419 2 hm_again_push(loop, c);
4420 2 break;
4421 }
4422  
4423 950 size_t headlen = (size_t)(end - c->rbuf);
4424 950 size_t bodystart = headlen + 4;
4425  
4426 /* one pass: framing decision + header-line index for the env build */
4427 hm_hline hidx_stack[HM_HIDX_STACK];
4428 950 const hm_hline *hidx = hidx_stack;
4429 950 int nhl = 0;
4430 950 long clen = 0;
4431 950 int frame = hm_parse_index(c->rbuf, headlen, &clen,
4432 hidx_stack, HM_HIDX_STACK, &nhl);
4433 950 ▶ if (frame == -2) { /* > HM_HIDX_STACK header lines: rescan
Branch: 1 branch
BranchTrueFalseTotal
if (frame == -2) { /* > HM_HIDX_STACK header lines: rescan 1 949 950
4434 into the loop's growable index */
4435 /*
4436 # uncoverable branch false class:ignore_covered_err
4437 # uncoverable condition right count:1 class:ignore_covered_err */
4438 1 ▶ if (nhl > loop->hidx_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (nhl > loop->hidx_cap) { 1 0 1
4439 2 loop->hidx = (hm_hline *)hm_xrealloc(loop->hidx,
4440 1 (size_t)nhl * sizeof(hm_hline));
4441 1 loop->hidx_cap = nhl;
4442 }
4443 1 frame = hm_parse_index(c->rbuf, headlen, &clen,
4444 loop->hidx, loop->hidx_cap, &nhl);
4445 1 hidx = loop->hidx;
4446 }
4447 950 ▶ if (frame) { /* smuggling/framing: reject + close */
Branch: 1 branch
BranchTrueFalseTotal
if (frame) { /* smuggling/framing: reject + close */ 9 941 950
4448 9 ▶ if (frame == 501) {
Branch: 1 branch
BranchTrueFalseTotal
if (frame == 501) { 1 8 9
4449 static const char e501[] =
4450 "HTTP/1.1 501 Not Implemented\r\nContent-Length: 0\r\n"
4451 "Connection: close\r\n\r\n";
4452 1 hm_wb_put(c, e501, sizeof(e501) - 1);
4453 } else {
4454 static const char e400[] =
4455 "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n"
4456 "Connection: close\r\n\r\n";
4457 8 hm_wb_put(c, e400, sizeof(e400) - 1);
4458 }
4459 9 c->keepalive = 0;
4460 9 break;
4461 }
4462  
4463 /* An expectation this server cannot meet is refused now, on the
4464 * headers alone - which is the answer the client asked for. */
4465 941 int expect = hm_expectation(c->rbuf, headlen);
4466 941 ▶ if (expect == HM_EXPECT_OTHER) {
Branch: 1 branch
BranchTrueFalseTotal
if (expect == HM_EXPECT_OTHER) { 2 939 941
4467 static const char e417[] =
4468 "HTTP/1.1 417 Expectation Failed\r\nContent-Length: 0\r\n"
4469 "Connection: close\r\n\r\n";
4470 2 hm_wb_put(c, e417, sizeof(e417) - 1);
4471 2 c->keepalive = 0;
4472 2 c->last_status = 417;
4473 2 break;
4474 }
4475  
4476 size_t body_consumed; /* wire octets after the headers this request uses */
4477 939 ▶ if (clen < 0) { /* chunked: validate, then decode in place */
Branch: 1 branch
BranchTrueFalseTotal
if (clen < 0) { /* chunked: validate, then decode in place */ 22 917 939
4478 22 size_t enc = 0, dec = 0;
4479 22 int r = hm_chunked_scan_from(c->rbuf + bodystart, c->rlen - bodystart,
4480 &enc, &dec, loop->max_read,
4481 &c->chunk_pos, &c->chunk_dec);
4482 22 ▶ if (r == HM_CHUNKED_TOOBIG) { /* well framed, just too large */
Branch: 1 branch
BranchTrueFalseTotal
if (r == HM_CHUNKED_TOOBIG) { /* well framed, just too large */ 2 20 22
4483 static const char e413[] =
4484 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4485 "Connection: close\r\n\r\n";
4486 2 hm_wb_put(c, e413, sizeof(e413) - 1);
4487 2 c->keepalive = 0;
4488 2 c->last_status = 413;
4489 12 break;
4490 }
4491 20 ▶ if (r < 0) { /* malformed chunked */
Branch: 1 branch
BranchTrueFalseTotal
if (r < 0) { /* malformed chunked */ 4 16 20
4492 static const char e400[] =
4493 "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n"
4494 "Connection: close\r\n\r\n";
4495 4 hm_wb_put(c, e400, sizeof(e400) - 1);
4496 4 c->keepalive = 0;
4497 4 break;
4498 }
4499 16 ▶ if (r == 0) { /* need more bytes */
Branch: 1 branch
BranchTrueFalseTotal
if (r == 0) { /* need more bytes */ 6 10 16
4500 6 c->body_phase = 1;
4501 6 c->body_t0 = loop->now;
4502 6 c->body_rx = 0;
4503 /*
4504 # uncoverable branch true
4505 # uncoverable condition left count:1 class:ignore_covered_err */
4506 6 ▶ if (c->rlen - bodystart >= loop->max_read) { /* too big to fit */
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen - bodystart >= loop->max_read) { /* too big to fit */ 0 6 6
4507 static const char e413[] =
4508 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4509 "Connection: close\r\n\r\n";
4510 0 hm_wb_put(c, e413, sizeof(e413) - 1); /* # uncoverable statement */
4511 0 c->keepalive = 0; /* # uncoverable statement */
4512 }
4513 6 else hm_send_continue(c, expect);
4514 6 break;
4515 }
4516 10 hm_chunked_compact(c->rbuf + bodystart); /* -> dec octets @ bodystart */
4517 10 clen = (long)dec;
4518 10 body_consumed = enc;
4519 } else {
4520 917 ▶ if (bodystart + (size_t)clen > loop->max_read) { /* can never fit */
Branch: 1 branch
BranchTrueFalseTotal
if (bodystart + (size_t)clen > loop->max_read) { /* can never fit */ 7 910 917
4521 static const char e413[] =
4522 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4523 "Connection: close\r\n\r\n";
4524 7 hm_wb_put(c, e413, sizeof(e413) - 1);
4525 7 c->keepalive = 0;
4526 7 break;
4527 }
4528 /* A large body is drained to a temp file as it arrives rather
4529 * than accumulated here. rbuf keeps the headers and whatever
4530 * arrived after the body; the file gets the body.
4531 *
4532 * Identity framing only. A chunked body has no Content-Length to
4533 * divert on and its decoder wants the octets contiguous, so those
4534 * still accumulate - documented rather than hidden.
4535 *
4536 * Nothing about the loop changes: this still `break`s to wait for
4537 * more, and is re-driven when the socket is readable again. What
4538 * changes is that the waiting no longer costs the body. */
4539 910 ▶ if ((long)clen > HM_SPILL_BODY) {
Branch: 1 branch
BranchTrueFalseTotal
if ((long)clen > HM_SPILL_BODY) { 23 887 910
4540 23 size_t have = c->rlen - bodystart;
4541 /*
4542 # uncoverable branch true class:ignore_covered_err
4543 # uncoverable condition left count:1 class:ignore_covered_err
4544 # uncoverable condition left count:2 class:ignore_covered_err */
4545 23 ▶ if (c->spill_fd < 0 && (c->spill_fd = hm_body_tmpfile()) < 0)
Branch: 2 branches
BranchTrueFalseTotal
if (c->spill_fd < 0 && (c->spill_fd = hm_body_tmpfile()) < 0) 5 18 23
if (c->spill_fd < 0 && (c->spill_fd = hm_body_tmpfile()) < 0) 0 5 5
4546 0 goto hm_no_spill; /* cannot: behave as before */ /* # uncoverable statement */
4547 /*
4548 # uncoverable branch false class:ignore_covered_err
4549 # uncoverable condition right count:1 class:ignore_covered_err */
4550 23 ▶ if (have) {
Branch: 1 branch
BranchTrueFalseTotal
if (have) { 20 3 23
4551 20 size_t want = have;
4552 20 size_t room = (size_t)(clen - c->spill_got);
4553 /*
4554 # uncoverable branch true class:ignore_covered_err
4555 # uncoverable condition left count:1 class:ignore_covered_err */
4556 20 ▶ if (want > room) want = room; /* the rest is the next
Branch: 1 branch
BranchTrueFalseTotal
if (want > room) want = room; /* the rest is the next 1 19 20
4557 * request, not this body */
4558 /*
4559 # uncoverable branch false class:ignore_covered_err
4560 # uncoverable condition right count:1 class:ignore_covered_err */
4561 20 ▶ if (want) {
Branch: 1 branch
BranchTrueFalseTotal
if (want) { 20 0 20
4562 20 ssize_t w = write(c->spill_fd, c->rbuf + bodystart, want);
4563 /*
4564 # uncoverable branch true class:ignore_covered_err
4565 # uncoverable condition left count:1 class:ignore_covered_err */
4566 54 ▶ if (w <= 0) { hm_close(aTHX_ loop, c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (w <= 0) { hm_close(aTHX_ loop, c); return; } 0 20 20
4567 20 c->spill_got += w;
4568 20 memmove(c->rbuf + bodystart, c->rbuf + bodystart + w,
4569 20 c->rlen - bodystart - w);
4570 20 c->rlen -= (size_t)w;
4571 }
4572 }
4573 23 ▶ if (c->spill_got < (long)clen) { /* await more */
Branch: 1 branch
BranchTrueFalseTotal
if (c->spill_got < (long)clen) { /* await more */ 19 4 23
4574 19 c->body_phase = 1;
4575 19 c->body_t0 = loop->now;
4576 19 c->body_rx = 0;
4577 19 hm_send_continue(c, expect);
4578 19 break;
4579 }
4580 /*
4581 # uncoverable branch true
4582 # uncoverable condition left count:1 class:ignore_covered_err */
4583 4 ▶ if (lseek(c->spill_fd, 0, SEEK_SET) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (lseek(c->spill_fd, 0, SEEK_SET) < 0) { 0 4 4
4584 0 hm_close(aTHX_ loop, c); return; /* # uncoverable statement */
4585 }
4586 4 body_consumed = 0; /* none of it is in rbuf */
4587 4 goto hm_have_body;
4588 }
4589 887 hm_no_spill:
4590 887 ▶ if (c->rlen - bodystart < (size_t)clen) { /* await full body */
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen - bodystart < (size_t)clen) { /* await full body */ 22 865 887
4591 22 c->body_phase = 1;
4592 22 c->body_t0 = loop->now;
4593 22 c->body_rx = 0;
4594 22 hm_send_continue(c, expect);
4595 22 break;
4596 }
4597 865 body_consumed = (size_t)clen;
4598 869 hm_have_body: ;
4599 }
4600  
4601 #ifdef HM_HAVE_NGHTTP2
4602 /* HTTP/1.1 Upgrade: h2c (cleartext, first request only). h2c-over-TLS
4603 * is forbidden by RFC 7540; the TLS path uses ALPN. */
4604 /*
4605 # uncoverable condition right count:1 class:ignore_covered_err
4606 # uncoverable condition right count:4 class:ignore_covered_err */
4607 if (c->lst && c->lst->http2 && !c->ssl && !c->h2 && c->nreqs == 0) {
4608 size_t ul = 0, sl = 0;
4609 const char *up = hm_find_header(c->rbuf, headlen, "upgrade", 7, &ul);
4610 const char *se = hm_find_header(c->rbuf, headlen, "http2-settings", 14, &sl);
4611 if (up && se && hm_ci_contains(up, ul, "h2c")) { /* # uncoverable condition right count:3 class:ignore_covered_err */
4612 static const char resp101[] =
4613 "HTTP/1.1 101 Switching Protocols\r\n"
4614 "Connection: Upgrade\r\nUpgrade: h2c\r\n\r\n";
4615 /*
4616 # uncoverable condition left count:1 class:ignore_covered_err
4617 # uncoverable condition right count:1 class:ignore_covered_err
4618 # uncoverable condition left count:2 class:ignore_covered_err */
4619 int is_head = (headlen >= 5 && hm_strncasecmp(c->rbuf, "HEAD ", 5) == 0);
4620 HV *env = hm_build_env(aTHX_ c->rbuf, headlen,
4621 c->rbuf + bodystart, clen, c, hidx, nhl);
4622 (void)hv_stores(env, "SERVER_PROTOCOL", newSVpvs("HTTP/2"));
4623 hm_wb_put(c, resp101, sizeof(resp101) - 1);
4624 {
4625 size_t consumed = bodystart + body_consumed;
4626 memmove(c->rbuf, c->rbuf + consumed, c->rlen - consumed);
4627 c->rlen -= consumed;
4628 c->nreqs++;
4629 loop->requests++;
4630 /* The request is consumed: the header and body clocks
4631 * stop here, as they do for an ordinary request below.
4632 * An h2 session never passes that point again, so one
4633 * whose upgrade arrived in two reads was closed by the
4634 * sweep as a slow request header_timeout later. */
4635 c->req_start = 0;
4636 c->body_phase = 0;
4637 c->chunk_pos = c->chunk_dec = 0;
4638 }
4639 {
4640 int rc;
4641 c->in_app = 1; /* the upgrade dispatches stream 1 */
4642 rc = hm_h2_start_upgrade(aTHX_ c, se, sl, env, is_head);
4643 c->in_app = 0;
4644 if (rc < 0 || c->close_deferred) { /* # uncoverable condition left count:2 class:ignore_covered_err */
4645 c->close_deferred = 0;
4646 hm_close(aTHX_ loop, c);
4647 return;
4648 }
4649 hm_read_resume(loop, c);
4650 }
4651 hm_h2_input(aTHX_ c); /* client's h2 preface + frames, + flush */
4652 return;
4653 }
4654 }
4655 #endif
4656  
4657 879 HV *env = hm_build_env(aTHX_ c->rbuf, headlen, c->rbuf + bodystart,
4658 clen, c, hidx, nhl);
4659 879 SV *env_rv = NULL;
4660 SV *resp;
4661 879 c->in_app = 1; /* see hm_close: a close meanwhile is deferred */
4662 879 ▶ if (c->lst && c->lst->redirect_https) { /* built-in :80 -> :443 bounce */ /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c->lst && c->lst->redirect_https) { /* built-in :80 -> :443 bounce */ /* # uncoverable condition right count:1 class:ignore_covered_err */ 879 0 879
if (c->lst && c->lst->redirect_https) { /* built-in :80 -> :443 bounce */ /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 878 879
4663 1 resp = hm_redirect_response(aTHX_ env, c->lst->redirect_https);
4664 1 ▶ if (hm_logging(loop)) env_rv = newRV_noinc((SV *)env); /* # uncoverable branch true class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (hm_logging(loop)) env_rv = newRV_noinc((SV *)env); /* # uncoverable branch true class:ignore_covered_err */ 1 0 1
if (hm_logging(loop)) env_rv = newRV_noinc((SV *)env); /* # uncoverable branch true class:ignore_covered_err */ 0 1 1
4665 1 else SvREFCNT_dec((SV *)env);
4666 878 ▶ } else if (hm_logging(loop)) { /* env survives for access_log */
Branch: 2 branches
BranchTrueFalseTotal
} else if (hm_logging(loop)) { /* env survives for access_log */ 775 103 878
} else if (hm_logging(loop)) { /* env survives for access_log */ 67 708 775
4667 170 env_rv = newRV_noinc((SV *)env);
4668 170 resp = hm_call_app(aTHX_ loop, env_rv);
4669 } else {
4670 708 resp = hm_call_app0(aTHX_ loop, env);
4671 }
4672 879 c->in_app = 0;
4673 879 ▶ if (c->close_deferred) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->close_deferred) { 1 878 879
4674 /* The peer left, or the sweep gave up on it, while the handler
4675 * ran. Nothing it returned has anywhere to go. */
4676 1 c->close_deferred = 0;
4677 /*
4678 # uncoverable branch true class:ignore_covered_err
4679 # uncoverable condition left count:1 class:ignore_covered_err */
4680 1 ▶ if (env_rv) SvREFCNT_dec(env_rv);
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) SvREFCNT_dec(env_rv); 0 1 1
4681 /*
4682 # uncoverable branch false class:ignore_covered_err
4683 # uncoverable condition right count:1 class:ignore_covered_err */
4684 1 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 1 0 1
4685 1 hm_close(aTHX_ loop, c);
4686 1 return;
4687 }
4688 878 hm_read_resume(loop, c);
4689  
4690 /* The app called detach: the socket is its own now. Drop whatever it
4691 * returned (the sentinel), forget the connection, and do not touch c
4692 * again. Any bytes past this request are dropped with it - RFC 6455
4693 * forbids the client sending before the 101, so they are a protocol
4694 * violation, not data we owe anyone. */
4695 878 ▶ if (c->detached) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->detached) { 4 874 878
4696 4 ▶ if (env_rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) { 1 3 4
4697 1 hm_access_log(aTHX_ loop, env_rv, 101, -1);
4698 1 SvREFCNT_dec(env_rv);
4699 }
4700 /*
4701 # uncoverable branch false class:ignore_covered_err
4702 # uncoverable condition right count:1 class:ignore_covered_err */
4703 4 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 4 0 4
4704 4 c->nreqs++;
4705 4 loop->requests++;
4706 4 hm_conn_release(aTHX_ loop, c);
4707 4 return;
4708 }
4709  
4710 /* The app opened a 101 stream handle from inside the handler
4711 * (hm_stream_open): the connection is a tunnel now, its bytes
4712 * belong to the handle both ways, and the triplet the handler
4713 * returned is the same sentinel a detach leaves behind. Parked for
4714 * the life of the handle - stream_close unparks it, and the close
4715 * that follows (keepalive is off) ends the tunnel. Bytes that came
4716 * in with the request are the handle's too, so they are handed
4717 * over rather than parsed as a request that will never come. */
4718 874 ▶ if (c->tunnel == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->tunnel == 2) { 6 868 874
4719 6 size_t consumed = bodystart + body_consumed;
4720 6 c->tunnel = 1;
4721 /*
4722 # uncoverable branch true class:ignore_covered_err
4723 # uncoverable condition left count:1 class:ignore_covered_err */
4724 6 ▶ if (env_rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) { 0 6 6
4725 0 hm_access_log(aTHX_ loop, env_rv, 101, -1); /* # uncoverable statement */
4726 0 SvREFCNT_dec(env_rv); /* # uncoverable statement */
4727 }
4728 /*
4729 # uncoverable branch false class:ignore_covered_err
4730 # uncoverable condition right count:1 class:ignore_covered_err */
4731 6 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 6 0 6
4732 6 memmove(c->rbuf, c->rbuf + consumed, c->rlen - consumed);
4733 6 c->rlen -= consumed;
4734 6 c->req_start = 0;
4735 6 c->nreqs++;
4736 6 loop->requests++;
4737 6 ▶ if (c->rlen) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen) { 5 1 6
4738 5 size_t n = c->rlen;
4739 5 c->rlen = 0;
4740 /*
4741 # uncoverable branch true class:ignore_covered_err
4742 # uncoverable condition left count:1 class:ignore_covered_err
4743 # uncoverable condition left count:2 class:ignore_covered_err
4744 # uncoverable condition right count:2 class:ignore_covered_err */
4745 5 ▶ if (!hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, n, 0)
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, n, 0) 0 5 5
4746 0 ▶ && loop->conns[c->fd] == c) /* # uncoverable statement class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
&& loop->conns[c->fd] == c) /* # uncoverable statement class:ignore_covered_err */ 0 0 0
4747 0 c->rlen = n; /* no read half yet: kept for it */ /* # uncoverable statement */
4748 }
4749 6 return;
4750 }
4751  
4752 868 size_t consumed = bodystart + body_consumed;
4753 868 memmove(c->rbuf, c->rbuf + consumed, c->rlen - consumed);
4754 868 c->rlen -= consumed;
4755 868 c->req_start = 0;
4756 868 c->body_phase = 0;
4757 868 c->chunk_pos = c->chunk_dec = 0;
4758 868 c->cont_sent = 0; /* the next request on this connection asks
4759 * for itself */
4760 868 served++;
4761 868 c->nreqs++;
4762 868 hm_count_request(loop);
4763  
4764 /* async: handler returned a Future -> park and wait; hold the
4765 * future so a client disconnect can cancel it */
4766 868 ▶ if (resp && hm_is_awaitable(aTHX_ resp)) {
Branch: 2 branches
BranchTrueFalseTotal
if (resp && hm_is_awaitable(aTHX_ resp)) { 865 3 868
if (resp && hm_is_awaitable(aTHX_ resp)) { 8 857 865
4767 8 c->awaiting = 1;
4768 8 c->resp_f = SvREFCNT_inc(resp);
4769 8 c->env_sv = env_rv; /* logged at delivery */
4770 8 hm_park(aTHX_ c, resp);
4771 8 SvREFCNT_dec(resp);
4772 /*
4773 # uncoverable branch true
4774 # uncoverable condition left count:1 class:ignore_covered_err */
4775 8 ▶ if (loop->conns[c->fd] != c) return; /* resolved + closed inline */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return; /* resolved + closed inline */ 0 8 8
4776 8 break;
4777 }
4778  
4779 /* psgi.streaming: coderef response -> park, hand it a responder */
4780 860 ▶ if (resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVCV) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVCV) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 857 3 860
if (resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVCV) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 857 0 857
if (resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVCV) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 40 817 857
4781 40 c->awaiting = 1;
4782 40 c->env_sv = env_rv; /* logged at respond time */
4783 40 hm_delayed(aTHX_ c, resp);
4784 40 SvREFCNT_dec(resp);
4785 40 ▶ if (loop->conns[c->fd] != c) return; /* responder ran + closed */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return; /* responder ran + closed */ 23 17 40
4786 17 break;
4787 }
4788  
4789 {
4790 820 int rc = hm_queue_response(aTHX_ c, resp);
4791 820 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 817 3 820
4792 /*
4793 # uncoverable branch true
4794 # uncoverable condition left count:1 class:ignore_covered_err
4795 # uncoverable condition left count:2 class:ignore_covered_err
4796 # uncoverable condition right count:2 class:ignore_covered_err */
4797 820 ▶ if (rc < 0) { if (env_rv) SvREFCNT_dec(env_rv); return; }
Branch: 2 branches
BranchTrueFalseTotal
if (rc < 0) { if (env_rv) SvREFCNT_dec(env_rv); return; } 0 820 820
if (rc < 0) { if (env_rv) SvREFCNT_dec(env_rv); return; } 0 0 0
4798 }
4799 820 ▶ if (env_rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) { 156 664 820
4800 156 hm_access_log(aTHX_ loop, env_rv, c->last_status, (ssize_t)c->last_blen);
4801 156 SvREFCNT_dec(env_rv);
4802 }
4803 820 ▶ if (!c->keepalive) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->keepalive) break; 667 153 820
4804 }
4805 932 ▶ if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 4 branches
BranchTrueFalseTotal
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 932 0 932
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 88 844 932
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 86 2 88
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 51 35 86
4806 51 c->req_start = loop->now;
4807 }
4808  
4809 /* A tunnel's bytes belong to its handle, not the request parser: hand over
4810 * whatever the read left in rbuf, or keep it when no read half is registered
4811 * yet. ONE function for both ways a read completes - readiness (hm_readable)
4812 * and completion (HM_EV_RECV) - because the completion path once had no
4813 * tunnel branch at all and fed the bytes to hm_process, where they sat as
4814 * the start of a request that never came. Every Linux box with liburing
4815 * takes that path by default, and macOS never does, so the six smokers that
4816 * failed t/41 were the first time it ran. Returns 0 when the callback closed
4817 * the connection. */
4818 7 static int hm_tunnel_bytes(pTHX_ hm_conn *c) {
4819 7 hm_loop *loop = c->loop;
4820 7 size_t have = c->rlen;
4821 7 c->rlen = 0;
4822 /*
4823 # uncoverable branch true class:ignore_covered_err
4824 # uncoverable condition left count:1 class:ignore_covered_err */
4825 7 ▶ if (!hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, have, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, have, 0)) { 0 7 7
4826 /*
4827 # uncoverable statement
4828 # uncoverable branch true
4829 # uncoverable branch false
4830 # uncoverable condition left count:1
4831 # uncoverable condition right count:1 */
4832 0 ▶ if (loop->conns[c->fd] != c) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return 0; 0 0 0
4833 0 c->rlen = have; /* no read half yet: kept for it */ /* # uncoverable statement */
4834 }
4835 7 return loop->conns[c->fd] == c;
4836 }
4837  
4838 /* Stop and restart reading a connection whose buffer is full while a frame
4839 * on the stack still holds pointers into it (hm_readable, below). The
4840 * watcher is persistent and level-triggered, so leaving the bytes in the
4841 * socket without this would wake the loop every turn until the frame
4842 * returned. Readiness mode only: a completion-mode read is armed from the
4843 * top of a loop turn (hm_run_again), never from under a frame. */
4844 37 static void hm_read_pause(hm_loop *loop, hm_conn *c) {
4845 /*
4846 # uncoverable branch true
4847 # uncoverable condition left count:1 class:ignore_covered_err */
4848 37 ▶ if (c->read_paused) return;
Branch: 1 branch
BranchTrueFalseTotal
if (c->read_paused) return; 0 37 37
4849 37 c->read_paused = 1;
4850 37 loop->be->remove_io(loop->be, c->fd, HM_EV_READ);
4851 }
4852 915 static void hm_read_resume(hm_loop *loop, hm_conn *c) {
4853 915 ▶ if (!c->read_paused) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->read_paused) return; 878 37 915
4854 37 c->read_paused = 0;
4855 37 loop->be->add_io(loop->be, c->fd, HM_EV_READ, 0);
4856 }
4857  
4858 1083 static void hm_readable(pTHX_ hm_conn *c) {
4859 1083 hm_loop *loop = c->loop;
4860 96 for (;;) {
4861 1179 ▶ if (c->rlen == c->rcap) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen == c->rcap) { 40 1139 1179
4862 /* A synchronous handler on the stack (in_app) may be nghttp2
4863 * reading frames out of this very buffer, or hm_process holding
4864 * offsets into it: growing it here would move it from under
4865 * them. Leave the rest in the socket until that frame returns. */
4866 /*
4867 # uncoverable branch true class:ignore_covered_err
4868 # uncoverable condition left count:1 class:ignore_covered_err
4869 # uncoverable condition left count:2 class:ignore_covered_err
4870 # uncoverable condition right count:2 class:ignore_covered_err */
4871 40 ▶ if (c->in_app && !hm_h2_reentrant(c)) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->in_app && !hm_h2_reentrant(c)) { 0 40 40
if (c->in_app && !hm_h2_reentrant(c)) { 0 0 0
4872 0 hm_read_pause(loop, c); /* # uncoverable statement */
4873 0 break; /* # uncoverable statement */
4874 }
4875 /* HTTP/2: the buffer holds frames, not a request, and nghttp2
4876 * parses them incrementally - a frame larger than the buffer is
4877 * consumed across reads. Hand over what is here and let the
4878 * level-triggered watcher bring the rest. The request ceiling
4879 * is per stream there (hm_h2_cb_data_chunk); applied to this
4880 * buffer it closed every upload over 16KB on a server whose
4881 * max_body was below that. */
4882 40 ▶ if (c->h2) break;
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) break; 0 40 40
4883 /* The same, one read earlier: the preface is in the buffer but
4884 * hm_process has not run to detect it. Let it. */
4885 40 ▶ if (hm_h2_preface_pending(c)) break;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_h2_preface_pending(c)) break; 0 40 40
4886 /* grow for large bodies; unbounded headers are rejected */
4887 /*
4888 # uncoverable condition left count:2 class:ignore_covered_err
4889 # uncoverable condition left count:3 class:ignore_covered_err */
4890 40 ▶ if (c->rcap >= loop->max_read
Branch: 1 branch
BranchTrueFalseTotal
if (c->rcap >= loop->max_read 39 1 40
4891 39 ▶ || (c->rlen >= 65536 && !hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4))) {
Branch: 2 branches
BranchTrueFalseTotal
|| (c->rlen >= 65536 && !hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4))) { 27 12 39
|| (c->rlen >= 65536 && !hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4))) { 0 27 27
4892 /* The buffer is full and may not grow. Until max_body was
4893 * configurable this only happened to a genuinely enormous
4894 * request and a bare close was defensible; now that an
4895 * operator can set the ceiling BELOW the initial buffer
4896 * (HM_RBUF, 16KB), it is the ordinary way an oversize
4897 * request ends - and dropping the connection with no
4898 * response at all would leave every such client staring at
4899 * a timeout rather than a 413. Answer, then close.
4900 *
4901 * Only for a request that at least has a complete header
4902 * block: without one this is a client streaming garbage,
4903 * which has earned nothing but the close it used to get. */
4904 /*
4905 # uncoverable branch false class:ignore_covered_err
4906 # uncoverable condition right count:1 class:ignore_covered_err
4907 # uncoverable condition right count:2 class:ignore_covered_err */
4908 1 ▶ if (c->rcap >= loop->max_read
Branch: 1 branch
BranchTrueFalseTotal
if (c->rcap >= loop->max_read 1 0 1
4909 1 ▶ && hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4)) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4)) { 1 0 1
4910 static const char e413[] =
4911 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4912 "Connection: close\r\n\r\n";
4913 1 hm_wb_put(c, e413, sizeof(e413) - 1);
4914 1 c->keepalive = 0;
4915 1 c->last_status = 413;
4916 1 c->last_blen = 0;
4917 1 (void)hm_flush(aTHX_ c);
4918 /*
4919 # uncoverable branch false
4920 # uncoverable condition right count:1 class:ignore_covered_err */
4921 1 ▶ if (loop->conns[c->fd] != c) return; /* flush closed it */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return; /* flush closed it */ 1 0 1
4922 }
4923 0 hm_close(aTHX_ loop, c); /* # uncoverable statement */
4924 0 return; /* # uncoverable statement */
4925 }
4926 {
4927 39 size_t ncap = c->rcap * 2; /* # uncoverable statement class:ignore_covered_err */
4928 /*
4929 # uncoverable statement class:ignore_covered_err
4930 # uncoverable branch true
4931 # uncoverable condition left count:1 */
4932 39 ▶ if (ncap > loop->max_read) ncap = loop->max_read;
Branch: 1 branch
BranchTrueFalseTotal
if (ncap > loop->max_read) ncap = loop->max_read; 0 39 39
4933 39 c->rbuf = (char *)hm_xrealloc(c->rbuf, ncap);
4934 39 c->rcap = ncap;
4935 }
4936 }
4937 1178 size_t want = c->rcap - c->rlen;
4938 1178 ssize_t n = hm_cread(c, c->rbuf + c->rlen, want);
4939 1178 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 1003 175 1178
4940 1003 c->rlen += (size_t)n;
4941 1003 c->last_rx = loop->now;
4942 1003 c->body_rx += (UV)n;
4943 /* A tunnel (a 101 stream handle): the bytes are the handle's,
4944 * not a request. Handed up read by read, so the buffer never
4945 * grows toward the ceiling that ends an oversize request. The
4946 * callback may close the stream and with it the connection.
4947 * Only once SETTLED (1): at 2 the request line is still in
4948 * rbuf and the hm_process frame that opened the tunnel owns the
4949 * buffer, so the bytes wait for it (it hands them over itself). */
4950 /*
4951 # uncoverable branch true class:ignore_covered_err
4952 # uncoverable condition left count:1 class:ignore_covered_err
4953 # uncoverable condition left count:2 class:ignore_covered_err */
4954 1003 ▶ if (c->tunnel == 1 && !hm_tunnel_bytes(aTHX_ c)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (c->tunnel == 1 && !hm_tunnel_bytes(aTHX_ c)) return; 7 996 1003
if (c->tunnel == 1 && !hm_tunnel_bytes(aTHX_ c)) return; 0 7 7
4955 /* A SHORT read means the socket buffer is drained: the kernel
4956 * handed over everything it had, so the confirming read that
4957 * would follow can only return EAGAIN. Stopping here removes ONE
4958 * SYSCALL FROM EVERY REQUEST - measured, an ordinary keep-alive
4959 * request cost three (two reads and a writev) and the second read
4960 * was always the empty one.
4961 *
4962 * Safe because the backends are LEVEL-triggered - no EV_CLEAR, no
4963 * EPOLLET. Draining to EAGAIN is an edge-triggered obligation,
4964 * and under level triggering anything that arrived between the
4965 * read and this line simply reports the fd readable again on the
4966 * next turn of the loop. Nothing is lost, and nothing stalls.
4967 *
4968 * NOT for TLS: a short SSL_read says nothing about the socket,
4969 * because the engine may hold more plaintext than it just
4970 * returned, and stopping on it would leave that sitting in the
4971 * engine until the peer happened to send again. */
4972 1003 ▶ if (!c->ssl && (size_t)n < want) {
Branch: 2 branches
BranchTrueFalseTotal
if (!c->ssl && (size_t)n < want) { 947 56 1003
if (!c->ssl && (size_t)n < want) { 907 40 947
4973 /* The disarm the EAGAIN branch below would have done. A write
4974 * watcher left armed over an empty write buffer re-fires
4975 * every turn and spins the worker at 100% CPU. */
4976 /*
4977 # uncoverable branch true class:ignore_covered_err
4978 # uncoverable condition left count:1 class:ignore_covered_err
4979 # uncoverable condition left count:2 class:ignore_covered_err */
4980 907 ▶ if (c->writing && c->woff == c->wlen) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->writing && c->woff == c->wlen) { 0 907 907
if (c->writing && c->woff == c->wlen) { 0 0 0
4981 0 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE); /* # uncoverable statement */
4982 0 c->writing = 0; /* # uncoverable statement */
4983 }
4984 907 break;
4985 }
4986 175 ▶ } else if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (n == 0) { 124 51 175
4987 /* The peer half-closed a tunnel: the same thing a zero read
4988 * means to a socket owner, told to the handle as fin before
4989 * the connection goes and the abort callback says the rest. */
4990 /*
4991 # uncoverable branch true class:ignore_covered_err
4992 # uncoverable condition left count:1 class:ignore_covered_err */
4993 124 ▶ if (c->tunnel) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->tunnel) { 0 124 124
4994 0 (void)hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, 0, 1); /* # uncoverable statement */
4995 /*
4996 # uncoverable statement
4997 # uncoverable branch true
4998 # uncoverable branch false
4999 # uncoverable condition left count:1
5000 # uncoverable condition right count:1 */
5001 0 ▶ if (loop->conns[c->fd] != c) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return; 0 0 0
5002 }
5003 124 hm_close(aTHX_ loop, c);
5004 124 return;
5005 51 ▶ } else if (errno == EAGAIN || errno == EWOULDBLOCK) { /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
} else if (errno == EAGAIN || errno == EWOULDBLOCK) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 51 51
} else if (errno == EAGAIN || errno == EWOULDBLOCK) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 0 0
5006 /* TLS read blocked wanting writable: arm a write watcher so a
5007 * write-readiness event re-drives us. Once it unblocks, drop that
5008 * watcher again unless there is queued output still waiting on
5009 * it. The backends are level-triggered, so a watcher left armed
5010 * over an empty write buffer is not merely untidy - it re-fires
5011 * every turn of the loop and spins the worker at 100% CPU. */
5012 /*
5013 # uncoverable branch true
5014 # uncoverable condition left count:1 class:ignore_covered_err */
5015 51 ▶ if (c->tls_r_wants_w) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->tls_r_wants_w) { 0 51 51
5016 /*
5017 # uncoverable statement
5018 # uncoverable branch true
5019 # uncoverable branch false
5020 # uncoverable condition left count:1
5021 # uncoverable condition right count:1 */
5022 0 ▶ if (!c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->writing) { 0 0 0
5023 0 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0); /* # uncoverable statement */
5024 0 c->writing = 1; /* # uncoverable statement */
5025 }
5026 /*
5027 # uncoverable branch true class:ignore_covered_err
5028 # uncoverable condition left count:1 class:ignore_covered_err
5029 # uncoverable condition left count:2 class:ignore_covered_err
5030 # uncoverable condition right count:2 class:ignore_covered_err */
5031 51 ▶ } else if (c->writing && c->woff == c->wlen) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (c->writing && c->woff == c->wlen) { 0 51 51
} else if (c->writing && c->woff == c->wlen) { 0 0 0
5032 0 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE); /* # uncoverable statement */
5033 0 c->writing = 0; /* # uncoverable statement */
5034 }
5035 51 break;
5036 } else {
5037 0 hm_close(aTHX_ loop, c);
5038 0 return;
5039 }
5040 }
5041 958 hm_lru_touch(loop, c);
5042 /* A tunnel carries no requests. A connection whose synchronous handler
5043 * is on the stack (its ->get pumped this loop) keeps the new bytes in
5044 * rbuf for the hm_process frame already running on it: a second frame
5045 * would consume the pipeline from under the first one's offsets. */
5046 /* HTTP/2 is the exception once nghttp2 has returned: a handler waiting
5047 * for its body to drain is waiting for the window updates in these very
5048 * bytes, and hm_h2_input takes them without starting another request. */
5049 958 ▶ if (!c->tunnel && (!c->in_app || hm_h2_reentrant(c))) hm_process(aTHX_ c);
Branch: 3 branches
BranchTrueFalseTotal
if (!c->tunnel && (!c->in_app || hm_h2_reentrant(c))) hm_process(aTHX_ c); 949 9 958
if (!c->tunnel && (!c->in_app || hm_h2_reentrant(c))) hm_process(aTHX_ c); 2 947 949
if (!c->tunnel && (!c->in_app || hm_h2_reentrant(c))) hm_process(aTHX_ c); 0 2 2
5050 958 ▶ if (loop->conns[c->fd] == c) hm_flush(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] == c) hm_flush(aTHX_ c); 930 28 958
5051 }
5052  
5053 static hm_tw *hm_add_timer_watch_c(hm_loop *loop, double secs,
5054 hm_abi_timer_cb cb, void *ud);
5055 static void hm_tls_handshake(pTHX_ hm_conn *c);
5056  
5057 /* The first bytes on a proxy_protocol listener. PEEK, so the header can be
5058 * parsed without taking anything behind it off the socket: a ClientHello or
5059 * an h2 preface in the same segment stays in the kernel for hm_tls_wrap and
5060 * hm_h2_detect, which then run exactly as on a listener without a proxy.
5061 * Only a complete header is consumed, by a read of exactly its length. A
5062 * partial one is re-peeked when the level-triggered watcher fires again;
5063 * one that never completes is closed by hm_sweep after header_timeout. */
5064 /* A partial PROXY header: the bytes stay in the socket (peeked, not read)
5065 * and the watcher is level-triggered, so returning to the loop would wake
5066 * it again at once - a peer that sent "PROXY TCP4 1" and stopped had the
5067 * worker re-peeking at 100% CPU until header_timeout. Reading is paused
5068 * and resumed by this timer; the sweep still closes a header that never
5069 * completes. */
5070 typedef struct { hm_loop *loop; int fd; UV id; } hm_pp_retry;
5071 37 static void hm_proxy_retry(pTHX_ void *ud) {
5072 37 hm_pp_retry *r = (hm_pp_retry *)ud;
5073 /*
5074 # uncoverable condition right count:1 class:ignore_covered_err
5075 # uncoverable condition right count:2 class:ignore_covered_err */
5076 37 ▶ hm_conn *c = (r->fd >= 0 && r->fd < HM_MAXFD) ? r->loop->conns[r->fd] : NULL;
Branch: 2 branches
BranchTrueFalseTotal
hm_conn *c = (r->fd >= 0 && r->fd < HM_MAXFD) ? r->loop->conns[r->fd] : NULL; 37 0 37
hm_conn *c = (r->fd >= 0 && r->fd < HM_MAXFD) ? r->loop->conns[r->fd] : NULL; 37 0 37
5077 PERL_UNUSED_CONTEXT;
5078 /*
5079 # uncoverable branch false class:ignore_covered_err
5080 # uncoverable condition right count:1 class:ignore_covered_err
5081 # uncoverable condition right count:2 class:ignore_covered_err
5082 # uncoverable condition right count:3 class:ignore_covered_err */
5083 37 ▶ if (c && c->id == r->id && c->pp_wait) hm_read_resume(r->loop, c);
Branch: 3 branches
BranchTrueFalseTotal
if (c && c->id == r->id && c->pp_wait) hm_read_resume(r->loop, c); 37 0 37
if (c && c->id == r->id && c->pp_wait) hm_read_resume(r->loop, c); 37 0 37
if (c && c->id == r->id && c->pp_wait) hm_read_resume(r->loop, c); 37 0 37
5084 37 free(r);
5085 37 }
5086  
5087 50 static void hm_proxy_readable(pTHX_ hm_conn *c) {
5088 50 hm_loop *loop = c->loop;
5089 unsigned char buf[HM_PP_MAX];
5090 hm_pp_result r;
5091 ssize_t n;
5092 long len;
5093 50 n = hm_os_recv_peek(c->fd, buf, sizeof(buf));
5094 /*
5095 # uncoverable branch true class:ignore_covered_err
5096 # uncoverable condition left count:1 class:ignore_covered_err */
5097 90 ▶ if (n == 0) { hm_close(aTHX_ loop, c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { hm_close(aTHX_ loop, c); return; } 0 50 50
5098 /*
5099 # uncoverable branch true
5100 # uncoverable condition left count:1 class:ignore_covered_err */
5101 50 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 0 50 50
5102 /*
5103 # uncoverable statement
5104 # uncoverable branch true
5105 # uncoverable branch false
5106 # uncoverable condition left count:1
5107 # uncoverable condition right count:1
5108 # uncoverable condition left count:2
5109 # uncoverable condition right count:2
5110 # uncoverable condition left count:3
5111 # uncoverable condition right count:3 */
5112 0 ▶ if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return;
Branch: 3 branches
BranchTrueFalseTotal
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return; 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return; 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return; 0 0 0
5113 0 hm_close(aTHX_ loop, c); return; /* # uncoverable statement */
5114 }
5115 50 len = hm_pp_parse(buf, (size_t)n, &r);
5116 50 ▶ if (len == 0) { /* more to come */
Branch: 1 branch
BranchTrueFalseTotal
if (len == 0) { /* more to come */ 37 13 50
5117 hm_pp_retry *rt;
5118 /*
5119 # uncoverable branch true
5120 # uncoverable condition left count:1 class:ignore_covered_err */
5121 37 ▶ if ((size_t)n >= sizeof(buf)) { hm_close(aTHX_ loop, c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if ((size_t)n >= sizeof(buf)) { hm_close(aTHX_ loop, c); return; } 0 37 37
5122 37 rt = (hm_pp_retry *)hm_xmalloc(sizeof(*rt));
5123 37 rt->loop = loop; rt->fd = c->fd; rt->id = c->id;
5124 37 hm_read_pause(loop, c);
5125 /*
5126 # uncoverable branch true class:ignore_covered_err
5127 # uncoverable condition left count:1 class:ignore_covered_err */
5128 37 ▶ if (!hm_add_timer_watch_c(loop, 0.05, hm_proxy_retry, rt)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_add_timer_watch_c(loop, 0.05, hm_proxy_retry, rt)) { 0 37 37
5129 0 free(rt); /* no timer: level-triggered it is */ /* # uncoverable statement */
5130 0 hm_read_resume(loop, c); /* # uncoverable statement */
5131 }
5132 37 return;
5133 }
5134 13 ▶ if (len < 0) { hm_close(aTHX_ loop, c); return; } /* not a PROXY header */
Branch: 1 branch
BranchTrueFalseTotal
if (len < 0) { hm_close(aTHX_ loop, c); return; } /* not a PROXY header */ 2 11 13
5135 /* take exactly the header; what follows is the client's first bytes */
5136 {
5137 11 ssize_t got = hm_os_recv(c->fd, buf, (size_t)len);
5138 /*
5139 # uncoverable branch true
5140 # uncoverable condition left count:1 class:ignore_covered_err */
5141 11 ▶ if (got != len) { hm_close(aTHX_ loop, c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (got != len) { hm_close(aTHX_ loop, c); return; } 0 11 11
5142 }
5143 11 c->pp_wait = 0;
5144 11 c->req_start = 0;
5145 /* The proxy's own address is kept for $env; the client's replaces the
5146 * peer, so REMOTE_ADDR, the access log, the rate limiter and the
5147 * denylist all see the client from here on. */
5148 11 memcpy(c->proxy_addr, c->peer, sizeof(c->proxy_addr));
5149 11 c->proxy_port = c->peer_port;
5150 11 ▶ if (r.family) {
Branch: 1 branch
BranchTrueFalseTotal
if (r.family) { 9 2 11
5151 static const unsigned char v4map[12] =
5152 { 0,0,0,0, 0,0,0,0, 0,0,0xff,0xff };
5153 9 c->peer[0] = '\0';
5154 /* ::ffff:a.b.c.d is the IPv4 client it names (see hm_fmt_peer) */
5155 9 ▶ if (r.family == AF_INET6 && memcmp(r.src, v4map, 12) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (r.family == AF_INET6 && memcmp(r.src, v4map, 12) == 0) 3 6 9
if (r.family == AF_INET6 && memcmp(r.src, v4map, 12) == 0) 1 2 3
5156 1 (void)inet_ntop(AF_INET, (const unsigned char *)r.src + 12,
5157 1 c->peer, (socklen_t)sizeof(c->peer));
5158 else
5159 8 (void)inet_ntop(r.family, r.src, c->peer, (socklen_t)sizeof(c->peer));
5160 9 c->peer_port = r.src_port;
5161 /* the denylist, again, now for the real client; the accept-time
5162 * check saw the proxy */
5163 9 ▶ if (hm_sa_deny_check(c->peer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_deny_check(c->peer)) { 1 8 9
5164 1 loop->denied++;
5165 1 hm_close(aTHX_ loop, c);
5166 1 return;
5167 }
5168 }
5169 /* distinct clients counts clients, not proxies, so the accept path
5170 * skipped it on this listener */
5171 /*
5172 # uncoverable branch true class:ignore_covered_err
5173 # uncoverable condition left count:1 class:ignore_covered_err
5174 # uncoverable condition left count:2 class:ignore_covered_err
5175 # uncoverable condition right count:2 class:ignore_covered_err */
5176 10 ▶ if (hm_sa_hll && c->peer[0]) hm_sa_hll_add(c->peer);
Branch: 2 branches
BranchTrueFalseTotal
if (hm_sa_hll && c->peer[0]) hm_sa_hll_add(c->peer); 0 10 10
if (hm_sa_hll && c->peer[0]) hm_sa_hll_add(c->peer); 0 0 0
5177 10 ▶ if (c->lst && c->lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (c->lst && c->lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 10 0 10
if (c->lst && c->lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 9 10
5178 1 hm_tls_wrap(c, c->lst->tls_ctx);
5179 1 hm_tls_handshake(aTHX_ c);
5180 } else {
5181 9 hm_readable(aTHX_ c);
5182 }
5183 }
5184  
5185 /* accept(2) failed for want of a descriptor. The listener is level-readable
5186 * and stays so, so simply returning would wake the loop again at once and
5187 * spin the worker at 100% CPU until the table had room. Reclaim an idle
5188 * keep-alive connection when there is one; otherwise stop listening for a
5189 * tenth of a second and come back. */
5190 /* Listeners whose starvation timer could not be armed (hm_accept_starved):
5191 * re-added from the top of a loop turn. */
5192 /*
5193 # uncoverable statement class:ignore_covered_err
5194 # uncoverable subroutine class:ignore_covered_err */
5195 26510 static void hm_accept_unstarve(hm_loop *loop) {
5196 int i;
5197 26510 loop->starved_retry = 0; /* # uncoverable statement class:ignore_covered_err */
5198 /*
5199 # uncoverable statement class:ignore_covered_err
5200 # uncoverable branch true class:ignore_covered_err
5201 # uncoverable branch false class:ignore_covered_err */
5202 53020 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 26510 26510 53020
5203 26510 hm_listener *l = &loop->listeners[i]; /* # uncoverable statement class:ignore_covered_err */
5204 /*
5205 # uncoverable statement class:ignore_covered_err
5206 # uncoverable branch true class:ignore_covered_err
5207 # uncoverable branch false class:ignore_covered_err
5208 # uncoverable condition left count:1 */
5209 26510 ▶ if (l->starved != 2) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (l->starved != 2) continue; 0 26510 26510
5210 26510 l->starved = 0; /* # uncoverable statement class:ignore_covered_err */
5211 /*
5212 # uncoverable statement class:ignore_covered_err
5213 # uncoverable branch false
5214 # uncoverable condition right count:1
5215 # uncoverable condition right count:2 */
5216 26510 ▶ if (!loop->stopping && l->fd >= 0)
Branch: 2 branches
BranchTrueFalseTotal
if (!loop->stopping && l->fd >= 0) 26510 0 26510
if (!loop->stopping && l->fd >= 0) 26510 0 26510
5217 26510 loop->be->add_io(loop->be, l->fd, HM_EV_READ, 0); /* # uncoverable statement class:ignore_covered_err */
5218 }
5219 26510 }
5220  
5221 typedef struct { hm_loop *loop; hm_listener *lst; } hm_starve;
5222 /*
5223 # uncoverable statement class:ignore_covered_err
5224 # uncoverable subroutine class:ignore_covered_err */
5225 0 static void hm_accept_rearm(pTHX_ void *ud) {
5226 0 hm_starve *s = (hm_starve *)ud; /* # uncoverable statement class:ignore_covered_err */
5227 0 s->lst->starved = 0; /* # uncoverable statement class:ignore_covered_err */
5228 /*
5229 # uncoverable statement class:ignore_covered_err
5230 # uncoverable branch true class:ignore_covered_err
5231 # uncoverable branch false class:ignore_covered_err
5232 # uncoverable condition left count:1 class:ignore_covered_err
5233 # uncoverable condition right count:1 class:ignore_covered_err
5234 # uncoverable condition left count:2 class:ignore_covered_err
5235 # uncoverable condition right count:2 class:ignore_covered_err */
5236 0 ▶ if (!s->loop->stopping && s->lst->fd >= 0)
Branch: 2 branches
BranchTrueFalseTotal
if (!s->loop->stopping && s->lst->fd >= 0) 0 0 0
if (!s->loop->stopping && s->lst->fd >= 0) 0 0 0
5237 0 s->loop->be->add_io(s->loop->be, s->lst->fd, HM_EV_READ, 0); /* # uncoverable statement class:ignore_covered_err */
5238 0 free(s); /* # uncoverable statement class:ignore_covered_err */
5239 0 }
5240 26570 static void hm_accept_starved(pTHX_ hm_loop *loop, hm_listener *lst) {
5241 26570 hm_conn *c = loop->lru_head; /* oldest activity first */
5242 848380 ▶ while (c) {
Branch: 1 branch
BranchTrueFalseTotal
while (c) { 821870 26510 848380
5243 /*
5244 # uncoverable condition right count:1 class:ignore_covered_err
5245 # uncoverable condition right count:2 class:ignore_covered_err
5246 # uncoverable condition right count:3 class:ignore_covered_err
5247 # uncoverable condition right count:4 class:ignore_covered_err
5248 # uncoverable condition right count:5 class:ignore_covered_err
5249 # uncoverable condition right count:6 class:ignore_covered_err
5250 # uncoverable condition right count:7 class:ignore_covered_err
5251 # uncoverable condition right count:8 class:ignore_covered_err */
5252 821870 ▶ if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs
Branch: 5 branches
BranchTrueFalseTotal
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 821870 0 821870
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 821870 0 821870
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 821870 0 821870
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 821870 0 821870
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 821870 0 821870
5253 821870 ▶ && c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind
Branch: 3 branches
BranchTrueFalseTotal
&& c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind 821870 0 821870
&& c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind 821870 0 821870
&& c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind 821870 0 821870
5254 821870 ▶ && c->nreqs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& c->nreqs > 0) { 60 821810 821870
5255 60 hm_close(aTHX_ loop, c);
5256 60 return;
5257 }
5258 821810 c = c->lru_next;
5259 }
5260 /*
5261 # uncoverable branch true
5262 # uncoverable condition left count:1 class:ignore_covered_err */
5263 26510 ▶ if (lst->starved) return;
Branch: 1 branch
BranchTrueFalseTotal
if (lst->starved) return; 0 26510 26510
5264 {
5265 26510 hm_starve *s = (hm_starve *)hm_xmalloc(sizeof(*s));
5266 26510 s->loop = loop;
5267 26510 s->lst = lst;
5268 26510 lst->starved = 1;
5269 26510 loop->be->remove_io(loop->be, lst->fd, HM_EV_READ);
5270 /*
5271 # uncoverable branch false class:ignore_covered_err
5272 # uncoverable condition right count:1 class:ignore_covered_err */
5273 26510 ▶ if (!hm_add_timer_watch_c(loop, 0.1, hm_accept_rearm, s)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_add_timer_watch_c(loop, 0.1, hm_accept_rearm, s)) { 26510 0 26510
5274 /* No timer to be had: on epoll a timer IS a descriptor, and
5275 * this is the descriptor famine. Re-added from the top of a
5276 * later loop turn instead (hm_accept_unstarve) - the next close
5277 * wakes the loop, and the interval sweep does within five
5278 * seconds regardless. Before this the listener stayed removed
5279 * and the worker never accepted again. */
5280 26510 free(s); /* # uncoverable statement class:ignore_covered_err */
5281 26510 lst->starved = 2; /* # uncoverable statement class:ignore_covered_err */
5282 26510 loop->starved_retry = 1; /* # uncoverable statement class:ignore_covered_err */
5283 }
5284 }
5285 }
5286  
5287 27644 static void hm_accept(pTHX_ hm_loop *loop, hm_listener *lst) {
5288 27644 int batch = 0;
5289 /*
5290 # uncoverable branch true class:ignore_covered_err
5291 # uncoverable condition left count:1 class:ignore_covered_err */
5292 27644 ▶ if (loop->stopping) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stopping) return; 0 27644 27644
5293 935 for (;;) {
5294 struct sockaddr_storage ss;
5295 28579 socklen_t slen = sizeof(ss);
5296 hm_conn *c;
5297 char peer[INET6_ADDRSTRLEN];
5298 int peer_port;
5299 #ifdef HM_HAVE_ACCEPT4
5300 /* Non-blocking and close-on-exec in the accept itself: two fewer
5301 * syscalls per connection, and no window in which a fork from a
5302 * handler inherits a client socket. */
5303 28579 int fd = accept4(lst->fd, (struct sockaddr *)&ss, &slen,
5304 SOCK_NONBLOCK | SOCK_CLOEXEC);
5305 #else
5306 int fd = hm_os_accept(lst->fd, (struct sockaddr *)&ss, &slen);
5307 #endif
5308 28579 ▶ if (fd < 0) { /* EAGAIN: drained */
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { /* EAGAIN: drained */ 27644 935 28579
5309 27644 ▶ if (errno == EMFILE || errno == ENFILE) /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (errno == EMFILE || errno == ENFILE) /* # uncoverable condition left count:2 class:ignore_covered_err */ 1074 26570 27644
if (errno == EMFILE || errno == ENFILE) /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 1074 1074
5310 26570 hm_accept_starved(aTHX_ loop, lst);
5311 27644 break;
5312 }
5313 /*
5314 # uncoverable branch true class:ignore_covered_err
5315 # uncoverable condition left count:1 class:ignore_covered_err */
5316 936 ▶ if (fd >= HM_MAXFD) { hm_os_close(fd); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= HM_MAXFD) { hm_os_close(fd); continue; } 0 935 935
5317 #if !defined(HM_HAVE_ACCEPT4) && !defined(_WIN32)
5318 /* Not into anything the application execs: a child that kept a
5319 * client socket open held the client past the response, and could
5320 * write onto it (onto a TLS socket, raw). hm_new_conn sets
5321 * non-blocking. */
5322 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
5323 #endif
5324 /* Denylist: format the peer and drop a blocked IP HERE, before a
5325 * connection object is allocated or a byte is read - the cheapest
5326 * possible rejection. Fails open (no arena -> deny_check is 0). */
5327 935 hm_fmt_peer(peer, sizeof(peer), &peer_port, (struct sockaddr *)&ss);
5328 935 ▶ if (hm_sa_deny_check(peer)) { hm_os_close(fd); loop->denied++; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_deny_check(peer)) { hm_os_close(fd); loop->denied++; continue; } 1 934 935
5329 /* Distinct clients, opt-in: with the sketch off this is one load of
5330 * a NULL, with it on a hash and a CAS-max on the peer string. */
5331 /*
5332 # uncoverable condition right count:2 class:ignore_covered_err
5333 # uncoverable condition right count:3 class:ignore_covered_err */
5334 934 ▶ if (hm_sa_hll && peer[0] && !lst->proxy_protocol) hm_sa_hll_add(peer);
Branch: 3 branches
BranchTrueFalseTotal
if (hm_sa_hll && peer[0] && !lst->proxy_protocol) hm_sa_hll_add(peer); 212 722 934
if (hm_sa_hll && peer[0] && !lst->proxy_protocol) hm_sa_hll_add(peer); 212 0 212
if (hm_sa_hll && peer[0] && !lst->proxy_protocol) hm_sa_hll_add(peer); 212 0 212
5335 934 c = hm_new_conn(loop, fd, lst);
5336 934 memcpy(c->peer, peer, sizeof(c->peer));
5337 934 c->peer_port = peer_port;
5338 934 loop->accepts++;
5339 /*
5340 # uncoverable branch true
5341 # uncoverable condition left count:1 class:ignore_covered_err */
5342 934 ▶ if (c->tls_failed) { hm_close(aTHX_ loop, c); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->tls_failed) { hm_close(aTHX_ loop, c); continue; } 0 934 934
5343 /* fairness: don't grab the whole queue in one wakeup; the listener
5344 * stays level-readable, so the next iteration resumes */
5345 /*
5346 # uncoverable branch true
5347 # uncoverable condition left count:1 class:ignore_covered_err */
5348 934 ▶ if (++batch >= 64) break;
Branch: 1 branch
BranchTrueFalseTotal
if (++batch >= 64) break; 0 934 934
5349 }
5350 }
5351  
5352 /* Drive the TLS handshake for a connection still in SSL_accept. On success,
5353 * switch to HTTP/2 if ALPN negotiated h2, then start serving. WANT_READ waits
5354 * on the always-armed read watcher; WANT_WRITE arms a write watcher. */
5355 117 static void hm_tls_handshake(pTHX_ hm_conn *c) {
5356 #ifdef HM_HAVE_OPENSSL
5357 117 hm_loop *loop = c->loop;
5358 117 SSL *ssl = (SSL *)c->ssl;
5359 int r;
5360 117 ERR_clear_error();
5361 117 r = SSL_accept(ssl);
5362 117 ▶ if (r == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (r == 1) { 54 63 117
5363 54 c->tls_hs = 0;
5364 54 hm_tls_capture_peer(c); /* protocol/cipher + any client cert */
5365 /* What the kernel took, for stats and tests. The write paths do NOT
5366 * read this - they ask OpenSSL again each time, because the answer
5367 * can change under them (see hm_ktls_tx). */
5368 54 c->ktls_tx = hm_ktls_tx(c) ? 1 : 0;
5369 /*
5370 # uncoverable branch true class:ignore_covered_err
5371 # uncoverable condition left count:1 class:ignore_covered_err */
5372 54 ▶ if (c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->writing) { 0 54 54
5373 0 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE); /* # uncoverable statement */
5374 0 c->writing = 0; /* # uncoverable statement */
5375 }
5376 #ifdef HM_HAVE_NGHTTP2
5377 if (c->lst && c->lst->http2) { /* # uncoverable condition right count:1 class:ignore_covered_err */
5378 const unsigned char *proto = NULL;
5379 unsigned int plen = 0;
5380 SSL_get0_alpn_selected(ssl, &proto, &plen);
5381 /*
5382 # uncoverable branch true class:ignore_covered_err
5383 # uncoverable condition left count:1 class:ignore_covered_err
5384 # uncoverable condition left count:2 class:ignore_covered_err
5385 # uncoverable condition right count:2 class:ignore_covered_err
5386 # uncoverable condition left count:3 class:ignore_covered_err */
5387 if (plen == 2 && memcmp(proto, "h2", 2) == 0
5388 && hm_h2_start(aTHX_ c) < 0) {
5389 hm_close(aTHX_ loop, c); /* # uncoverable statement */
5390 return; /* # uncoverable statement */
5391 }
5392 }
5393 #endif
5394 54 hm_readable(aTHX_ c); /* any early app data is already buffered */
5395 54 return;
5396 }
5397 {
5398 63 int e = SSL_get_error(ssl, r);
5399 63 ▶ if (e == SSL_ERROR_WANT_READ) return; /* read watcher armed */
Branch: 1 branch
BranchTrueFalseTotal
if (e == SSL_ERROR_WANT_READ) return; /* read watcher armed */ 56 7 63
5400 /*
5401 # uncoverable branch true
5402 # uncoverable condition left count:1 class:ignore_covered_err */
5403 7 ▶ if (e == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (e == SSL_ERROR_WANT_WRITE) { 0 7 7
5404 /*
5405 # uncoverable statement
5406 # uncoverable branch true
5407 # uncoverable branch false
5408 # uncoverable condition left count:1
5409 # uncoverable condition right count:1 */
5410 0 ▶ if (!c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->writing) { 0 0 0
5411 0 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0); /* # uncoverable statement */
5412 0 c->writing = 1; /* # uncoverable statement */
5413 }
5414 0 return; /* # uncoverable statement */
5415 }
5416 7 hm_close(aTHX_ loop, c); /* handshake failed */
5417 }
5418 #else
5419 (void)c;
5420 #endif
5421 }
5422  
5423 /* ---- timeouts, shutdown, loop -------------------------------------------- */
5424  
5425 /* Resolve an app io-readiness Future (fd became readable/writable), or run
5426 * a persistent watch_io callback. */
5427 22 static void hm_io_event(pTHX_ hm_loop *loop, int fd, int mask, hm_iow *slot) {
5428 22 SV *sv = slot->sv;
5429 PERL_UNUSED_VAR(loop);
5430 22 ▶ if (slot->c_cb) { slot->c_cb(aTHX_ fd, mask, slot->c_ud); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (slot->c_cb) { slot->c_cb(aTHX_ fd, mask, slot->c_ud); return; } 6 16 22
5431 /*
5432 # uncoverable branch true
5433 # uncoverable condition left count:1 class:ignore_covered_err */
5434 16 ▶ if (!sv) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return; 0 16 16
5435 16 ▶ if (slot->is_cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (slot->is_cb) { 8 8 16
5436 8 dSP;
5437 8 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 8 8
5438 8 PUTBACK;
5439 8 call_sv(sv, G_DISCARD | G_EVAL);
5440 8 hm_warn_died(aTHX_ "watch_io callback");
5441 8 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 8 8
5442 } else {
5443 8 slot->sv = NULL; /* one-shot */
5444 8 hmf_done0(aTHX_ sv);
5445 8 SvREFCNT_dec(sv);
5446 }
5447 }
5448  
5449 /* Timeout sweep: close idle keep-alive connections and slow/partial-request
5450 * (slowloris) connections. Runs on a periodic backend timer. */
5451 16 static void hm_sweep(pTHX_ hm_loop *loop) {
5452 16 hm_conn *c = loop->lru_head;
5453 16 time_t now = time(NULL);
5454 16 loop->now = now;
5455 25 ▶ while (c) {
Branch: 1 branch
BranchTrueFalseTotal
while (c) { 9 16 25
5456 9 hm_conn *next = c->lru_next;
5457 /* in_app: a synchronous handler is running for it (and pumping
5458 * this loop); its request is in progress, not idle */
5459 /*
5460 # uncoverable branch false class:ignore_covered_err
5461 # uncoverable condition right count:1 class:ignore_covered_err
5462 # uncoverable condition right count:2 class:ignore_covered_err */
5463 9 ▶ if (!c->awaiting && !c->in_app) {
Branch: 2 branches
BranchTrueFalseTotal
if (!c->awaiting && !c->in_app) { 9 0 9
if (!c->awaiting && !c->in_app) { 9 0 9
5464 9 double idle = difftime(now, c->last_active);
5465 /* Two guards for two phases. The header block is timed from the
5466 * request's first byte, which is the slowloris guard. Once the
5467 * headers are complete and a body is arriving, the clock is
5468 * progress: a body that has not delivered a byte for
5469 * body_timeout is dead, however long it has been coming - and
5470 * an upload slower than max_body in header_timeout is not. */
5471 17 ▶ int slow = c->req_start &&
Branch: 1 branch
BranchTrueFalseTotal
int slow = c->req_start && 8 1 9
5472 8 ▶ (c->body_phase
Branch: 1 branch
BranchTrueFalseTotal
(c->body_phase 5 3 8
5473 5 ▶ ? difftime(now, c->last_rx) > loop->body_timeout
Branch: 1 branch
BranchTrueFalseTotal
? difftime(now, c->last_rx) > loop->body_timeout 1 4 5
5474 3 ▶ : difftime(now, c->req_start) > loop->header_timeout);
Branch: 1 branch
BranchTrueFalseTotal
: difftime(now, c->req_start) > loop->header_timeout); 2 1 3
5475 /* Two OPT-IN floors under the progress clock, for a deployment
5476 * that cannot afford a body dribbled a byte a minute for ever:
5477 * a minimum average rate over the body phase (judged after two
5478 * seconds, so a first slow segment is not a verdict), and a
5479 * ceiling on the whole request from its first byte. */
5480 9 ▶ if (!slow && c->req_start && c->body_phase && loop->body_min_rate) {
Branch: 4 branches
BranchTrueFalseTotal
if (!slow && c->req_start && c->body_phase && loop->body_min_rate) { 6 3 9
if (!slow && c->req_start && c->body_phase && loop->body_min_rate) { 5 1 6
if (!slow && c->req_start && c->body_phase && loop->body_min_rate) { 4 1 5
if (!slow && c->req_start && c->body_phase && loop->body_min_rate) { 1 3 4
5481 1 double span = difftime(now, c->body_t0);
5482 /*
5483 # uncoverable branch false class:ignore_covered_err
5484 # uncoverable condition right count:1 class:ignore_covered_err
5485 # uncoverable condition right count:2 class:ignore_covered_err */
5486 1 ▶ if (span >= 2.0
Branch: 1 branch
BranchTrueFalseTotal
if (span >= 2.0 1 0 1
5487 1 ▶ && (double)c->body_rx / span < (double)loop->body_min_rate)
Branch: 1 branch
BranchTrueFalseTotal
&& (double)c->body_rx / span < (double)loop->body_min_rate) 1 0 1
5488 1 slow = 1;
5489 }
5490 9 ▶ if (!slow && c->req_start && loop->request_timeout > 0 /* # uncoverable condition right count:4 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (!slow && c->req_start && loop->request_timeout > 0 /* # uncoverable condition right count:4 class:ignore_covered_err */ 5 4 9
if (!slow && c->req_start && loop->request_timeout > 0 /* # uncoverable condition right count:4 class:ignore_covered_err */ 4 1 5
if (!slow && c->req_start && loop->request_timeout > 0 /* # uncoverable condition right count:4 class:ignore_covered_err */ 1 3 4
5491 1 ▶ && difftime(now, c->req_start) > loop->request_timeout)
Branch: 1 branch
BranchTrueFalseTotal
&& difftime(now, c->req_start) > loop->request_timeout) 1 0 1
5492 1 slow = 1;
5493 9 ▶ if (idle > loop->idle_timeout || slow)
Branch: 2 branches
BranchTrueFalseTotal
if (idle > loop->idle_timeout || slow) 8 1 9
if (idle > loop->idle_timeout || slow) 5 3 8
5494 6 hm_close(aTHX_ loop, c);
5495 }
5496 9 c = next;
5497 }
5498 16 }
5499  
5500 /* Graceful shutdown: stop accepting, close idle (served) connections,
5501 * finish in-flight work bounded by shutdown_grace; responses during
5502 * shutdown get Connection: close. */
5503 134 static void hm_on_signal(pTHX_ hm_loop *loop) {
5504 hm_conn *c;
5505 /*
5506 # uncoverable branch true
5507 # uncoverable condition left count:1 class:ignore_covered_err */
5508 134 ▶ if (loop->stopping) { loop->stop = 1; return; } /* second signal: hard */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stopping) { loop->stop = 1; return; } /* second signal: hard */ 0 134 134
5509 134 loop->stopping = 1;
5510 {
5511 int i;
5512 279 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 145 134 279
5513 /*
5514 # uncoverable branch false class:ignore_covered_err
5515 # uncoverable condition right count:1 class:ignore_covered_err */
5516 145 ▶ if (loop->listeners[i].fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].fd >= 0) 145 0 145
5517 145 loop->be->remove_io(loop->be, loop->listeners[i].fd, HM_EV_READ);
5518 /* Stop taking datagrams too. A QUIC connection already up is
5519 * not on this fd in any fd-indexed sense, so nothing else here
5520 * reaches it; draining those needs a graceful shutdown that
5521 * sends CONNECTION_CLOSE, which is not implemented. */
5522 /*
5523 # uncoverable branch true class:ignore_covered_err
5524 # uncoverable condition left count:1 class:ignore_covered_err */
5525 145 ▶ if (loop->listeners[i].udp_fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].udp_fd >= 0) 0 145 145
5526 0 loop->be->remove_io(loop->be, loop->listeners[i].udp_fd, HM_EV_READ); /* # uncoverable statement class:ignore_covered_err */
5527 }
5528 }
5529 134 hm_quic_shutdown(aTHX_ loop);
5530 134 c = loop->lru_head;
5531 136 ▶ while (c) {
Branch: 1 branch
BranchTrueFalseTotal
while (c) { 2 134 136
5532 2 hm_conn *next = c->lru_next;
5533 /*
5534 # uncoverable condition right count:2 class:ignore_covered_err
5535 # uncoverable condition right count:3 class:ignore_covered_err
5536 # uncoverable condition right count:4 class:ignore_covered_err */
5537 2 ▶ if (!c->awaiting && !c->in_app && c->rlen == 0 && c->wlen == c->woff
Branch: 4 branches
BranchTrueFalseTotal
if (!c->awaiting && !c->in_app && c->rlen == 0 && c->wlen == c->woff 1 1 2
if (!c->awaiting && !c->in_app && c->rlen == 0 && c->wlen == c->woff 1 0 1
if (!c->awaiting && !c->in_app && c->rlen == 0 && c->wlen == c->woff 1 0 1
if (!c->awaiting && !c->in_app && c->rlen == 0 && c->wlen == c->woff 1 0 1
5538 1 ▶ && c->nreqs > 0)
Branch: 1 branch
BranchTrueFalseTotal
&& c->nreqs > 0) 1 0 1
5539 1 hm_close(aTHX_ loop, c);
5540 2 c = next;
5541 }
5542 134 ▶ if (loop->nconns == 0) { loop->stop = 1; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (loop->nconns == 0) { loop->stop = 1; return; } 133 1 134
5543 /*
5544 # uncoverable branch false class:ignore_covered_err
5545 # uncoverable condition right count:1 class:ignore_covered_err */
5546 1 ▶ if (!loop->hardstop_tw) {
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->hardstop_tw) { 1 0 1
5547 1 loop->hardstop_tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
5548 1 loop->hardstop_tw->kind = HM_TW_HARDSTOP;
5549 1 loop->hardstop_tw->loop = loop;
5550 1 loop->hardstop_tw->due = hm_tw_due(loop->shutdown_grace);
5551 /*
5552 # uncoverable branch true class:ignore_covered_err
5553 # uncoverable condition left count:1 class:ignore_covered_err */
5554 1 ▶ if (loop->be->add_timer(loop->be, loop->shutdown_grace, 1, loop->hardstop_tw) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (loop->be->add_timer(loop->be, loop->shutdown_grace, 1, loop->hardstop_tw) < 0) 0 1 1
5555 0 hm_errlog("Hyperman: cannot arm the shutdown_grace timer: %s\n", strerror(errno)); /* # uncoverable statement */
5556 }
5557 }
5558  
5559 /* Drain a snapshot of the deferred (run-soon) queue. */
5560 31273 static void hm_run_deferred(pTHX_ hm_loop *loop) {
5561 31273 SSize_t n = av_len(loop->deferred) + 1;
5562 SSize_t i;
5563 31273 ▶ if (!n) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!n) return; 31271 2 31273
5564 2 ENTER; SAVETMPS;
5565 5 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 3 2 5
5566 3 SV *cb = sv_2mortal(av_shift(loop->deferred));
5567 3 dSP;
5568 3 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 3 3
5569 3 PUTBACK;
5570 3 call_sv(cb, G_DISCARD | G_EVAL);
5571 3 hm_warn_died(aTHX_ "deferred callback");
5572 }
5573 2 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 2 0 2
5574 }
5575  
5576 /* Re-process connections that hit the fairness cap with requests still
5577 * buffered, now that everyone else has been serviced. */
5578 31273 static void hm_run_again(pTHX_ hm_loop *loop) {
5579 31273 int n = loop->again_n;
5580 int i;
5581 31273 ▶ if (!n) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!n) return; 31261 12 31273
5582 12 loop->again_n = 0;
5583 24 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 12 12 24
5584 12 hm_conn *c = loop->conns[loop->again[i].fd];
5585 /*
5586 # uncoverable branch false class:ignore_covered_err
5587 # uncoverable condition right count:1 class:ignore_covered_err
5588 # uncoverable condition right count:2 class:ignore_covered_err */
5589 12 ▶ if (c && c->id == loop->again[i].id) c->again_queued = 0;
Branch: 2 branches
BranchTrueFalseTotal
if (c && c->id == loop->again[i].id) c->again_queued = 0; 12 0 12
if (c && c->id == loop->again[i].id) c->again_queued = 0; 12 0 12
5590 /*
5591 # uncoverable branch false class:ignore_covered_err
5592 # uncoverable condition right count:1 class:ignore_covered_err
5593 # uncoverable condition right count:2 class:ignore_covered_err
5594 # uncoverable condition right count:3 class:ignore_covered_err
5595 # uncoverable condition right count:4 class:ignore_covered_err
5596 # uncoverable condition left count:5 class:ignore_covered_err
5597 # uncoverable condition right count:5 class:ignore_covered_err
5598 # uncoverable condition right count:6 class:ignore_covered_err */
5599 12 ▶ if (c && c->id == loop->again[i].id && !c->awaiting
Branch: 3 branches
BranchTrueFalseTotal
if (c && c->id == loop->again[i].id && !c->awaiting 12 0 12
if (c && c->id == loop->again[i].id && !c->awaiting 12 0 12
if (c && c->id == loop->again[i].id && !c->awaiting 12 0 12
5600 12 ▶ && (!c->in_app || hm_h2_reentrant(c)) && !c->bsrc.kind) {
Branch: 3 branches
BranchTrueFalseTotal
&& (!c->in_app || hm_h2_reentrant(c)) && !c->bsrc.kind) { 0 12 12
&& (!c->in_app || hm_h2_reentrant(c)) && !c->bsrc.kind) { 0 0 0
&& (!c->in_app || hm_h2_reentrant(c)) && !c->bsrc.kind) { 12 0 12
5601 12 hm_process(aTHX_ c);
5602 /*
5603 # uncoverable branch false class:ignore_covered_err
5604 # uncoverable condition right count:1 class:ignore_covered_err */
5605 12 ▶ if (loop->conns[c->fd] == c) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] == c) { 12 0 12
5606 12 hm_flush(aTHX_ c);
5607 /* THE re-arm point for completion mode, and the reason
5608 * anything that wants a read armed calls hm_again_push
5609 * rather than arming for itself: this runs at the top of a
5610 * loop turn, so hm_process is not on the stack and growing
5611 * the read buffer cannot pull the ground out from under the
5612 * pointers it holds into it. */
5613 12 ▶ if (loop->conns[c->fd] == c) hm_rearm_read(loop, c);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] == c) hm_rearm_read(loop, c); 11 1 12
5614 }
5615 }
5616 }
5617 }
5618  
5619 31352 static void hm_dispatch(pTHX_ hm_loop *loop, hm_event *ev) {
5620 /*
5621 # uncoverable branch true count:3
5622 # uncoverable branch true count:6 class:ignore_covered_err */
5623 31352 switch (ev->kind) {
5624 2355 case HM_EV_TIMER: {
5625 2355 hm_tw *tw = (hm_tw *)ev->udata;
5626 2355 ▶ if (!tw || tw->dead) return; /* cancelled earlier in this batch */ /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!tw || tw->dead) return; /* cancelled earlier in this batch */ /* # uncoverable condition left count:1 class:ignore_covered_err */ 2355 0 2355
if (!tw || tw->dead) return; /* cancelled earlier in this batch */ /* # uncoverable condition left count:1 class:ignore_covered_err */ 10 2345 2355
5627 2345 ▶ if (tw->kind == HM_TW_SWEEP) { hm_sweep(aTHX_ loop); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (tw->kind == HM_TW_SWEEP) { hm_sweep(aTHX_ loop); return; } 16 2329 2345
5628 /* A oneshot delivered before its deadline (NetBSD's kqueue timed a
5629 * 300ms Fetch request out at 246ms on a smoker) is re-armed for the
5630 * remainder and not fired. The backend has already dropped it, so the
5631 * same watcher is free to re-add; each re-arm is shorter, so a
5632 * backend that is always early still converges. Within a
5633 * millisecond is the backends' own rounding. */
5634 /*
5635 # uncoverable branch false class:ignore_covered_err
5636 # uncoverable condition right count:1 class:ignore_covered_err */
5637 2329 ▶ if (tw->due > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (tw->due > 0) { 2329 0 2329
5638 2329 double left = tw->due - (double)hm_now_ns() / 1e9;
5639 /* could not re-arm (no descriptor for a timerfd): early beats
5640 * never, so it fires now */
5641 /*
5642 # uncoverable branch true class:ignore_covered_err
5643 # uncoverable condition left count:1 class:ignore_covered_err
5644 # uncoverable condition left count:2 class:ignore_covered_err
5645 # uncoverable condition right count:2 class:ignore_covered_err */
5646 2329 ▶ if (left > 1e-3 && loop->be->add_timer(loop->be, left, 1, tw) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (left > 1e-3 && loop->be->add_timer(loop->be, left, 1, tw) == 0) 0 2329 2329
if (left > 1e-3 && loop->be->add_timer(loop->be, left, 1, tw) == 0) 0 0 0
5647 0 return; /* # uncoverable statement */
5648 }
5649 2329 ▶ if (tw->kind == HM_TW_HARDSTOP) { loop->stop = 1; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (tw->kind == HM_TW_HARDSTOP) { loop->stop = 1; return; } 1 2328 2329
5650 2328 ▶ if (tw->kind == HM_TW_C) { /* ABI timer: no Perl frame */
Branch: 1 branch
BranchTrueFalseTotal
if (tw->kind == HM_TW_C) { /* ABI timer: no Perl frame */ 279 2049 2328
5651 279 hm_abi_timer_cb cb = tw->c_cb;
5652 279 void *ud = tw->c_ud;
5653 279 free(tw);
5654 279 cb(aTHX_ ud);
5655 279 return;
5656 }
5657 {
5658 2049 SV *sv = tw->sv;
5659 2049 int kind = tw->kind;
5660 2049 free(tw);
5661 2049 ▶ if (kind == HM_TW_FUTURE) {
Branch: 1 branch
BranchTrueFalseTotal
if (kind == HM_TW_FUTURE) { 2020 29 2049
5662 2020 hmf_done0(aTHX_ sv);
5663 } else {
5664 29 dSP;
5665 29 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 29 29
5666 29 PUTBACK;
5667 29 call_sv(sv, G_DISCARD | G_EVAL);
5668 29 hm_warn_died(aTHX_ "timer callback");
5669 29 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 29 29
5670 }
5671 2049 SvREFCNT_dec(sv);
5672 }
5673 2049 return;
5674 }
5675 129 case HM_EV_SIGNAL:
5676 129 ▶ if (ev->fd == SIGUSR1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ev->fd == SIGUSR1) { 3 126 129
5677 /* With a scoreboard the supervisor prints every row itself and
5678 * never forwards USR1; this line is the no-arena fallback. */
5679 /*
5680 # uncoverable branch false class:ignore_covered_err
5681 # uncoverable condition right count:1 class:ignore_covered_err */
5682 3 ▶ if (!hm_sa_board_live())
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_sa_board_live()) 3 0 3
5683 6 hm_errlog("Hyperman worker %d: requests=%lu accepts=%lu conns=%d "
5684 "bytes_out=%lu backend=%s%s\n",
5685 3 hm_os_getpid(),
5686 3 (unsigned long)loop->requests, (unsigned long)loop->accepts,
5687 3 loop->nconns, (unsigned long)loop->bytes_out,
5688 6 ▶ loop->be->name, loop->stopping ? " (draining)" : ""); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
loop->be->name, loop->stopping ? " (draining)" : ""); /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 3 3
5689 3 return;
5690 }
5691 126 hm_on_signal(aTHX_ loop);
5692 126 return;
5693 0 case HM_EV_RECV: { /* # uncoverable statement */
5694 /* A read the core asked for has finished; the bytes are already in
5695 * the buffer it supplied. */
5696 0 int fd = ev->fd; /* # uncoverable statement */
5697 /*
5698 # uncoverable statement
5699 # uncoverable condition left count:1
5700 # uncoverable condition right count:1
5701 # uncoverable condition left count:2
5702 # uncoverable condition right count:2 */
5703 0 ▶ hm_conn *c = (fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL;
Branch: 2 branches
BranchTrueFalseTotal
hm_conn *c = (fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 0 0 0
hm_conn *c = (fd >= 0 && fd < HM_MAXFD) ? loop->conns[fd] : NULL; 0 0 0
5704  
5705 /* Is this OUR read? A completion can outlive its connection - the fd
5706 * may have been closed and reused since - and the token is the only
5707 * thing that can tell the difference. Anything that does not match
5708 * belongs to a connection that is gone, and the buffer it was reading
5709 * into is parked waiting for exactly this moment. */
5710 /*
5711 # uncoverable statement
5712 # uncoverable branch true
5713 # uncoverable branch false
5714 # uncoverable condition left count:1
5715 # uncoverable condition right count:1
5716 # uncoverable condition left count:2
5717 # uncoverable condition right count:2
5718 # uncoverable condition left count:3
5719 # uncoverable condition right count:3 */
5720 0 ▶ if (!c || !c->recv_inflight || HM_RECV_TOKEN(c) != ev->token) {
Branch: 3 branches
BranchTrueFalseTotal
if (!c || !c->recv_inflight || HM_RECV_TOKEN(c) != ev->token) { 0 0 0
if (!c || !c->recv_inflight || HM_RECV_TOKEN(c) != ev->token) { 0 0 0
if (!c || !c->recv_inflight || HM_RECV_TOKEN(c) != ev->token) { 0 0 0
5721 0 hm_quar_release(loop, ev->token); /* # uncoverable statement */
5722 0 return; /* # uncoverable statement */
5723 }
5724 0 c->recv_inflight = 0; /* # uncoverable statement */
5725 /*
5726 # uncoverable statement
5727 # uncoverable branch true
5728 # uncoverable branch false
5729 # uncoverable condition left count:1
5730 # uncoverable condition right count:1 */
5731 0 ▶ if (ev->res <= 0) { /* EOF, error, or the cancel from a close */
Branch: 1 branch
BranchTrueFalseTotal
if (ev->res <= 0) { /* EOF, error, or the cancel from a close */ 0 0 0
5732 /* The peer half-closed a tunnel: fin to the handle first, as
5733 * hm_readable's zero read does, then the close says the rest. */
5734 /*
5735 # uncoverable statement
5736 # uncoverable branch true
5737 # uncoverable branch false
5738 # uncoverable condition left count:1
5739 # uncoverable condition right count:1
5740 # uncoverable condition left count:2
5741 # uncoverable condition right count:2 */
5742 0 ▶ if (c->tunnel && ev->res == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->tunnel && ev->res == 0) { 0 0 0
if (c->tunnel && ev->res == 0) { 0 0 0
5743 0 (void)hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, 0, 1); /* # uncoverable statement */
5744 /*
5745 # uncoverable statement
5746 # uncoverable branch true
5747 # uncoverable branch false
5748 # uncoverable condition left count:1
5749 # uncoverable condition right count:1 */
5750 0 ▶ if (loop->conns[fd] != c) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return; 0 0 0
5751 }
5752 0 hm_close(aTHX_ loop, c); /* # uncoverable statement */
5753 0 return; /* # uncoverable statement */
5754 }
5755 0 c->rlen += (size_t)ev->res; /* # uncoverable statement */
5756 0 c->last_rx = loop->now; /* # uncoverable statement */
5757 0 c->body_rx += (UV)ev->res; /* # uncoverable statement */
5758 0 c->last_active = loop->now; /* # uncoverable statement */
5759 0 hm_lru_touch(loop, c); /* # uncoverable statement */
5760 /* A tunnel carries no requests: its bytes go to the handle. The
5761 * parser would hold them as an unfinished request line forever. */
5762 /*
5763 # uncoverable statement
5764 # uncoverable branch true
5765 # uncoverable branch false
5766 # uncoverable branch true count:2
5767 # uncoverable branch false count:2
5768 # uncoverable branch true count:3
5769 # uncoverable branch false count:3
5770 # uncoverable condition left count:1
5771 # uncoverable condition right count:1
5772 # uncoverable condition left count:2
5773 # uncoverable condition right count:2 */
5774 0 ▶ if (c->tunnel == 1) { if (!hm_tunnel_bytes(aTHX_ c)) return; }
Branch: 2 branches
BranchTrueFalseTotal
if (c->tunnel == 1) { if (!hm_tunnel_bytes(aTHX_ c)) return; } 0 0 0
if (c->tunnel == 1) { if (!hm_tunnel_bytes(aTHX_ c)) return; } 0 0 0
5775 /* The same rule hm_readable applies: a synchronous handler's frame
5776 * is on the stack for this connection (its ->get pumped the loop,
5777 * and this read was in flight when it was handed the pipeline), or
5778 * a tunnel was opened inside it and the request is still in rbuf.
5779 * That frame owns the buffer. The bytes wait in it, nothing is
5780 * dispatched or re-armed from under it, and whoever called that
5781 * frame re-arms when it returns (hm_deliver's hm_again_push, or the
5782 * re-arm below in the frame that called hm_process). Without this a
5783 * second hm_process re-parsed the request at rbuf[0], called the
5784 * application twice, and left the outer frame to memmove with a
5785 * consumed count larger than what remained. */
5786 /*
5787 # uncoverable statement
5788 # uncoverable branch true
5789 # uncoverable branch false
5790 # uncoverable condition left count:1
5791 # uncoverable condition right count:1
5792 # uncoverable condition left count:2
5793 # uncoverable condition right count:2
5794 # uncoverable condition left count:3
5795 # uncoverable condition right count:3 */
5796 0 ▶ else if (c->tunnel == 2 || (c->in_app && !hm_h2_reentrant(c))) return;
Branch: 3 branches
BranchTrueFalseTotal
else if (c->tunnel == 2 || (c->in_app && !hm_h2_reentrant(c))) return; 0 0 0
else if (c->tunnel == 2 || (c->in_app && !hm_h2_reentrant(c))) return; 0 0 0
else if (c->tunnel == 2 || (c->in_app && !hm_h2_reentrant(c))) return; 0 0 0
5797 0 else hm_process(aTHX_ c); /* # uncoverable statement */
5798 /*
5799 # uncoverable statement
5800 # uncoverable branch true
5801 # uncoverable branch false
5802 # uncoverable condition left count:1
5803 # uncoverable condition right count:1 */
5804 0 ▶ if (loop->conns[fd] != c) return; /* dispatch closed it */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return; /* dispatch closed it */ 0 0 0
5805 0 hm_flush(aTHX_ c); /* # uncoverable statement */
5806 /*
5807 # uncoverable statement
5808 # uncoverable branch true
5809 # uncoverable branch false
5810 # uncoverable condition left count:1
5811 # uncoverable condition right count:1 */
5812 0 ▶ if (loop->conns[fd] != c) return; /* flush closed it */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return; /* flush closed it */ 0 0 0
5813 /* Re-armed even while PARKED or streaming, and that is not an
5814 * optimisation - it is how a disconnect is noticed at all.
5815 *
5816 * A readiness backend keeps a persistent watcher on every connection,
5817 * so a client that walks away from a parked async request wakes the
5818 * loop with EOF and the response Future gets cancelled. Completion
5819 * mode has no such watcher: with no read outstanding the close is
5820 * simply never seen, the Future is never cancelled, and the
5821 * connection sits there until the idle sweep. t/13-async-psgi.t
5822 * catches exactly this.
5823 *
5824 * Safe because the request's bytes are gone from the buffer before it
5825 * parks - hm_process consumes them, and hm_new_input COPIES the body
5826 * into an SV - so nothing points into rbuf across a park, and the
5827 * kernel only ever writes past rlen. */
5828 0 hm_rearm_read(loop, c); /* # uncoverable statement */
5829 0 return; /* # uncoverable statement */
5830 }
5831 28851 case HM_EV_READ: {
5832 28851 int fd = ev->fd;
5833 hm_conn *c;
5834 hm_listener *lst;
5835 28851 ▶ if ((lst = hm_listener_for_fd(loop, fd))) { hm_accept(aTHX_ loop, lst); return; }
Branch: 1 branch
BranchTrueFalseTotal
if ((lst = hm_listener_for_fd(loop, fd))) { hm_accept(aTHX_ loop, lst); return; } 27644 1207 28851
5836 /* Between the two, because a UDP listener fd is never in conns[]:
5837 * QUIC multiplexes every connection over the one socket, so there is
5838 * nothing fd-indexed to find. */
5839 /*
5840 # uncoverable branch true class:ignore_covered_err
5841 # uncoverable condition left count:1 class:ignore_covered_err */
5842 1207 ▶ if ((lst = hm_listener_for_udp(loop, fd))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((lst = hm_listener_for_udp(loop, fd))) { 0 1207 1207
5843 0 hm_quic_readable(aTHX_ loop, lst); /* # uncoverable statement class:ignore_covered_err */
5844 0 return; /* # uncoverable statement class:ignore_covered_err */
5845 }
5846 1207 ▶ if ((c = loop->conns[fd])) {
Branch: 1 branch
BranchTrueFalseTotal
if ((c = loop->conns[fd])) { 1186 21 1207
5847 1186 ▶ if (c->pp_wait) hm_proxy_readable(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (c->pp_wait) hm_proxy_readable(aTHX_ c); 50 1136 1186
5848 1136 ▶ else if (c->tls_hs) hm_tls_handshake(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
else if (c->tls_hs) hm_tls_handshake(aTHX_ c); 116 1020 1136
5849 1020 else hm_readable(aTHX_ c);
5850 }
5851 /*
5852 # uncoverable branch false class:ignore_covered_err
5853 # uncoverable condition right count:1 class:ignore_covered_err
5854 # uncoverable condition right count:2 class:ignore_covered_err */
5855 21 ▶ else if (loop->io_r[fd].sv || loop->io_r[fd].c_cb)
Branch: 2 branches
BranchTrueFalseTotal
else if (loop->io_r[fd].sv || loop->io_r[fd].c_cb) 6 15 21
else if (loop->io_r[fd].sv || loop->io_r[fd].c_cb) 6 0 6
5856 21 hm_io_event(aTHX_ loop, fd, HM_EV_READ, &loop->io_r[fd]);
5857 1207 return;
5858 }
5859 17 case HM_EV_WRITE: {
5860 17 int fd = ev->fd;
5861 hm_conn *c;
5862 17 ▶ if ((c = loop->conns[fd])) {
Branch: 1 branch
BranchTrueFalseTotal
if ((c = loop->conns[fd])) { 16 1 17
5863 /* TLS post-handshake: when the write watcher is armed because
5864 * SSL_read wanted a writable socket, route through hm_readable so
5865 * the blocked read is re-driven (it flushes pending output at the
5866 * end). Otherwise this is ordinary write backpressure and the
5867 * read side is not blocked at all - going through hm_readable
5868 * then costs an SSL_read that can only return EAGAIN, once per
5869 * writable wakeup for the whole of a large response. */
5870 /*
5871 # uncoverable branch true
5872 # uncoverable condition left count:1 class:ignore_covered_err */
5873 16 ▶ if (c->tls_hs) hm_tls_handshake(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (c->tls_hs) hm_tls_handshake(aTHX_ c); 0 16 16
5874 /*
5875 # uncoverable branch true class:ignore_covered_err
5876 # uncoverable condition left count:1 class:ignore_covered_err
5877 # uncoverable condition left count:2 class:ignore_covered_err */
5878 16 ▶ else if (c->ssl && c->tls_r_wants_w) hm_readable(aTHX_ c);
Branch: 2 branches
BranchTrueFalseTotal
else if (c->ssl && c->tls_r_wants_w) hm_readable(aTHX_ c); 3 13 16
else if (c->ssl && c->tls_r_wants_w) hm_readable(aTHX_ c); 0 3 3
5879 16 else hm_flush(aTHX_ c);
5880 }
5881 /*
5882 # uncoverable condition left count:2 class:ignore_covered_err
5883 # uncoverable branch false class:ignore_covered_err
5884 # uncoverable condition right count:1 class:ignore_covered_err
5885 # uncoverable condition right count:2 class:ignore_covered_err */
5886 1 ▶ else if (loop->io_w[fd].sv || loop->io_w[fd].c_cb)
Branch: 2 branches
BranchTrueFalseTotal
else if (loop->io_w[fd].sv || loop->io_w[fd].c_cb) 0 1 1
else if (loop->io_w[fd].sv || loop->io_w[fd].c_cb) 0 0 0
5887 1 hm_io_event(aTHX_ loop, fd, HM_EV_WRITE, &loop->io_w[fd]);
5888 17 return;
5889 }
5890 }
5891 }
5892  
5893 /* Run the loop until ->stop, or (when awaiting) until $until is ready.
5894 * Re-entrant: ->get/->await inside a handler pumps this same loop, so the
5895 * worker keeps serving other connections while awaiting. */
5896 /* Dispatch what the calling frames took from the backend and have not yet
5897 * reached, nearest first. Each index moves past an event BEFORE it is
5898 * dispatched, so a run nested deeper inside it skips it too. */
5899 26 static void hm_batch_drain(pTHX_ hm_loop *loop, hm_batch *b) {
5900 52 ▶ for (; b; b = b->up)
Branch: 1 branch
BranchTrueFalseTotal
for (; b; b = b->up) 26 26 52
5901 34 ▶ while (b->i < b->n) hm_dispatch(aTHX_ loop, &b->evs[b->i++]);
Branch: 1 branch
BranchTrueFalseTotal
while (b->i < b->n) hm_dispatch(aTHX_ loop, &b->evs[b->i++]); 8 26 34
5902 26 }
5903  
5904 226 static void hm_loop_run(pTHX_ hm_loop *loop, SV *until) {
5905 hm_event evs[HM_MAXEV];
5906 hm_batch b;
5907 /* The fire queue is pumped by whoever enqueues, unless a pump is
5908 * already on the stack (hm_fq_active), which makes a continuation that
5909 * enqueues from inside a callback leave its work for the pump above
5910 * it. That pump is above THIS frame too when a handler reached through
5911 * the queue (a parked response delivering the next pipelined request)
5912 * calls ->get: the nested run here must pump for itself, or every
5913 * continuation it waits on - a ->then, a combinator - sits in the queue
5914 * until it returns, which is never.
5915 *
5916 * This frame's state goes on the save stack, so a croak out of here (a
5917 * die from a signal handler under a ->get) restores it as a return
5918 * does. loop->batch most of all: left behind, it names this frame's
5919 * evs after the frame is gone. */
5920 226 ENTER;
5921 226 SAVEINT(hm_fq_active);
5922 226 SAVEVPTR(hm_cur_loop);
5923 226 SAVEINT(loop->running);
5924 226 SAVEVPTR(loop->batch);
5925 226 hm_fq_active = 0;
5926 226 hm_cur_loop = loop;
5927 226 loop->running++;
5928 226 b.evs = evs;
5929 226 b.n = b.i = 0;
5930 226 b.up = loop->batch;
5931 226 loop->batch = &b;
5932 /* Cleared for the OUTERMOST run only. A nested run is a handler's ->get
5933 * pumping this loop, and a stop asked for while it runs - the second
5934 * TERM, the shutdown_grace hard-stop, the last connection closing while
5935 * draining - is the outer run's to act on: the nested one breaks and
5936 * leaves the flag set. Clearing it on exit, as this once did, swallowed
5937 * every stop that landed under a handler, and the hard-stop timer is
5938 * one-shot so the worker then never left. */
5939 226 ▶ if (loop->running == 1) loop->stop = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->running == 1) loop->stop = 0; 205 21 226
5940 31047 for (;;) {
5941 31273 double timeout = -1.0;
5942 int n, i;
5943 31273 loop->now = time(NULL);
5944 31273 ▶ if (b.up) hm_batch_drain(aTHX_ loop, b.up);
Branch: 1 branch
BranchTrueFalseTotal
if (b.up) hm_batch_drain(aTHX_ loop, b.up); 26 31247 31273
5945 31273 ▶ if (loop->recycle_pending && !loop->stopping) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (loop->recycle_pending && !loop->stopping) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 31265 31273
if (loop->recycle_pending && !loop->stopping) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 0 8
5946 8 loop->recycle_pending = 0;
5947 8 hm_on_signal(aTHX_ loop); /* max_requests recycle: drain + exit */
5948 }
5949 31273 hm_run_deferred(aTHX_ loop);
5950 31273 hm_run_again(aTHX_ loop);
5951 31273 ▶ if (loop->starved_retry) hm_accept_unstarve(loop);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->starved_retry) hm_accept_unstarve(loop); 26510 4763 31273
5952 31273 ▶ if (loop->stop) break;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stop) break; 12 31261 31273
5953 31261 ▶ if (until && hmf_state(aTHX_ until) != HMF_PENDING) break;
Branch: 2 branches
BranchTrueFalseTotal
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 2077 29184 31261
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 4 2073 2077
5954 31257 ▶ if (av_len(loop->deferred) >= 0 || loop->again_n) timeout = 0.0;
Branch: 2 branches
BranchTrueFalseTotal
if (av_len(loop->deferred) >= 0 || loop->again_n) timeout = 0.0; 31256 1 31257
if (av_len(loop->deferred) >= 0 || loop->again_n) timeout = 0.0; 1 31255 31256
5955 /* QUIC's deadlines do not live in the backend's timer list - see the
5956 * costing in hm_quic.h - so the wait is clamped to the nearest one
5957 * here instead. Rounding UP is correct: ngtcp2 copes with a late
5958 * expiry and not with an early one, and the backends already round
5959 * to milliseconds. One compare when there is no QUIC listener. */
5960 /*
5961 # uncoverable branch true class:ignore_covered_err
5962 # uncoverable condition left count:1 class:ignore_covered_err */
5963 31257 ▶ if (loop->qheap.n) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->qheap.n) { 0 31257 31257
5964 /* Through a function rather than reaching into the heap here:
5965 * hm_qconn is an opaque forward declaration on a build without
5966 * QUIC, and dereferencing it would compile only where the
5967 * feature is present - which is not where the mistake shows up. */
5968 0 uint64_t now_ns = hm_now_ns(); /* # uncoverable statement class:ignore_covered_err */
5969 0 uint64_t due = hm_quic_next_deadline(loop); /* # uncoverable statement class:ignore_covered_err */
5970 /*
5971 # uncoverable statement class:ignore_covered_err
5972 # uncoverable branch true class:ignore_covered_err
5973 # uncoverable branch false class:ignore_covered_err
5974 # uncoverable condition left count:1 class:ignore_covered_err
5975 # uncoverable condition right count:1 class:ignore_covered_err */
5976 0 ▶ if (due != (uint64_t)-1) {
Branch: 1 branch
BranchTrueFalseTotal
if (due != (uint64_t)-1) { 0 0 0
5977 0 double secs = due <= now_ns ? 0.0 /* # uncoverable statement class:ignore_covered_err */
5978 0 ▶ : (double)(due - now_ns) / 1e9; /* # uncoverable statement class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
: (double)(due - now_ns) / 1e9; /* # uncoverable statement class:ignore_covered_err */ 0 0 0
5979 /*
5980 # uncoverable statement class:ignore_covered_err
5981 # uncoverable branch true class:ignore_covered_err
5982 # uncoverable branch false class:ignore_covered_err
5983 # uncoverable condition left count:1 class:ignore_covered_err
5984 # uncoverable condition right count:1 class:ignore_covered_err
5985 # uncoverable condition left count:2 class:ignore_covered_err
5986 # uncoverable condition right count:2 class:ignore_covered_err */
5987 0 ▶ if (timeout < 0.0 || secs < timeout) timeout = secs;
Branch: 2 branches
BranchTrueFalseTotal
if (timeout < 0.0 || secs < timeout) timeout = secs; 0 0 0
if (timeout < 0.0 || secs < timeout) timeout = secs; 0 0 0
5988 }
5989 }
5990 31257 n = loop->be->wait(loop->be, evs, HM_MAXEV, timeout);
5991 /*
5992 # uncoverable branch true
5993 # uncoverable condition left count:1 class:ignore_covered_err
5994 # uncoverable condition left count:2 class:ignore_covered_err
5995 # uncoverable condition right count:2 class:ignore_covered_err */
5996 31257 ▶ if (n < 0) { if (errno == EINTR) continue; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0) { if (errno == EINTR) continue; break; } 0 31257 31257
if (n < 0) { if (errno == EINTR) continue; break; } 0 0 0
5997 31257 b.n = n;
5998 31257 b.i = 0;
5999 62601 ▶ while (b.i < b.n) hm_dispatch(aTHX_ loop, &evs[b.i++]);
Branch: 1 branch
BranchTrueFalseTotal
while (b.i < b.n) hm_dispatch(aTHX_ loop, &evs[b.i++]); 31344 31257 62601
6000 31257 b.n = 0;
6001 31257 ▶ if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop); /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop); /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 31246 31257
if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop); /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 0 11
6002 /*
6003 # uncoverable branch true class:ignore_covered_err
6004 # uncoverable condition left count:1 class:ignore_covered_err */
6005 31257 ▶ if (loop->qheap.n) hm_quic_expire(aTHX_ loop);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->qheap.n) hm_quic_expire(aTHX_ loop); 0 31257 31257
6006 31257 ▶ if (loop->log_fd >= 0 && loop->log_len) hm_log_flush(loop);
Branch: 2 branches
BranchTrueFalseTotal
if (loop->log_fd >= 0 && loop->log_len) hm_log_flush(loop); 187 31070 31257
if (loop->log_fd >= 0 && loop->log_len) hm_log_flush(loop); 65 122 187
6007 31257 ▶ if (loop->stop) break;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stop) break; 145 31112 31257
6008 31112 ▶ if (until && hmf_state(aTHX_ until) != HMF_PENDING) break;
Branch: 2 branches
BranchTrueFalseTotal
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 2070 29042 31112
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 65 2005 2070
6009 }
6010 /*
6011 # uncoverable branch true class:ignore_covered_err
6012 # uncoverable condition left count:1 class:ignore_covered_err
6013 # uncoverable condition left count:2 class:ignore_covered_err
6014 # uncoverable condition right count:2 class:ignore_covered_err */
6015 226 ▶ if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop);
Branch: 2 branches
BranchTrueFalseTotal
if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop); 0 226 226
if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop); 0 0 0
6016 226 LEAVE;
6017 226 }
6018  
6019 /* ---- loop lifecycle ------------------------------------------------------- */
6020  
6021 177 static hm_loop *hm_loop_new(pTHX_ const char *backend_name) {
6022 177 hm_loop *loop = (hm_loop *)hm_xcalloc(1, sizeof(hm_loop));
6023 /*
6024 # uncoverable branch true
6025 # uncoverable condition left count:1 class:ignore_covered_err */
6026 177 ▶ if (!loop) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) return NULL; 0 177 177
6027 177 ▶ if (!backend_name || !*backend_name) /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!backend_name || !*backend_name) /* # uncoverable condition left count:2 class:ignore_covered_err */ 24 153 177
if (!backend_name || !*backend_name) /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 24 24
6028 153 backend_name = getenv("HYPERMAN_BACKEND");
6029 177 loop->be = hm_backend_create(backend_name);
6030 177 ▶ if (!loop->be) { free(loop); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->be) { free(loop); return NULL; } 4 173 177
6031 173 loop->pid = hm_os_getpid();
6032 173 loop->conns = (hm_conn **)hm_xcalloc(HM_MAXFD, sizeof(hm_conn *));
6033 173 loop->io_r = (hm_iow *)hm_xcalloc(HM_MAXFD, sizeof(hm_iow));
6034 173 loop->io_w = (hm_iow *)hm_xcalloc(HM_MAXFD, sizeof(hm_iow));
6035 173 loop->deferred = newAV();
6036 173 loop->log_fd = -1;
6037 173 loop->now = time(NULL);
6038 173 loop->idle_timeout = 60.0;
6039 173 loop->header_timeout = 30.0;
6040 173 loop->body_timeout = 60.0;
6041 173 loop->max_pipeline = 32;
6042 173 loop->max_read = 16 * 1024 * 1024; /* request ceiling */
6043 173 loop->compress = 0; /* off by default */
6044 173 loop->compress_min = HZ_MIN_LENGTH;
6045 173 loop->compress_level = HZ_LEVEL;
6046 173 loop->shutdown_grace = 30.0;
6047 /* Completion-mode reads, on wherever the backend can do them.
6048 *
6049 * That is io_uring alone, and io_uring IS auto-selected wherever
6050 * liburing was found at build time (the chooser goes kqueue, io_uring,
6051 * epoll, poll), so on such a Linux box this is the default read path -
6052 * which is why every change to how bytes ARRIVE lands on both the
6053 * readiness and the completion path (t/49 sweeps both).
6054 *
6055 * HYPERMAN_COMPLETION overrides, exactly as HYPERMAN_BACKEND overrides
6056 * the chooser; run(completion => ...) overrides both, being the most
6057 * specific thing the caller said. */
6058 173 loop->completion = loop->be->submit_recv ? 1 : 0;
6059 {
6060 173 const char *v = getenv("HYPERMAN_COMPLETION");
6061 /*
6062 # uncoverable branch true class:ignore_covered_err
6063 # uncoverable condition left count:1 class:ignore_covered_err
6064 # uncoverable condition left count:2 class:ignore_covered_err
6065 # uncoverable condition right count:2 class:ignore_covered_err */
6066 173 ▶ if (v && *v)
Branch: 2 branches
BranchTrueFalseTotal
if (v && *v) 0 173 173
if (v && *v) 0 0 0
6067 0 loop->completion = /* # uncoverable statement */
6068 /*
6069 # uncoverable statement
6070 # uncoverable condition left count:1
6071 # uncoverable condition right count:1
6072 # uncoverable condition left count:2
6073 # uncoverable condition right count:2 */
6074 0 ▶ (*v != '0' && loop->be->submit_recv) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
(*v != '0' && loop->be->submit_recv) ? 1 : 0; 0 0 0
(*v != '0' && loop->be->submit_recv) ? 1 : 0; 0 0 0
6075 }
6076 173 return loop;
6077 }
6078  
6079 /* Free a loop.
6080 *
6081 * A loop belongs to the process that created it, and every DESCRIPTOR in it -
6082 * the backend's own (kqueue/epoll), the connection sockets, the log file -
6083 * belongs to that process too. A loop inherited across a fork is therefore
6084 * freed WITHOUT closing anything: the memory is ours to release, the fds are
6085 * not.
6086 *
6087 * Closing them is destructive, not merely untidy. kqueue descriptors do not
6088 * survive fork(2): the kernel invalidates the child's copy, so the number is
6089 * free and the child's very next kqueue() is handed it back - closing the
6090 * inherited loop then shuts the CHILD'S OWN queue and nothing it watches
6091 * fires again. The epoll and connection fds are the parent's, still live, and
6092 * closing our duplicates frees numbers the child immediately reuses. */
6093 /* A loop inherited across a fork must never reach its backend. On Linux an
6094 * epoll INSTANCE is a shared kernel object: fork duplicates the fd but both
6095 * processes' epoll_ctl calls edit the SAME interest list, so a child
6096 * "cleaning up" inherited watchers silently deregisters the PARENT's fds -
6097 * the parent then waits on an empty set forever (the DBIx::Loop
6098 * disown-in-a-forked-child hang, Punk t/39). kqueue merely hands the child
6099 * a dead descriptor, which is why macOS never showed it. The copied
6100 * user-space tables are ours to update; the kernel object is not. */
6101 #define HM_LOOP_INHERITED(loop) ((loop)->pid != hm_os_getpid())
6102  
6103 171 static void hm_loop_free(pTHX_ hm_loop *loop) {
6104 int i;
6105 int owned;
6106 /*
6107 # uncoverable branch true
6108 # uncoverable condition left count:1 class:ignore_covered_err */
6109 171 ▶ if (!loop) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) return; 0 171 171
6110 171 owned = (loop->pid == hm_os_getpid());
6111 /* Read buffers still parked for completions that will now never be
6112 * reaped. The ring is torn down with the backend below, so nothing can
6113 * be writing into them by the time this returns. */
6114 171 hm_quar_free_all(loop);
6115 171 hm_tw_gy_sweep(loop);
6116 11206827 ▶ for (i = 0; i < HM_MAXFD; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < HM_MAXFD; i++) { 11206656 171 11206827
6117 11206656 ▶ if (loop->conns[i]) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[i]) { 1 11206655 11206656
6118 1 hm_conn *c = loop->conns[i];
6119 /*
6120 # uncoverable branch false class:ignore_covered_err
6121 # uncoverable condition right count:1 class:ignore_covered_err */
6122 1 ▶ if (owned) hm_os_close(c->fd);
Branch: 1 branch
BranchTrueFalseTotal
if (owned) hm_os_close(c->fd); 1 0 1
6123 /*
6124 # uncoverable branch true class:ignore_covered_err
6125 # uncoverable condition left count:1 class:ignore_covered_err */
6126 1 ▶ if (c->h2) hm_h2_free(aTHX_ c->h2);
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) hm_h2_free(aTHX_ c->h2); 0 1 1
6127 /*
6128 # uncoverable branch false class:ignore_covered_err
6129 # uncoverable condition right count:1 class:ignore_covered_err */
6130 1 ▶ if (c->io_sv) SvREFCNT_dec(c->io_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->io_sv) SvREFCNT_dec(c->io_sv); 1 0 1
6131 /*
6132 # uncoverable branch false class:ignore_covered_err
6133 # uncoverable condition right count:1 class:ignore_covered_err */
6134 1 ▶ if (c->resp_f) SvREFCNT_dec(c->resp_f);
Branch: 1 branch
BranchTrueFalseTotal
if (c->resp_f) SvREFCNT_dec(c->resp_f); 1 0 1
6135 /*
6136 # uncoverable branch true class:ignore_covered_err
6137 # uncoverable condition left count:1 class:ignore_covered_err */
6138 1 ▶ if (c->env_sv) SvREFCNT_dec(c->env_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) SvREFCNT_dec(c->env_sv); 0 1 1
6139 /*
6140 # uncoverable branch false class:ignore_covered_err
6141 # uncoverable condition right count:1 class:ignore_covered_err */
6142 1 ▶ if (c->peer_sv) SvREFCNT_dec(c->peer_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_sv) SvREFCNT_dec(c->peer_sv); 1 0 1
6143 /*
6144 # uncoverable branch false class:ignore_covered_err
6145 # uncoverable condition right count:1 class:ignore_covered_err */
6146 1 ▶ if (c->peer_host_sv) SvREFCNT_dec(c->peer_host_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_host_sv) SvREFCNT_dec(c->peer_host_sv); 1 0 1
6147 /*
6148 # uncoverable branch false class:ignore_covered_err
6149 # uncoverable condition right count:1 class:ignore_covered_err */
6150 1 ▶ if (c->peer_port_sv) SvREFCNT_dec(c->peer_port_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_port_sv) SvREFCNT_dec(c->peer_port_sv); 1 0 1
6151 /*
6152 # uncoverable branch false class:ignore_covered_err
6153 # uncoverable condition right count:1 class:ignore_covered_err */
6154 1 ▶ if (c->sname_sv) SvREFCNT_dec(c->sname_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->sname_sv) SvREFCNT_dec(c->sname_sv); 1 0 1
6155 /*
6156 # uncoverable branch false class:ignore_covered_err
6157 # uncoverable condition right count:1 class:ignore_covered_err */
6158 1 ▶ if (c->sport_sv) SvREFCNT_dec(c->sport_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (c->sport_sv) SvREFCNT_dec(c->sport_sv); 1 0 1
6159 /*
6160 # uncoverable branch false class:ignore_covered_err
6161 # uncoverable condition right count:1 class:ignore_covered_err
6162 # uncoverable branch true class:ignore_covered_err
6163 # uncoverable condition left count:1 class:ignore_covered_err */
6164 1 ▶ if (c->wbuf) free(c->wbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->wbuf) free(c->wbuf); 1 0 1
6165 /*
6166 # uncoverable branch false class:ignore_covered_err
6167 # uncoverable condition right count:1 class:ignore_covered_err */
6168 1 ▶ if (c->rbuf) free(c->rbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->rbuf) free(c->rbuf); 1 0 1
6169 1 free(c);
6170 1 loop->conns[i] = NULL;
6171 }
6172 /*
6173 # uncoverable branch true class:ignore_covered_err
6174 # uncoverable condition left count:1 class:ignore_covered_err */
6175 11206656 ▶ if (loop->io_r[i].sv) SvREFCNT_dec(loop->io_r[i].sv);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->io_r[i].sv) SvREFCNT_dec(loop->io_r[i].sv); 0 11206656 11206656
6176 /*
6177 # uncoverable statement class:ignore_covered_err
6178 # uncoverable branch true
6179 # uncoverable condition left count:1 */
6180 11206656 ▶ if (loop->io_w[i].sv) SvREFCNT_dec(loop->io_w[i].sv);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->io_w[i].sv) SvREFCNT_dec(loop->io_w[i].sv); 0 11206656 11206656
6181 }
6182 310 ▶ while (loop->pool) {
Branch: 1 branch
BranchTrueFalseTotal
while (loop->pool) { 139 171 310
6183 139 hm_conn *c = loop->pool;
6184 139 loop->pool = c->pool_next;
6185 139 ▶ if (c->wbuf) free(c->wbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->wbuf) free(c->wbuf); 117 22 139
6186 139 ▶ if (c->rbuf) free(c->rbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->rbuf) free(c->rbuf); 138 1 139
6187 139 free(c);
6188 }
6189 171 ▶ if (loop->log_fd >= 0 && owned) { hm_log_flush(loop); hm_os_close(loop->log_fd); } /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (loop->log_fd >= 0 && owned) { hm_log_flush(loop); hm_os_close(loop->log_fd); } /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 163 171
if (loop->log_fd >= 0 && owned) { hm_log_flush(loop); hm_os_close(loop->log_fd); } /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 0 8
6190 171 ▶ if (loop->log_buf) free(loop->log_buf);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_buf) free(loop->log_buf); 8 163 171
6191 316 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 145 171 316
6192 /* Before the fds: freeing a connection writes a CONNECTION_CLOSE. */
6193 /*
6194 # uncoverable branch false class:ignore_covered_err
6195 # uncoverable condition right count:1 class:ignore_covered_err */
6196 145 ▶ if (owned) hm_quic_srv_free(aTHX_ &loop->listeners[i]);
Branch: 1 branch
BranchTrueFalseTotal
if (owned) hm_quic_srv_free(aTHX_ &loop->listeners[i]); 145 0 145
6197 /*
6198 # uncoverable branch false class:ignore_covered_err
6199 # uncoverable condition right count:1 class:ignore_covered_err */
6200 145 ▶ if (loop->listeners[i].host) free(loop->listeners[i].host);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].host) free(loop->listeners[i].host); 145 0 145
6201 /*
6202 # uncoverable branch true class:ignore_covered_err
6203 # uncoverable condition left count:1 class:ignore_covered_err */
6204 145 ▶ if (loop->listeners[i].altsvc) free(loop->listeners[i].altsvc);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].altsvc) free(loop->listeners[i].altsvc); 0 145 145
6205 145 ▶ if (loop->listeners[i].tls_sni) SvREFCNT_dec(loop->listeners[i].tls_sni);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].tls_sni) SvREFCNT_dec(loop->listeners[i].tls_sni); 4 141 145
6206 /* `owned` for the same reason every other descriptor here is: a loop
6207 * belonging to another process holds fd NUMBERS that are ours, and
6208 * closing them would close whatever this process has since put
6209 * there. An inherited UDP listener is the third case of that, after
6210 * the backend descriptor and the connections. */
6211 /*
6212 # uncoverable branch true class:ignore_covered_err
6213 # uncoverable condition left count:1 class:ignore_covered_err
6214 # uncoverable condition left count:2 class:ignore_covered_err
6215 # uncoverable condition right count:2 class:ignore_covered_err */
6216 145 ▶ if (loop->listeners[i].udp_fd >= 0 && owned)
Branch: 2 branches
BranchTrueFalseTotal
if (loop->listeners[i].udp_fd >= 0 && owned) 0 145 145
if (loop->listeners[i].udp_fd >= 0 && owned) 0 0 0
6217 0 hm_os_close(loop->listeners[i].udp_fd); /* # uncoverable statement class:ignore_covered_err */
6218 }
6219 171 ▶ if (loop->listeners) free(loop->listeners);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners) free(loop->listeners); 134 37 171
6220 /* A weak copy of the wrapper (hm_loop_to_sv): dropping it frees the RV
6221 * alone and runs no DESTROY. */
6222 171 ▶ if (loop->self_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->self_sv) { 123 48 171
6223 123 SV *self = loop->self_sv;
6224 123 loop->self_sv = NULL;
6225 123 loop->perl_owned = 0;
6226 123 SvREFCNT_dec(self);
6227 }
6228 171 ▶ if (loop->log_cb) SvREFCNT_dec(loop->log_cb);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_cb) SvREFCNT_dec(loop->log_cb); 4 167 171
6229 171 ▶ if (loop->app) SvREFCNT_dec(loop->app);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->app) SvREFCNT_dec(loop->app); 134 37 171
6230 171 SvREFCNT_dec((SV *)loop->deferred);
6231 171 ▶ if (loop->again) free(loop->again);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->again) free(loop->again); 8 163 171
6232 171 ▶ if (loop->hidx) free(loop->hidx);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->hidx) free(loop->hidx); 1 170 171
6233 171 ▶ if (loop->sweep_tw) free(loop->sweep_tw);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->sweep_tw) free(loop->sweep_tw); 134 37 171
6234 171 ▶ if (loop->hardstop_tw) free(loop->hardstop_tw);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->hardstop_tw) free(loop->hardstop_tw); 1 170 171
6235 /*
6236 # uncoverable branch true class:ignore_covered_err
6237 # uncoverable condition left count:1 class:ignore_covered_err */
6238 171 ▶ if (loop->qheap.a) free(loop->qheap.a);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->qheap.a) free(loop->qheap.a); 0 171 171
6239 /* destroy() releases the backend's memory either way; `foreign` is what
6240 * stops it closing descriptors that are not ours - see the note above */
6241 171 ▶ if (!owned) loop->be->foreign = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!owned) loop->be->foreign = 1; 6 165 171
6242 171 loop->be->destroy(loop->be);
6243 171 free(loop->conns);
6244 171 free(loop->io_r);
6245 171 free(loop->io_w);
6246 171 free(loop);
6247 }
6248  
6249 /* Attach the PSGI server to a loop: listener, shutdown/stats signals via
6250 * the backend's signal watcher, and the timeout sweep timer. */
6251 134 static void hm_attach_server(pTHX_ hm_loop *loop, SV *app) {
6252 int i;
6253 134 loop->app = SvREFCNT_inc(app);
6254 134 loop->attached = 1;
6255 279 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 145 134 279
6256 145 loop->be->add_io(loop->be, loop->listeners[i].fd, HM_EV_READ, 0);
6257 /*
6258 # uncoverable branch true class:ignore_covered_err
6259 # uncoverable condition left count:1 class:ignore_covered_err */
6260 145 ▶ if (loop->listeners[i].udp_fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].udp_fd >= 0) { 0 145 145
6261 /* After the fork, in the worker that will serve: the SSL_CTX and
6262 * the CID table belong to this process alone. */
6263 0 hm_quic_srv_attach(aTHX_ loop, &loop->listeners[i], i); /* # uncoverable statement class:ignore_covered_err */
6264 0 loop->be->add_io(loop->be, loop->listeners[i].udp_fd, HM_EV_READ, 0); /* # uncoverable statement class:ignore_covered_err */
6265 }
6266 }
6267 #ifndef _WIN32
6268 /* Ignore the default dispositions: these arrive through the backend's
6269 * signal watcher instead. Windows has no signal to ignore - the
6270 * WSAPoll backend's console handler is the only source there. */
6271 134 signal(SIGPIPE, SIG_IGN);
6272 134 signal(SIGTERM, SIG_IGN);
6273 134 signal(SIGINT, SIG_IGN);
6274 134 signal(SIGUSR1, SIG_IGN);
6275 #endif
6276 134 loop->be->add_signal(loop->be, SIGTERM);
6277 134 loop->be->add_signal(loop->be, SIGINT);
6278 134 loop->be->add_signal(loop->be, SIGUSR1);
6279 134 loop->sweep_tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
6280 134 loop->sweep_tw->kind = HM_TW_SWEEP;
6281 134 loop->sweep_tw->loop = loop;
6282 /*
6283 # uncoverable branch true class:ignore_covered_err
6284 # uncoverable condition left count:1 class:ignore_covered_err */
6285 134 ▶ if (loop->be->add_timer(loop->be, HM_SWEEP_SECS, 0, loop->sweep_tw) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (loop->be->add_timer(loop->be, HM_SWEEP_SECS, 0, loop->sweep_tw) < 0) 0 134 134
6286 0 hm_errlog("Hyperman: cannot arm the timeout sweep: %s\n", strerror(errno)); /* # uncoverable statement class:ignore_covered_err */
6287 134 }
6288  
6289 /* register a timer watcher resolving a Future / running a callback */
6290 2061 static void hm_add_timer_watch(pTHX_ hm_loop *loop, double secs, SV *sv, int kind) {
6291 2061 hm_tw *tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
6292 2061 tw->kind = kind;
6293 2061 tw->sv = SvREFCNT_inc(sv);
6294 2061 tw->loop = loop;
6295 2061 tw->due = hm_tw_due(secs);
6296 /* A backend can refuse: on epoll every timer is a descriptor, so under
6297 * EMFILE there is none to be had. Silently dropping it left a ->get on
6298 * the timer's future pumping the loop for ever. */
6299 /*
6300 # uncoverable branch true class:ignore_covered_err
6301 # uncoverable condition left count:1 class:ignore_covered_err
6302 # uncoverable condition right count:1 class:ignore_covered_err
6303 # uncoverable condition left count:2 class:ignore_covered_err */
6304 2061 ▶ if (!HM_LOOP_INHERITED(loop) && loop->be->add_timer(loop->be, secs, 1, tw) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop) && loop->be->add_timer(loop->be, secs, 1, tw) < 0) { 2061 0 2061
if (!HM_LOOP_INHERITED(loop) && loop->be->add_timer(loop->be, secs, 1, tw) < 0) { 0 2061 2061
6305 0 int e = errno; /* # uncoverable statement */
6306 0 SvREFCNT_dec(sv); /* # uncoverable statement */
6307 0 free(tw); /* # uncoverable statement */
6308 0 croak("Hyperman: cannot arm a timer: %s", strerror(e)); /* # uncoverable statement */
6309 }
6310 2061 }
6311  
6312 /* Let go of whatever a watcher slot held. A one-shot future that was still
6313 * pending is CANCELLED, not dropped: a `->get` waiting on it would otherwise
6314 * pump the loop for a readiness nothing is watching for any more. */
6315 143 static void hm_iow_release_sv(pTHX_ SV *sv, int is_cb) {
6316 143 ▶ if (!sv) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return; 136 7 143
6317 /*
6318 # uncoverable condition right count:2 class:ignore_covered_err
6319 # uncoverable condition right count:3 class:ignore_covered_err */
6320 7 ▶ if (!is_cb && hmf_is_future(aTHX_ sv) && hmf_state(aTHX_ sv) == HMF_PENDING)
Branch: 3 branches
BranchTrueFalseTotal
if (!is_cb && hmf_is_future(aTHX_ sv) && hmf_state(aTHX_ sv) == HMF_PENDING) 3 4 7
if (!is_cb && hmf_is_future(aTHX_ sv) && hmf_state(aTHX_ sv) == HMF_PENDING) 3 0 3
if (!is_cb && hmf_is_future(aTHX_ sv) && hmf_state(aTHX_ sv) == HMF_PENDING) 3 0 3
6321 3 hmf_cancel(aTHX_ sv);
6322 7 SvREFCNT_dec(sv);
6323 }
6324  
6325 /* The slot is EMPTIED before the old occupant is released, and the new
6326 * occupant (where there is one) is seated before that too: releasing a
6327 * pending future fires its callbacks, and one of those may watch this same
6328 * fd again. With the release first, that inner registration landed in the
6329 * slot and was then overwritten by the outer one - a future that never
6330 * fired - or, on the remove path, was left in a slot whose kind had been
6331 * reset, so the next event settled a callback CV as if it were a future. */
6332 /*
6333 # uncoverable statement
6334 # uncoverable subroutine */
6335 0 static void hm_iow_release(pTHX_ hm_iow *slot) {
6336 0 SV *sv = slot->sv; /* # uncoverable statement */
6337 0 int is_cb = slot->is_cb; /* # uncoverable statement */
6338 /*
6339 # uncoverable statement
6340 # uncoverable branch true
6341 # uncoverable branch false
6342 # uncoverable condition left count:1
6343 # uncoverable condition right count:1 */
6344 0 ▶ if (!sv) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return; 0 0 0
6345 0 slot->sv = NULL; /* # uncoverable statement */
6346 0 hm_iow_release_sv(aTHX_ sv, is_cb); /* # uncoverable statement */
6347 }
6348  
6349 15 static void hm_add_io_watch(pTHX_ hm_loop *loop, int fd, const char *mode,
6350 SV *sv, int is_cb) {
6351 hm_iow *slot;
6352 SV *old;
6353 int old_cb;
6354 int mask;
6355 /*
6356 # uncoverable branch true class:ignore_covered_err
6357 # uncoverable condition left count:1 class:ignore_covered_err
6358 # uncoverable condition left count:2 class:ignore_covered_err */
6359 15 ▶ if (fd < 0 || fd >= HM_MAXFD) croak("Hyperman: bad fd %d", fd);
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 || fd >= HM_MAXFD) croak("Hyperman: bad fd %d", fd); 15 0 15
if (fd < 0 || fd >= HM_MAXFD) croak("Hyperman: bad fd %d", fd); 0 15 15
6360 15 ▶ if (mode[0] == 'w') { slot = &loop->io_w[fd]; mask = HM_EV_WRITE; }
Branch: 1 branch
BranchTrueFalseTotal
if (mode[0] == 'w') { slot = &loop->io_w[fd]; mask = HM_EV_WRITE; } 1 14 15
6361 14 else { slot = &loop->io_r[fd]; mask = HM_EV_READ; }
6362 15 old = slot->sv;
6363 15 old_cb = slot->is_cb;
6364 15 slot->sv = SvREFCNT_inc(sv);
6365 15 slot->is_cb = (unsigned char)is_cb;
6366 15 slot->c_cb = NULL;
6367 15 slot->c_ud = NULL;
6368 /*
6369 # uncoverable branch false class:ignore_covered_err
6370 # uncoverable condition right count:1 class:ignore_covered_err */
6371 15 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 15 0 15
6372 15 loop->be->add_io(loop->be, fd, mask, is_cb ? 0 : 1);
6373 15 hm_iow_release_sv(aTHX_ old, old_cb);
6374 15 }
6375  
6376 /* ABI: persistent C watcher, replacing whatever held the slot. */
6377 121 static void hm_add_io_watch_c(pTHX_ hm_loop *loop, int fd, int mask,
6378 hm_abi_io_cb cb, void *ud) {
6379 hm_iow *slot;
6380 SV *old;
6381 int old_cb;
6382 /*
6383 # uncoverable branch true class:ignore_covered_err
6384 # uncoverable condition left count:1 class:ignore_covered_err
6385 # uncoverable condition left count:2 class:ignore_covered_err */
6386 121 ▶ if (fd < 0 || fd >= HM_MAXFD) croak("Hyperman: bad fd %d", fd);
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 || fd >= HM_MAXFD) croak("Hyperman: bad fd %d", fd); 121 0 121
if (fd < 0 || fd >= HM_MAXFD) croak("Hyperman: bad fd %d", fd); 0 121 121
6387 121 ▶ slot = (mask & HM_EV_WRITE) ? &loop->io_w[fd] : &loop->io_r[fd]; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
slot = (mask & HM_EV_WRITE) ? &loop->io_w[fd] : &loop->io_r[fd]; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 121 121
6388 121 old = slot->sv;
6389 121 old_cb = slot->is_cb;
6390 121 slot->sv = NULL;
6391 121 slot->is_cb = 0;
6392 121 slot->c_cb = cb;
6393 121 slot->c_ud = ud;
6394 /*
6395 # uncoverable branch false class:ignore_covered_err
6396 # uncoverable condition right count:1 class:ignore_covered_err */
6397 121 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 121 0 121
6398 121 loop->be->add_io(loop->be, fd,
6399 121 ▶ (mask & HM_EV_WRITE) ? HM_EV_WRITE : HM_EV_READ, 0); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
(mask & HM_EV_WRITE) ? HM_EV_WRITE : HM_EV_READ, 0); /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 121 121
6400 121 hm_iow_release_sv(aTHX_ old, old_cb);
6401 121 }
6402  
6403 /* Drop one direction's watcher (any kind); idempotent. */
6404 7 static void hm_del_io_watch(pTHX_ hm_loop *loop, int fd, int mask) {
6405 hm_iow *slot;
6406 SV *old;
6407 int old_cb;
6408 /*
6409 # uncoverable branch true class:ignore_covered_err
6410 # uncoverable condition left count:1 class:ignore_covered_err
6411 # uncoverable condition left count:2 class:ignore_covered_err */
6412 7 ▶ if (fd < 0 || fd >= HM_MAXFD) return;
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 || fd >= HM_MAXFD) return; 7 0 7
if (fd < 0 || fd >= HM_MAXFD) return; 0 7 7
6413 7 ▶ slot = (mask & HM_EV_WRITE) ? &loop->io_w[fd] : &loop->io_r[fd]; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
slot = (mask & HM_EV_WRITE) ? &loop->io_w[fd] : &loop->io_r[fd]; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 7 7
6414 /*
6415 # uncoverable branch true class:ignore_covered_err
6416 # uncoverable condition left count:1 class:ignore_covered_err
6417 # uncoverable condition left count:2 class:ignore_covered_err */
6418 7 ▶ if (!slot->sv && !slot->c_cb) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!slot->sv && !slot->c_cb) return; 1 6 7
if (!slot->sv && !slot->c_cb) return; 0 1 1
6419 7 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 5 2 7
6420 5 loop->be->remove_io(loop->be, fd,
6421 5 ▶ (mask & HM_EV_WRITE) ? HM_EV_WRITE : HM_EV_READ); /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
(mask & HM_EV_WRITE) ? HM_EV_WRITE : HM_EV_READ); /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 5 5
6422 7 old = slot->sv;
6423 7 old_cb = slot->is_cb;
6424 7 slot->sv = NULL;
6425 7 slot->is_cb = 0;
6426 7 slot->c_cb = NULL;
6427 7 slot->c_ud = NULL;
6428 7 hm_iow_release_sv(aTHX_ old, old_cb);
6429 }
6430  
6431 /* ABI: one-shot C timer; the returned watcher doubles as the cancel handle
6432 * (freed on fire or on cancel, never both - single-threaded). */
6433 26933 static hm_tw *hm_add_timer_watch_c(hm_loop *loop, double secs,
6434 hm_abi_timer_cb cb, void *ud) {
6435 26933 hm_tw *tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
6436 26933 tw->kind = HM_TW_C;
6437 26933 tw->loop = loop;
6438 26933 tw->c_cb = cb;
6439 26933 tw->c_ud = ud;
6440 26933 tw->due = hm_tw_due(secs);
6441 26933 ▶ if (loop->be->add_timer(loop->be, secs, 1, tw) < 0) { /* # uncoverable branch true class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->be->add_timer(loop->be, secs, 1, tw) < 0) { /* # uncoverable branch true class:ignore_covered_err */ 26510 423 26933
6442 /* NULL, and a line in the log: the C callers (the scoreboard tick,
6443 * the bus poll, the accept re-arm) each have a fallback or a reason
6444 * to be loud, and an ABI consumer is told the handle is NULL. */
6445 26510 hm_errlog("Hyperman: cannot arm a %.3fs timer: %s\n", secs, strerror(errno)); /* # uncoverable statement class:ignore_covered_err */
6446 26510 free(tw); /* # uncoverable statement class:ignore_covered_err */
6447 26510 return NULL; /* # uncoverable statement class:ignore_covered_err */
6448 }
6449 423 return tw;
6450 }
6451  
6452 11 static void hm_del_timer_watch(pTHX_ hm_loop *loop, hm_tw *tw) {
6453 /*
6454 # uncoverable branch true class:ignore_covered_err
6455 # uncoverable condition left count:1 class:ignore_covered_err
6456 # uncoverable condition left count:2 class:ignore_covered_err */
6457 11 ▶ if (!tw || tw->dead) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!tw || tw->dead) return; 11 0 11
if (!tw || tw->dead) return; 0 11 11
6458 /*
6459 # uncoverable branch false class:ignore_covered_err
6460 # uncoverable condition right count:1 class:ignore_covered_err */
6461 11 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 11 0 11
6462 11 loop->be->del_timer(loop->be, tw);
6463 /*
6464 # uncoverable branch true class:ignore_covered_err
6465 # uncoverable condition left count:1 class:ignore_covered_err */
6466 11 ▶ if (tw->sv) { SvREFCNT_dec(tw->sv); tw->sv = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (tw->sv) { SvREFCNT_dec(tw->sv); tw->sv = NULL; } 0 11 11
6467 /* Not freed here: an event naming it may already be in the batch being
6468 * dispatched (see hm_tw.dead). hm_dispatch skips it; hm_tw_gy_sweep
6469 * frees it once the outermost loop's batch is done. */
6470 11 tw->dead = 1;
6471 11 tw->gy_next = loop->tw_gy;
6472 11 loop->tw_gy = tw;
6473 }
6474  
6475 /* Free the cancelled timers. Only between batches of the OUTERMOST loop
6476 * run: a nested run (a handler's ->get) sits inside one of the outer
6477 * batch's events, and the outer batch may still name any of them. */
6478 182 static void hm_tw_gy_sweep(hm_loop *loop) {
6479 182 hm_tw *tw = loop->tw_gy, *n;
6480 182 loop->tw_gy = NULL;
6481 193 ▶ while (tw) { n = tw->gy_next; free(tw); tw = n; }
Branch: 1 branch
BranchTrueFalseTotal
while (tw) { n = tw->gy_next; free(tw); tw = n; } 11 182 193
6482 182 }
6483  
6484 9 static hm_loop *hm_need_loop(void) {
6485 9 ▶ if (!hm_cur_loop)
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_cur_loop) 1 8 9
6486 1 croak("Hyperman: no event loop is running in this process");
6487 8 return hm_cur_loop;
6488 }
6489  
6490 /* ---- listener + process model -------------------------------------------- */
6491  
6492 /* Create, bind, and listen a non-blocking TCP socket. Returns fd or -1. */
6493 /* Resolve a listen address ONCE, at startup: an IPv4 or IPv6 literal (with
6494 * or without brackets), a hostname, or nothing for every IPv4 interface.
6495 * getaddrinfo's first answer is taken. Failure is an error string for the
6496 * croak and never a silent fallback: a host that did not parse used to bind
6497 * INADDR_ANY, which exposed the service on every interface for a typo. */
6498 108 static int hm_resolve(const char *host, int port, int socktype,
6499 struct sockaddr_storage *out, socklen_t *outlen,
6500 char *err, size_t errlen) {
6501 108 struct addrinfo hints, *res = NULL;
6502 char hbuf[256], pbuf[16];
6503 108 const char *h = host;
6504 int rc;
6505 /*
6506 # uncoverable branch true class:ignore_covered_err
6507 # uncoverable condition left count:1 class:ignore_covered_err
6508 # uncoverable condition left count:2 class:ignore_covered_err */
6509 108 ▶ if (!h || !*h) h = "0.0.0.0";
Branch: 2 branches
BranchTrueFalseTotal
if (!h || !*h) h = "0.0.0.0"; 108 0 108
if (!h || !*h) h = "0.0.0.0"; 0 108 108
6510 108 ▶ if (h[0] == '[') {
Branch: 1 branch
BranchTrueFalseTotal
if (h[0] == '[') { 2 106 108
6511 2 size_t l = strlen(h);
6512 /*
6513 # uncoverable condition left count:1 class:ignore_covered_err
6514 # uncoverable condition left count:3 class:ignore_covered_err */
6515 2 ▶ if (l < 3 || h[l - 1] != ']' || l - 2 >= sizeof(hbuf)) {
Branch: 3 branches
BranchTrueFalseTotal
if (l < 3 || h[l - 1] != ']' || l - 2 >= sizeof(hbuf)) { 2 0 2
if (l < 3 || h[l - 1] != ']' || l - 2 >= sizeof(hbuf)) { 1 1 2
if (l < 3 || h[l - 1] != ']' || l - 2 >= sizeof(hbuf)) { 0 1 1
6516 1 snprintf(err, errlen, "malformed bracketed address");
6517 1 return -1;
6518 }
6519 1 memcpy(hbuf, h + 1, l - 2);
6520 1 hbuf[l - 2] = '\0';
6521 1 h = hbuf;
6522 }
6523 107 memset(&hints, 0, sizeof(hints));
6524 107 hints.ai_family = AF_UNSPEC;
6525 107 hints.ai_socktype = socktype;
6526 107 hints.ai_flags = AI_NUMERICSERV | AI_PASSIVE;
6527 107 snprintf(pbuf, sizeof(pbuf), "%d", port);
6528 107 rc = getaddrinfo(h, pbuf, &hints, &res);
6529 /*
6530 # uncoverable branch true class:ignore_covered_err
6531 # uncoverable condition left count:1 class:ignore_covered_err
6532 # uncoverable condition left count:2 class:ignore_covered_err */
6533 107 ▶ if (rc != 0 || !res) {
Branch: 2 branches
BranchTrueFalseTotal
if (rc != 0 || !res) { 107 0 107
if (rc != 0 || !res) { 0 107 107
6534 /*
6535 # uncoverable statement class:ignore_covered_err
6536 # uncoverable condition left count:1 class:ignore_covered_err
6537 # uncoverable condition right count:1 class:ignore_covered_err */
6538 0 ▶ snprintf(err, errlen, "%s", rc ? gai_strerror(rc) : "no address");
Branch: 1 branch
BranchTrueFalseTotal
snprintf(err, errlen, "%s", rc ? gai_strerror(rc) : "no address"); 0 0 0
6539 /*
6540 # uncoverable statement class:ignore_covered_err
6541 # uncoverable branch true class:ignore_covered_err
6542 # uncoverable branch false class:ignore_covered_err
6543 # uncoverable condition left count:1 class:ignore_covered_err
6544 # uncoverable condition right count:1 class:ignore_covered_err */
6545 0 ▶ if (res) freeaddrinfo(res);
Branch: 1 branch
BranchTrueFalseTotal
if (res) freeaddrinfo(res); 0 0 0
6546 0 return -1; /* # uncoverable statement class:ignore_covered_err */
6547 }
6548 /*
6549 # uncoverable branch true
6550 # uncoverable condition left count:1 class:ignore_covered_err */
6551 107 ▶ if (res->ai_addrlen > sizeof(*out)) { freeaddrinfo(res); snprintf(err, errlen, "address too long"); return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (res->ai_addrlen > sizeof(*out)) { freeaddrinfo(res); snprintf(err, errlen, "address too long"); return -1; } 0 107 107
6552 107 memcpy(out, res->ai_addr, res->ai_addrlen);
6553 107 *outlen = (socklen_t)res->ai_addrlen;
6554 107 freeaddrinfo(res);
6555 107 return 0;
6556 }
6557  
6558 /* A unix-domain address. sun_path is 104 bytes on macOS and 108 on Linux,
6559 * and a path that does not fit is refused rather than truncated. */
6560 7 static int hm_resolve_unix(const char *path, struct sockaddr_storage *out,
6561 socklen_t *outlen, char *err, size_t errlen) {
6562 #ifdef _WIN32
6563 (void)path; (void)out; (void)outlen;
6564 snprintf(err, errlen, "unix-domain listeners are not supported on Windows");
6565 return -1;
6566 #else
6567 7 struct sockaddr_un *un = (struct sockaddr_un *)out;
6568 7 size_t l = strlen(path);
6569 7 ▶ if (l == 0 || l >= sizeof(un->sun_path)) { /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (l == 0 || l >= sizeof(un->sun_path)) { /* # uncoverable condition left count:1 class:ignore_covered_err */ 7 0 7
if (l == 0 || l >= sizeof(un->sun_path)) { /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 6 7
6570 1 snprintf(err, errlen, "path is empty or longer than %d bytes",
6571 (int)sizeof(un->sun_path) - 1);
6572 1 return -1;
6573 }
6574 6 memset(out, 0, sizeof(*out));
6575 6 un->sun_family = AF_UNIX;
6576 6 memcpy(un->sun_path, path, l + 1);
6577 6 *outlen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + l + 1);
6578 6 return 0;
6579 #endif
6580 }
6581  
6582 /* An IPv6 listener is v6 ONLY, so `::` and `0.0.0.0` can both be listed on
6583 * one port; without it the second bind fails on Linux and the v4-mapped
6584 * addresses the dual-stack socket would report differ by platform. */
6585 87 static void hm_v6only(int fd, const struct sockaddr *sa) {
6586 #ifdef IPV6_V6ONLY
6587 /*
6588 # uncoverable branch true class:ignore_covered_err
6589 # uncoverable condition left count:1 class:ignore_covered_err */
6590 87 ▶ if (sa->sa_family == AF_INET6) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa->sa_family == AF_INET6) { 0 87 87
6591 0 int one = 1; /* # uncoverable statement class:ignore_covered_err */
6592 0 hm_os_setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)); /* # uncoverable statement class:ignore_covered_err */
6593 }
6594 #else
6595 (void)fd; (void)sa;
6596 #endif
6597 87 }
6598  
6599 88 static int hm_make_listener(const struct sockaddr *sa, socklen_t salen, int reuseport) {
6600 88 int one = 1;
6601 int fd;
6602 #ifndef _WIN32
6603 /* A path listener: a socket file left by an earlier run is replaced; a
6604 * regular file at the path is somebody else's and is refused. */
6605 88 ▶ if (sa->sa_family == AF_UNIX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa->sa_family == AF_UNIX) { 3 85 88
6606 3 const char *p = ((const struct sockaddr_un *)sa)->sun_path;
6607 struct stat st;
6608 3 ▶ if (stat(p, &st) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (stat(p, &st) == 0) { 2 1 3
6609 int pfd;
6610 2 ▶ if (!S_ISSOCK(st.st_mode)) { errno = EEXIST; return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (!S_ISSOCK(st.st_mode)) { errno = EEXIST; return -1; } 1 1 2
6611 /* Somebody answering at the path is a live server, and this
6612 * would have unlinked its socket from under it (a second
6613 * instance started by mistake took the path silently). Refused
6614 * as a TCP bind of a busy port is. */
6615 1 pfd = hm_os_socket(AF_UNIX, SOCK_STREAM, 0);
6616 /*
6617 # uncoverable branch false class:ignore_covered_err
6618 # uncoverable condition right count:1 class:ignore_covered_err */
6619 1 ▶ if (pfd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pfd >= 0) { 1 0 1
6620 1 int alive = connect(pfd, sa, salen) == 0;
6621 1 hm_os_close(pfd);
6622 /*
6623 # uncoverable branch true
6624 # uncoverable condition left count:1 class:ignore_covered_err */
6625 1 ▶ if (alive) { errno = EADDRINUSE; return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (alive) { errno = EADDRINUSE; return -1; } 0 1 1
6626 }
6627 1 (void)unlink(p);
6628 }
6629 }
6630 #endif
6631 87 fd = hm_os_socket(sa->sa_family, SOCK_STREAM, 0);
6632 /*
6633 # uncoverable branch true
6634 # uncoverable condition left count:1 class:ignore_covered_err */
6635 87 ▶ if (fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return -1; 0 87 87
6636 #ifndef _WIN32
6637 /* Not into anything the application execs. A re-exec successor is the
6638 * one program meant to inherit it, and hm_reexec clears this for that
6639 * child alone. */
6640 87 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
6641 #endif
6642 87 hm_v6only(fd, sa);
6643 #ifdef _WIN32
6644 /* SO_REUSEADDR on Windows lets a second bind STEAL a live listener,
6645 * which is the opposite of the Unix meaning we want here (rebind a
6646 * TIME_WAIT port). SO_EXCLUSIVEADDRUSE is the flag that buys what
6647 * SO_REUSEADDR buys everywhere else. */
6648 hm_os_setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &one, sizeof(one));
6649 #else
6650 87 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
6651 #endif
6652 #ifdef SO_REUSEPORT
6653 87 ▶ if (reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (reuseport) 3 84 87
6654 3 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
6655 #else
6656 (void)reuseport;
6657 #endif
6658 87 ▶ if (hm_os_bind(fd, sa, salen) < 0) { /* # uncoverable branch true class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
if (hm_os_bind(fd, sa, salen) < 0) { /* # uncoverable branch true class:ignore_covered_err */ 1 86 87
6659 1 hm_os_close(fd); return -1; /* # uncoverable statement class:ignore_covered_err */
6660 }
6661 /*
6662 # uncoverable branch true
6663 # uncoverable condition left count:1 class:ignore_covered_err */
6664 86 ▶ if (hm_os_listen(fd, SOMAXCONN) < 0) { hm_os_close(fd); return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (hm_os_listen(fd, SOMAXCONN) < 0) { hm_os_close(fd); return -1; } 0 86 86
6665 86 hm_set_nonblock(fd);
6666 86 return fd;
6667 }
6668  
6669 /* The QUIC listener: the same address as its TCP twin, over UDP. No
6670 * listen(2) - there is no accept queue, because there is no accept: one
6671 * socket carries every connection and the Destination Connection ID in each
6672 * packet says which (hm_quic.h). SO_REUSEPORT is honoured the same way, and
6673 * carries the same caveat the TCP side does not have: the kernel's UDP
6674 * reuseport hash is over the 4-tuple, so a client that migrates lands on a
6675 * different worker than the one holding its connection. That is why
6676 * migration is deferred rather than half-supported. */
6677 /*
6678 # uncoverable statement class:ignore_covered_err
6679 # uncoverable subroutine class:ignore_covered_err */
6680 0 static int hm_make_udp_listener(const struct sockaddr *sa, socklen_t salen, int reuseport) {
6681 0 int one = 1; /* # uncoverable statement class:ignore_covered_err */
6682 0 int fd = hm_os_socket(sa->sa_family, SOCK_DGRAM, 0); /* # uncoverable statement class:ignore_covered_err */
6683 /*
6684 # uncoverable branch true class:ignore_covered_err
6685 # uncoverable statement class:ignore_covered_err
6686 # uncoverable branch false class:ignore_covered_err
6687 # uncoverable condition left count:1 class:ignore_covered_err
6688 # uncoverable condition right count:1 class:ignore_covered_err */
6689 0 ▶ if (fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return -1; 0 0 0
6690 #ifndef _WIN32
6691 0 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); /* # uncoverable statement class:ignore_covered_err */
6692 #endif
6693 0 hm_v6only(fd, sa); /* # uncoverable statement class:ignore_covered_err */
6694 #ifdef _WIN32
6695 hm_os_setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &one, sizeof(one));
6696 #else
6697 0 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); /* # uncoverable statement class:ignore_covered_err */
6698 #endif
6699 #ifdef SO_REUSEPORT
6700 /*
6701 # uncoverable statement class:ignore_covered_err
6702 # uncoverable branch true class:ignore_covered_err
6703 # uncoverable branch false class:ignore_covered_err
6704 # uncoverable condition left count:1 class:ignore_covered_err
6705 # uncoverable condition right count:1 class:ignore_covered_err */
6706 0 ▶ if (reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (reuseport) 0 0 0
6707 0 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)); /* # uncoverable statement */
6708 #else
6709 (void)reuseport;
6710 #endif
6711 /*
6712 # uncoverable branch true class:ignore_covered_err
6713 # uncoverable statement class:ignore_covered_err
6714 # uncoverable branch false class:ignore_covered_err
6715 # uncoverable condition left count:1 class:ignore_covered_err
6716 # uncoverable condition right count:1 class:ignore_covered_err */
6717 0 ▶ if (hm_os_bind(fd, sa, salen) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_os_bind(fd, sa, salen) < 0) { 0 0 0
6718 0 hm_os_close(fd); return -1; /* # uncoverable statement */
6719 }
6720 0 hm_set_nonblock(fd); /* # uncoverable statement class:ignore_covered_err */
6721 0 return fd; /* # uncoverable statement class:ignore_covered_err */
6722 }
6723  
6724 /* ---- the supervisor half: POSIX only --------------------------------------
6725 * Everything from here to the end of hm_run_server's pool branch needs
6726 * fork(2), waitpid(2) and POSIX signal delivery. Windows has none of the
6727 * three, and perl's fork emulation is ithreads - N interpreters inside ONE
6728 * process, sharing the file-scope state this server keeps per process - so
6729 * a pool there would corrupt, not scale. Windows runs the single-worker
6730 * in-process path instead (hm_run_server, above the pool branch), and an
6731 * explicit workers > 1 is refused at boot. */
6732 #ifndef _WIN32
6733  
6734 /* Supervisor signal flags: TERM/INT = shut the pool down, HUP/USR2 =
6735 * recycle workers with zero downtime, USR1 = stats dump. */
6736 static volatile sig_atomic_t hm_sup_term = 0;
6737 static volatile sig_atomic_t hm_sup_hup = 0;
6738 static volatile sig_atomic_t hm_sup_usr1 = 0;
6739 static volatile sig_atomic_t hm_sup_tick = 0; /* ALRM: the liveness look */
6740 static volatile sig_atomic_t hm_sup_usr2 = 0; /* re-exec a successor */
6741 /* The successor supervisor a USR2 started, until it has taken over (it
6742 * TERMs us) or died trying (the reaper clears it). */
6743 static pid_t hm_resup_pid = 0;
6744 /* What this process was started as, for the exec: $^X and perl's argv from
6745 * the first argument on. Copied at BOOT, because `$0 = ...` on Linux writes
6746 * over the memory PL_origargv points into. */
6747 static char **hm_boot_argv = NULL;
6748 /* Set in a successor: the supervisor that handed its sockets over and is
6749 * told to drain once this pool is up. */
6750 static pid_t hm_resup_old = 0;
6751 /* An alarm the caller had pending when run() was called: the deadline it asked
6752 * for, and whether it has come due. The supervisor's tick owns SIGALRM, so the
6753 * caller's is carried rather than cancelled. */
6754 static time_t hm_sup_alarm_at = 0;
6755 static int hm_sup_alarmed = 0;
6756 85 static void hm_sup_sig(int sig) {
6757 85 ▶ if (sig == SIGHUP) hm_sup_hup = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (sig == SIGHUP) hm_sup_hup = 1; 2 83 85
6758 83 ▶ else if (sig == SIGUSR2) hm_sup_usr2 = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGUSR2) hm_sup_usr2 = 1; 5 78 83
6759 78 ▶ else if (sig == SIGUSR1) hm_sup_usr1 = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGUSR1) hm_sup_usr1 = 1; 5 73 78
6760 73 ▶ else if (sig == SIGALRM) hm_sup_tick = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGALRM) hm_sup_tick = 1; 3 70 73
6761 70 ▶ else if (sig == SIGCHLD) ; /* no-op: just wakes sigsuspend() */
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGCHLD) ; /* no-op: just wakes sigsuspend() */ 27 43 70
6762 27 else hm_sup_term = 1;
6763 85 }
6764  
6765 /* Wedged is not dead. A worker that is alive but has stopped turning its
6766 * loop keeps its pid and its row; what stops is the row's `updated` stamp,
6767 * which the one-second tick moves. Three looks three seconds apart with the
6768 * stamp unmoved and the pid answering kill(0) is the signal, logged once per
6769 * episode. The respawn policy is untouched: this says, it does not act. */
6770 #define HM_SUP_TICK_SECS 3
6771 #define HM_SUP_WEDGED_TICKS 3
6772 static uint64_t hm_child_seen[1024];
6773 static int hm_child_stale[1024];
6774  
6775 2 static void hm_sup_watch_board(void) {
6776 int i;
6777 /*
6778 # uncoverable branch true
6779 # uncoverable condition left count:1 class:ignore_covered_err */
6780 2 ▶ if (!hm_sa_board_live()) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_sa_board_live()) return; 0 2 2
6781 6 ▶ for (i = 0; i < hm_nchildren; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) { 4 2 6
6782 sa_sb_reading rd;
6783 4 pid_t pid = hm_children[i];
6784 /*
6785 # uncoverable branch true
6786 # uncoverable condition left count:1 class:ignore_covered_err */
6787 4 ▶ if (hm_sa_board_row_of((uint64_t)pid, &rd) < 0) { hm_child_stale[i] = 0; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_board_row_of((uint64_t)pid, &rd) < 0) { hm_child_stale[i] = 0; continue; } 0 4 4
6788 /*
6789 # uncoverable branch true
6790 # uncoverable condition left count:1 class:ignore_covered_err */
6791 4 ▶ if (kill(pid, 0) != 0) continue; /* gone: the reaper's business */
Branch: 1 branch
BranchTrueFalseTotal
if (kill(pid, 0) != 0) continue; /* gone: the reaper's business */ 0 4 4
6792 /*
6793 # uncoverable branch true
6794 # uncoverable condition left count:1 class:ignore_covered_err */
6795 4 ▶ if (rd.updated == hm_child_seen[i]) {
Branch: 1 branch
BranchTrueFalseTotal
if (rd.updated == hm_child_seen[i]) { 0 4 4
6796 /*
6797 # uncoverable statement
6798 # uncoverable branch true
6799 # uncoverable branch false
6800 # uncoverable condition left count:1
6801 # uncoverable condition right count:1 */
6802 0 ▶ if (++hm_child_stale[i] == HM_SUP_WEDGED_TICKS)
Branch: 1 branch
BranchTrueFalseTotal
if (++hm_child_stale[i] == HM_SUP_WEDGED_TICKS) 0 0 0
6803 0 hm_errlog("Hyperman: worker %d is alive but has not " /* # uncoverable statement */
6804 "updated its scoreboard row for %d seconds: wedged?\n",
6805 (int)pid, HM_SUP_TICK_SECS * HM_SUP_WEDGED_TICKS); /* # uncoverable statement */
6806 }
6807 else {
6808 4 hm_child_seen[i] = rd.updated;
6809 4 hm_child_stale[i] = 0;
6810 }
6811 }
6812 }
6813  
6814 /* What to exec on USR2: perl's own argv from the first argument on. $^X
6815 * supplies the interpreter at exec time. Copied at BOOT, because `$0 = ...`
6816 * on Linux writes over the memory PL_origargv points into. */
6817 148 static void hm_boot_argv_save(pTHX) {
6818 148 int i, n = PL_origargc;
6819 /*
6820 # uncoverable branch true class:ignore_covered_err
6821 # uncoverable condition left count:1 class:ignore_covered_err
6822 # uncoverable condition left count:2 class:ignore_covered_err */
6823 148 ▶ if (n <= 0 || !PL_origargv) return;
Branch: 2 branches
BranchTrueFalseTotal
if (n <= 0 || !PL_origargv) return; 148 0 148
if (n <= 0 || !PL_origargv) return; 0 148 148
6824 148 hm_boot_argv = (char **)hm_xmalloc(sizeof(char *) * (size_t)(n + 1));
6825 646 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 498 148 646
6826 498 ▶ const char *a = PL_origargv[i] ? PL_origargv[i] : ""; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
const char *a = PL_origargv[i] ? PL_origargv[i] : ""; /* # uncoverable condition right count:1 class:ignore_covered_err */ 498 0 498
6827 498 hm_boot_argv[i] = (char *)hm_xmalloc(strlen(a) + 1);
6828 498 memcpy(hm_boot_argv[i], a, strlen(a) + 1);
6829 }
6830 148 hm_boot_argv[n] = NULL;
6831 /* argv[0] becomes the interpreter path at exec; keep the name perl was
6832 * invoked under as its argv[0] */
6833 }
6834  
6835 #else
6836 /* No re-exec on Windows: there is no USR2 to ask for one. */
6837 #define hm_boot_argv_save(x) ((void)0)
6838 #endif /* !_WIN32 - the rest of this section is shared; hm_spawn and the
6839 * pool branch of hm_run_server re-open the guard below */
6840  
6841 /* One listener as configured by run(): its bind address, optional TLS, h2,
6842 * and https-redirect target. The bound fd and built SSL_CTX are filled in by
6843 * hm_run_server before the workers fork. */
6844 typedef struct {
6845 const char *host;
6846 int port;
6847 const char *path; /* a unix-domain listener instead of host:port */
6848 int mode_set, mode; /* its file mode, when given */
6849 int inherit; /* adopt this one from LISTEN_FDS */
6850 int proxy_protocol; /* every connection opens with a PROXY header */
6851 const char *tls_cert, *tls_key, *tls_ca;
6852 int tls_verify;
6853 SV *tls_sni;
6854 int http2;
6855 int http3;
6856 int redirect_https;
6857 int fd; /* bound fd (parent), or -1 under reuseport */
6858 int udp_fd; /* the QUIC socket, same rules; -1 if no h3 */
6859 void *tls_ctx; /* built SSL_CTX*, or NULL for plain */
6860 struct sockaddr_storage sa; /* host:port resolved once, in the parent; */
6861 socklen_t salen; /* what every bind, incl. a reuseport
6862 * rebind in a worker, binds */
6863 } hm_listener_spec;
6864  
6865 /* Validate one listener's options at run() time (before any bind/fork). */
6866 129 static void hm_check_listener(pTHX_ const hm_listener_spec *s) {
6867 /*
6868 # uncoverable condition left count:2 class:ignore_covered_err
6869 # uncoverable condition left count:3 class:ignore_covered_err
6870 # uncoverable condition left count:4 class:ignore_covered_err
6871 # uncoverable condition left count:5 class:ignore_covered_err */
6872 129 ▶ if (s->tls_cert || s->tls_key || s->tls_ca || s->tls_sni || s->tls_verify) {
Branch: 5 branches
BranchTrueFalseTotal
if (s->tls_cert || s->tls_key || s->tls_ca || s->tls_sni || s->tls_verify) { 115 14 129
if (s->tls_cert || s->tls_key || s->tls_ca || s->tls_sni || s->tls_verify) { 115 0 115
if (s->tls_cert || s->tls_key || s->tls_ca || s->tls_sni || s->tls_verify) { 115 0 115
if (s->tls_cert || s->tls_key || s->tls_ca || s->tls_sni || s->tls_verify) { 115 0 115
if (s->tls_cert || s->tls_key || s->tls_ca || s->tls_sni || s->tls_verify) { 0 115 115
6873 14 ▶ if (!(s->tls_cert && s->tls_key)) /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!(s->tls_cert && s->tls_key)) /* # uncoverable condition left count:1 class:ignore_covered_err */ 14 0 14
if (!(s->tls_cert && s->tls_key)) /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 13 14
6874 1 croak("Hyperman->run: tls_cert and tls_key must be given together");
6875 /*
6876 # uncoverable branch true
6877 # uncoverable condition left count:1 class:ignore_covered_err */
6878 13 ▶ if (!hm_tls_available())
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_tls_available()) 0 13 13
6879 0 croak("Hyperman->run: TLS requested but OpenSSL support was not " /* # uncoverable statement */
6880 "built (install libssl-dev and reinstall Hyperman)");
6881 13 ▶ if (s->tls_verify && !s->tls_ca)
Branch: 2 branches
BranchTrueFalseTotal
if (s->tls_verify && !s->tls_ca) 3 10 13
if (s->tls_verify && !s->tls_ca) 1 2 3
6882 1 croak("Hyperman->run: tls_verify needs tls_ca (the CA to verify "
6883 "client certificates against)");
6884 }
6885 /*
6886 # uncoverable branch true class:ignore_covered_err
6887 # uncoverable condition left count:1 class:ignore_covered_err
6888 # uncoverable condition left count:2 class:ignore_covered_err */
6889 127 ▶ if (s->http2 && !hm_h2_available())
Branch: 2 branches
BranchTrueFalseTotal
if (s->http2 && !hm_h2_available()) 1 126 127
if (s->http2 && !hm_h2_available()) 1 0 1
6890 1 croak("Hyperman->run: http2 requested but nghttp2 support was not " /* # uncoverable statement */
6891 "built (install libnghttp2-dev and reinstall Hyperman)");
6892 126 ▶ if (s->http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) { 3 123 126
6893 /*
6894 # uncoverable branch true class:ignore_covered_err
6895 # uncoverable branch false class:ignore_covered_err
6896 # uncoverable condition right count:1 class:ignore_covered_err */
6897 3 ▶ if (!hm_h3_available())
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_h3_available()) 3 0 3
6898 3 croak("Hyperman->run: http3 requested but QUIC support was not " /* # uncoverable statement class:ignore_covered_err */
6899 "built (it needs ngtcp2, ngtcp2_crypto_ossl, nghttp3 and "
6900 "OpenSSL 3.5 or newer - reinstall Hyperman once they are "
6901 "installed)");
6902 /* There is no cleartext QUIC the way there is h2c: the transport's
6903 * handshake IS a TLS handshake, so a certificate is not optional. */
6904 /*
6905 # uncoverable statement class:ignore_covered_err
6906 # uncoverable branch true class:ignore_covered_err
6907 # uncoverable branch false class:ignore_covered_err
6908 # uncoverable condition left count:1 class:ignore_covered_err
6909 # uncoverable condition right count:1 class:ignore_covered_err
6910 # uncoverable condition left count:2 class:ignore_covered_err
6911 # uncoverable condition right count:2 class:ignore_covered_err */
6912 0 ▶ if (!(s->tls_cert && s->tls_key))
Branch: 2 branches
BranchTrueFalseTotal
if (!(s->tls_cert && s->tls_key)) 0 0 0
if (!(s->tls_cert && s->tls_key)) 0 0 0
6913 0 croak("Hyperman->run: http3 needs tls_cert and tls_key (QUIC has " /* # uncoverable statement class:ignore_covered_err */
6914 "no cleartext mode)");
6915 }
6916 123 ▶ if (s->redirect_https && (s->tls_cert || s->tls_key)) /* # uncoverable condition left count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if (s->redirect_https && (s->tls_cert || s->tls_key)) /* # uncoverable condition left count:3 class:ignore_covered_err */ 2 121 123
if (s->redirect_https && (s->tls_cert || s->tls_key)) /* # uncoverable condition left count:3 class:ignore_covered_err */ 1 1 2
if (s->redirect_https && (s->tls_cert || s->tls_key)) /* # uncoverable condition left count:3 class:ignore_covered_err */ 0 1 1
6917 1 croak("Hyperman->run: redirect_https on a TLS listener makes no sense");
6918 122 ▶ if (s->path) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) { 8 114 122
6919 /*
6920 # uncoverable branch true class:ignore_covered_err
6921 # uncoverable condition left count:1 class:ignore_covered_err */
6922 8 ▶ if (s->http3)
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) 0 8 8
6923 0 croak("Hyperman->run: http3 needs an IP listener; a path listener " /* # uncoverable statement class:ignore_covered_err */
6924 "has no UDP twin");
6925 }
6926 /*
6927 # uncoverable branch true class:ignore_covered_err
6928 # uncoverable condition left count:1 class:ignore_covered_err
6929 # uncoverable condition left count:2 class:ignore_covered_err */
6930 122 ▶ if (s->proxy_protocol && s->http3)
Branch: 2 branches
BranchTrueFalseTotal
if (s->proxy_protocol && s->http3) 3 119 122
if (s->proxy_protocol && s->http3) 0 3 3
6931 0 warn("Hyperman->run: proxy_protocol applies to the TCP side of this " /* # uncoverable statement class:ignore_covered_err */
6932 "listener only; QUIC has no byte stream before its handshake and "
6933 "reports real datagram sources");
6934 122 }
6935  
6936 /* Overlay per-listener options from a `listen => [ {..} ]` hashref onto a spec
6937 * pre-seeded with the top-level defaults. Unknown keys croak. A bare true
6938 * redirect_https means "the standard 443". */
6939 22 static void hm_listener_from_hv(pTHX_ HV *h, hm_listener_spec *s) {
6940 HE *he;
6941 22 hv_iterinit(h);
6942 58 ▶ while ((he = hv_iternext(h))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(h))) { 39 19 58
6943 39 ▶ STRLEN klen; const char *k = HePV(he, klen); SV *v = HeVAL(he);
Branch: 1 branch
BranchTrueFalseTotal
STRLEN klen; const char *k = HePV(he, klen); SV *v = HeVAL(he); 0 39 39
6944 39 ▶ if (strEQ(k, "port")) s->port = (int)SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(k, "port")) s->port = (int)SvIV(v); 12 27 39
6945 /*
6946 # uncoverable branch true count:3 class:ignore_covered_err
6947 # uncoverable condition right count:2 class:ignore_covered_err */
6948 34 ▶ else if (strEQ(k, "host")) { if (SvOK(v)) s->host = SvPV_nolen(v); }
Branch: 2 branches
BranchTrueFalseTotal
else if (strEQ(k, "host")) { if (SvOK(v)) s->host = SvPV_nolen(v); } 7 20 27
else if (strEQ(k, "host")) { if (SvOK(v)) s->host = SvPV_nolen(v); } 7 0 7
6949 /*
6950 # uncoverable branch true count:3 class:ignore_covered_err
6951 # uncoverable condition right count:2 class:ignore_covered_err */
6952 28 ▶ else if (strEQ(k, "path")) { if (SvOK(v)) s->path = SvPV_nolen(v); }
Branch: 2 branches
BranchTrueFalseTotal
else if (strEQ(k, "path")) { if (SvOK(v)) s->path = SvPV_nolen(v); } 8 12 20
else if (strEQ(k, "path")) { if (SvOK(v)) s->path = SvPV_nolen(v); } 8 0 8
6953 12 ▶ else if (strEQ(k, "inherit")) s->inherit = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "inherit")) s->inherit = SvTRUE(v) ? 1 : 0; 1 11 12
6954 11 ▶ else if (strEQ(k, "proxy_protocol")) s->proxy_protocol = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "proxy_protocol")) s->proxy_protocol = SvTRUE(v) ? 1 : 0; 3 8 11
6955 8 ▶ else if (strEQ(k, "mode")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "mode")) { 2 6 8
6956 /*
6957 # uncoverable branch false class:ignore_covered_err
6958 # uncoverable condition right count:1 class:ignore_covered_err */
6959 2 ▶ if (SvOK(v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(v)) { 2 0 2
6960 2 ▶ if (SvIOK(v) || SvNOK(v)) s->mode = (int)SvIV(v); /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (SvIOK(v) || SvNOK(v)) s->mode = (int)SvIV(v); /* # uncoverable condition left count:2 class:ignore_covered_err */ 1 1 2
if (SvIOK(v) || SvNOK(v)) s->mode = (int)SvIV(v); /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 1 1
6961 else {
6962 char *end;
6963 1 const char *m = SvPV_nolen(v);
6964 1 s->mode = (int)strtol(m, &end, 8);
6965 /*
6966 # uncoverable branch false class:ignore_covered_err
6967 # uncoverable condition left count:1 class:ignore_covered_err
6968 # uncoverable condition right count:1 class:ignore_covered_err
6969 # uncoverable condition right count:2 class:ignore_covered_err */
6970 1 ▶ if (*m == '\0' || *end != '\0')
Branch: 2 branches
BranchTrueFalseTotal
if (*m == '\0' || *end != '\0') 1 0 1
if (*m == '\0' || *end != '\0') 1 0 1
6971 1 croak("Hyperman->run: mode '%s' is not an octal number", m);
6972 }
6973 1 s->mode_set = 1;
6974 }
6975 }
6976 7 ▶ else if (strEQ(k, "tls_cert")) s->tls_cert = SvOK(v) ? SvPV_nolen(v) : NULL; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
else if (strEQ(k, "tls_cert")) s->tls_cert = SvOK(v) ? SvPV_nolen(v) : NULL; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 5 6
else if (strEQ(k, "tls_cert")) s->tls_cert = SvOK(v) ? SvPV_nolen(v) : NULL; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
6977 6 ▶ else if (strEQ(k, "tls_key")) s->tls_key = SvOK(v) ? SvPV_nolen(v) : NULL; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
else if (strEQ(k, "tls_key")) s->tls_key = SvOK(v) ? SvPV_nolen(v) : NULL; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 4 5
else if (strEQ(k, "tls_key")) s->tls_key = SvOK(v) ? SvPV_nolen(v) : NULL; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
6978 /*
6979 # uncoverable branch true
6980 # uncoverable condition left count:1 class:ignore_covered_err
6981 # uncoverable condition left count:2 class:ignore_covered_err
6982 # uncoverable condition right count:2 class:ignore_covered_err */
6983 4 ▶ else if (strEQ(k, "tls_ca")) s->tls_ca = SvOK(v) ? SvPV_nolen(v) : NULL;
Branch: 2 branches
BranchTrueFalseTotal
else if (strEQ(k, "tls_ca")) s->tls_ca = SvOK(v) ? SvPV_nolen(v) : NULL; 0 4 4
else if (strEQ(k, "tls_ca")) s->tls_ca = SvOK(v) ? SvPV_nolen(v) : NULL; 0 0 0
6984 /*
6985 # uncoverable branch true
6986 # uncoverable condition left count:1 class:ignore_covered_err
6987 # uncoverable condition left count:2 class:ignore_covered_err
6988 # uncoverable condition right count:2 class:ignore_covered_err */
6989 4 ▶ else if (strEQ(k, "tls_sni")) s->tls_sni = SvOK(v) ? v : NULL;
Branch: 2 branches
BranchTrueFalseTotal
else if (strEQ(k, "tls_sni")) s->tls_sni = SvOK(v) ? v : NULL; 0 4 4
else if (strEQ(k, "tls_sni")) s->tls_sni = SvOK(v) ? v : NULL; 0 0 0
6990 4 ▶ else if (strEQ(k, "http2")) s->http2 = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "http2")) s->http2 = SvTRUE(v) ? 1 : 0; 0 4 4
6991 4 ▶ else if (strEQ(k, "http3")) s->http3 = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "http3")) s->http3 = SvTRUE(v) ? 1 : 0; 1 3 4
6992 3 ▶ else if (strEQ(k, "redirect_https")) s->redirect_https = (int)SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "redirect_https")) s->redirect_https = (int)SvIV(v); 1 2 3
6993 2 ▶ else if (strEQ(k, "tls_verify")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "tls_verify")) { 1 1 2
6994 1 const char *m = SvPV_nolen(v);
6995 /*
6996 # uncoverable branch true
6997 # uncoverable condition left count:1 class:ignore_covered_err */
6998 1 ▶ if (strEQ(m, "require")) s->tls_verify = 2;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(m, "require")) s->tls_verify = 2; 0 1 1
6999 /*
7000 # uncoverable branch true
7001 # uncoverable condition left count:1 class:ignore_covered_err */
7002 1 ▶ else if (strEQ(m, "optional")) s->tls_verify = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(m, "optional")) s->tls_verify = 1; 0 1 1
7003 /*
7004 # uncoverable branch true
7005 # uncoverable condition left count:1 class:ignore_covered_err */
7006 1 ▶ else if (strEQ(m, "none")) s->tls_verify = 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(m, "none")) s->tls_verify = 0; 0 1 1
7007 1 else croak("Hyperman->run: tls_verify must be none/optional/require");
7008 }
7009 1 else croak("Hyperman->run: unknown listen option '%s'", k);
7010 }
7011 /*
7012 # uncoverable branch true class:ignore_covered_err
7013 # uncoverable condition left count:1 class:ignore_covered_err */
7014 19 ▶ if (s->redirect_https == 1) s->redirect_https = 443;
Branch: 1 branch
BranchTrueFalseTotal
if (s->redirect_https == 1) s->redirect_https = 443; 0 19 19
7015 /* A path listener is seeded with the top-level host and port like every
7016 * other spec; the path is the address, so those defaults are dropped
7017 * rather than read as a contradiction. */
7018 19 ▶ if (s->path) { s->host = NULL; s->port = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) { s->host = NULL; s->port = 0; } 8 11 19
7019 19 }
7020  
7021 /* Everything a worker needs; one struct so spawn plumbing stays sane. */
7022 typedef struct {
7023 SV *app;
7024 hm_listener_spec *lspecs; /* one or more listeners */
7025 int nlspecs;
7026 double idle_t, header_t, body_t, request_t, grace;
7027 UV body_min_rate;
7028 int max_pipe, reuseport, affinity, nworkers;
7029 int completion; /* -1 = say nothing, 0/1 = force */
7030 int compress;
7031 size_t compress_min;
7032 int compress_level;
7033 size_t max_read; /* request ceiling; 16MB by default */
7034 SV *compress_types;
7035 UV max_requests;
7036 SV *log_cb; /* access_log coderef, or NULL */
7037 int log_fd; /* fast access-log fd, or -1 */
7038 const char *log_path; /* access_log file to open (parent), or NULL */
7039 const char *log_format; /* access_log_format, NULL = Combined */
7040 hm_logtok *logtok; /* ... compiled, before the fork */
7041 int nlogtok, log_json, log_wants_t0;
7042 int err_fd; /* error_log fd, or -1 = stderr */
7043 const char *err_path; /* error_log file to open (parent), or NULL */
7044 /* Privileges, dropped in the parent after every bind and before the
7045 * first fork (hm_drop_privileges). Names are resolved FIRST, before the
7046 * bind, so an unknown user is a croak with the port still free. */
7047 const char *drop_user; /* user => name or uid, or NULL */
7048 const char *drop_group; /* group => name or gid, or NULL */
7049 const char *pid_path; /* pid_file, or NULL */
7050 int listen_fds; /* adopt every listener from LISTEN_FDS */
7051 int umask_set; /* umask => given */
7052 unsigned umask_val;
7053 int drop_uid_set, drop_gid_set;
7054 long drop_uid, drop_gid;
7055 char drop_name[64]; /* the user's name, for initgroups */
7056 SV *deny; /* arrayref of IPs to denylist, or NULL */
7057 unsigned deny_cap, rate_cap; /* arena table sizes, 0 = default */
7058 unsigned bus_slots, bus_slot_size, bus_groups; /* 0 = default */
7059 UV http3_max_conns; /* QUIC connection ceiling, 0 = off */
7060 const char *arena_name; /* Shared::Arena name, NULL = anonymous */
7061 STRLEN arena_name_len;
7062 UV arena_size; /* bytes, 0 = computed from the tenants */
7063 int distinct_clients; /* count distinct peers at accept (HLL) */
7064 } hm_worker_cfg;
7065  
7066 /* Populate the loop's listener array from the (already bound) specs. Under
7067 * reuseport each worker rebinds, so fds are passed in; otherwise they are the
7068 * parent's inherited fds. Returns 0, or -1 if a reuseport rebind failed. */
7069 134 static int hm_worker_listeners(hm_loop *loop, const hm_worker_cfg *cfg,
7070 const int *fds) {
7071 int i;
7072 134 loop->listeners = (hm_listener *)hm_xcalloc(cfg->nlspecs, sizeof(hm_listener));
7073 134 loop->nlisteners = cfg->nlspecs;
7074 279 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 145 134 279
7075 145 const hm_listener_spec *s = &cfg->lspecs[i];
7076 145 hm_listener *l = &loop->listeners[i];
7077 145 ▶ l->fd = fds ? fds[i] : s->fd;
Branch: 1 branch
BranchTrueFalseTotal
l->fd = fds ? fds[i] : s->fd; 2 143 145
7078 /*
7079 # uncoverable branch true
7080 # uncoverable condition left count:1 class:ignore_covered_err */
7081 145 ▶ if (l->fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (l->fd < 0) return -1; 0 145 145
7082 145 ▶ l->udp_fd = fds ? fds[cfg->nlspecs + i] : s->udp_fd;
Branch: 1 branch
BranchTrueFalseTotal
l->udp_fd = fds ? fds[cfg->nlspecs + i] : s->udp_fd; 2 143 145
7083 145 l->is_unix = s->path ? 1 : 0;
7084 145 l->proxy_protocol = s->proxy_protocol;
7085 282 ▶ l->host = strdup(s->path ? s->path
Branch: 1 branch
BranchTrueFalseTotal
l->host = strdup(s->path ? s->path 8 137 145
7086 /*
7087 # uncoverable condition right count:1 class:ignore_covered_err
7088 # uncoverable condition right count:2 class:ignore_covered_err */
7089 137 ▶ : s->host && *s->host ? s->host : "0.0.0.0");
Branch: 2 branches
BranchTrueFalseTotal
: s->host && *s->host ? s->host : "0.0.0.0"); 137 0 137
: s->host && *s->host ? s->host : "0.0.0.0"); 137 0 137
7090 145 l->port = s->port;
7091 145 l->tls_ctx = s->tls_ctx;
7092 145 l->http2 = s->http2;
7093 145 l->http3 = s->http3;
7094 145 l->redirect_https = s->redirect_https;
7095 /* Copied, not borrowed: hm_tls_reload frees the context it
7096 * replaces, and a rebuild has to name the same cert and key. */
7097 145 ▶ l->tls_cert = s->tls_cert ? strdup(s->tls_cert) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
l->tls_cert = s->tls_cert ? strdup(s->tls_cert) : NULL; 8 137 145
7098 145 ▶ l->tls_key = s->tls_key ? strdup(s->tls_key) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
l->tls_key = s->tls_key ? strdup(s->tls_key) : NULL; 8 137 145
7099 145 ▶ l->tls_ca = s->tls_ca ? strdup(s->tls_ca) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
l->tls_ca = s->tls_ca ? strdup(s->tls_ca) : NULL; 1 144 145
7100 145 l->tls_verify = s->tls_verify;
7101 145 ▶ l->tls_sni = s->tls_sni ? SvREFCNT_inc(s->tls_sni) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
l->tls_sni = s->tls_sni ? SvREFCNT_inc(s->tls_sni) : NULL; 4 141 145
7102 /* Precomputed once here rather than per response: the value never
7103 * changes for the life of the listener, and a header built per
7104 * request would be built on the hot path for every request the
7105 * listener ever serves. */
7106 /*
7107 # uncoverable branch true class:ignore_covered_err
7108 # uncoverable condition left count:1 class:ignore_covered_err */
7109 145 ▶ if (l->udp_fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (l->udp_fd >= 0) { 0 145 145
7110 char b[64];
7111 0 int n = snprintf(b, sizeof(b), "h3=\":%d\"; ma=86400", l->port); /* # uncoverable statement class:ignore_covered_err */
7112 /*
7113 # uncoverable statement class:ignore_covered_err
7114 # uncoverable condition left count:1 class:ignore_covered_err
7115 # uncoverable condition right count:1 class:ignore_covered_err
7116 # uncoverable condition left count:2 class:ignore_covered_err
7117 # uncoverable condition right count:2 class:ignore_covered_err */
7118 0 ▶ l->altsvc = (n > 0 && n < (int)sizeof(b)) ? strdup(b) : NULL;
Branch: 2 branches
BranchTrueFalseTotal
l->altsvc = (n > 0 && n < (int)sizeof(b)) ? strdup(b) : NULL; 0 0 0
l->altsvc = (n > 0 && n < (int)sizeof(b)) ? strdup(b) : NULL; 0 0 0
7119 }
7120 }
7121 134 return 0;
7122 }
7123  
7124 /* Rebuild this worker's TLS contexts from a fresh SNI map.
7125 *
7126 * The listener array is the WORKER'S: hm_worker_listeners above ran after
7127 * the fork and copied the parent's tls_ctx pointer into it, so swapping
7128 * that pointer changes this process and nothing else. The listening fd is
7129 * not touched, so nothing is unbound and no connection is refused;
7130 * connections already handshook keep the SSL they hold, and the next one
7131 * this worker accepts uses the new context.
7132 *
7133 * NOTHING IS INSTALLED THAT SERVES LESS THAN WHAT IS RUNNING. Two ways a
7134 * rebuild can come back worse, and both keep the old context:
7135 *
7136 * - the default certificate will not load. It is the one every
7137 * hostname falls back to, so a fleet keeps serving the stale one
7138 * rather than none.
7139 * - a per-host certificate will not load. hm_tls_ctx_build skips it
7140 * with a message and still returns a usable default, which is right
7141 * at boot but silently drops that domain to the fallback here. So
7142 * the built registry is counted against what was asked for, and a
7143 * context carrying fewer hosts is thrown away. The cost is that one
7144 * corrupt PEM defers everybody's update to the next poll, against
7145 * installing a context that quietly stopped serving a domain.
7146 *
7147 * Returns the number of listeners rebuilt. */
7148 3 static int hm_tls_reload(pTHX_ hm_loop *loop, SV *sni) {
7149 3 int i, done = 0;
7150 /*
7151 # uncoverable condition right count:1 class:ignore_covered_err
7152 # uncoverable condition right count:2 class:ignore_covered_err
7153 # uncoverable condition right count:3 class:ignore_covered_err */
7154 3 ▶ int given = sni && SvROK(sni) && SvTYPE(SvRV(sni)) == SVt_PVHV;
Branch: 3 branches
BranchTrueFalseTotal
int given = sni && SvROK(sni) && SvTYPE(SvRV(sni)) == SVt_PVHV; 3 0 3
int given = sni && SvROK(sni) && SvTYPE(SvRV(sni)) == SVt_PVHV; 3 0 3
int given = sni && SvROK(sni) && SvTYPE(SvRV(sni)) == SVt_PVHV; 3 0 3
7155 /*
7156 # uncoverable branch true
7157 # uncoverable condition left count:1 class:ignore_covered_err */
7158 3 ▶ if (!loop) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) return 0; 0 3 3
7159  
7160 6 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 3 3 6
7161 3 hm_listener *l = &loop->listeners[i];
7162 void *fresh;
7163 unsigned char tkey[HM_TLS_TKEY_MAX];
7164 3 const unsigned char *tk = NULL;
7165 3 size_t tklen = 0;
7166 /* No map given: the listener's own, so a reload called for the
7167 * default certificate alone keeps every SNI host. Without this the
7168 * rebuilt context had no registry and the "fewer hosts" refusal
7169 * below did not apply to it, so every name fell to the default. */
7170 3 ▶ SV *use = given ? sni : l->tls_sni; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
SV *use = given ? sni : l->tls_sni; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 3 3
7171 3 ▶ int want = (use && SvROK(use) && SvTYPE(SvRV(use)) == SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
int want = (use && SvROK(use) && SvTYPE(SvRV(use)) == SVt_PVHV) 3 0 3
int want = (use && SvROK(use) && SvTYPE(SvRV(use)) == SVt_PVHV) 3 0 3
7172 6 ▶ ? (int)HvUSEDKEYS((HV *)SvRV(use)) : -1; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
? (int)HvUSEDKEYS((HV *)SvRV(use)) : -1; /* # uncoverable condition left count:1 class:ignore_covered_err */ 3 0 3
? (int)HvUSEDKEYS((HV *)SvRV(use)) : -1; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 3 3
7173 /*
7174 # uncoverable condition left count:1 class:ignore_covered_err
7175 # uncoverable condition left count:2 class:ignore_covered_err
7176 # uncoverable condition left count:3 class:ignore_covered_err */
7177 4 ▶ if (!l->tls_ctx || !l->tls_cert || !l->tls_key) continue; /* plain */
Branch: 3 branches
BranchTrueFalseTotal
if (!l->tls_ctx || !l->tls_cert || !l->tls_key) continue; /* plain */ 3 0 3
if (!l->tls_ctx || !l->tls_cert || !l->tls_key) continue; /* plain */ 3 0 3
if (!l->tls_ctx || !l->tls_cert || !l->tls_key) continue; /* plain */ 0 3 3
7178  
7179 /* Carry the running context's session-ticket key into the new one.
7180 * The boot-time contexts are built before the fork, so every worker
7181 * starts out able to decrypt every other worker's tickets - but this
7182 * reload runs independently in each of them, and SSL_CTX_new mints a
7183 * fresh random key. Left alone, the first rotation would leave a
7184 * ticket issued by one worker undecryptable by its siblings, and
7185 * every resumption a client attempted would quietly become a full
7186 * handshake: the signature and key exchange that tickets exist to
7187 * avoid, on a fleet that rotates certificates continuously. */
7188 /*
7189 # uncoverable branch false class:ignore_covered_err
7190 # uncoverable condition right count:1 class:ignore_covered_err */
7191 3 ▶ if (hm_tls_get_ticket_key(l->tls_ctx, tkey, &tklen)) tk = tkey;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_tls_get_ticket_key(l->tls_ctx, tkey, &tklen)) tk = tkey; 3 0 3
7192  
7193 3 fresh = hm_tls_ctx_build(aTHX_ l->tls_cert, l->tls_key, l->tls_ca,
7194 l->tls_verify, use, l->http2, tk, tklen);
7195 /*
7196 # uncoverable branch true
7197 # uncoverable condition left count:1 class:ignore_covered_err */
7198 3 ▶ if (!fresh) continue; /* keep what we are serving */
Branch: 1 branch
BranchTrueFalseTotal
if (!fresh) continue; /* keep what we are serving */ 0 3 3
7199  
7200 3 ▶ if (want > 0 && hm_tls_sni_count(fresh) < want) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (want > 0 && hm_tls_sni_count(fresh) < want) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 3 0 3
if (want > 0 && hm_tls_sni_count(fresh) < want) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 2 3
7201 1 hm_errlog("Hyperman TLS: reload built %d of %d SNI hosts; "
7202 "keeping the running certificates\n",
7203 hm_tls_sni_count(fresh), want);
7204 1 hm_tls_ctx_free(fresh);
7205 1 continue;
7206 }
7207  
7208 /* The QUIC context serves the SAME certificate over the same origin,
7209 * so it is rebuilt with the TCP one and the two are swapped together
7210 * or not at all. Swapping only the TCP side leaves a fleet serving a
7211 * fresh certificate over TCP and a stale one over QUIC - a mismatch
7212 * no TCP-only monitor can see, on the transport a browser prefers.
7213 *
7214 * The new QUIC context is built BEFORE either is installed, so a
7215 * failure to build it keeps both of the running pair rather than
7216 * leaving a half-swapped listener. */
7217 /*
7218 # uncoverable statement class:ignore_covered_err
7219 # uncoverable branch true
7220 # uncoverable condition left count:1
7221 # uncoverable condition left count:2
7222 # uncoverable condition right count:2 */
7223 2 ▶ if (l->udp_fd >= 0 && l->quic) {
Branch: 2 branches
BranchTrueFalseTotal
if (l->udp_fd >= 0 && l->quic) { 0 2 2
if (l->udp_fd >= 0 && l->quic) { 0 0 0
7224 0 void *qfresh = hm_tls_quic_ctx_build(l->tls_cert, l->tls_key, /* # uncoverable statement */
7225 0 l->tls_ca, l->tls_verify, /* # uncoverable statement */
7226 tk, tklen); /* # uncoverable statement */
7227 /*
7228 # uncoverable statement
7229 # uncoverable branch true
7230 # uncoverable branch false
7231 # uncoverable condition left count:1
7232 # uncoverable condition right count:1 */
7233 0 ▶ if (!qfresh) {
Branch: 1 branch
BranchTrueFalseTotal
if (!qfresh) { 0 0 0
7234 0 hm_errlog("Hyperman TLS: reload could not rebuild the " /* # uncoverable statement */
7235 "QUIC context; keeping both running "
7236 "certificates\n");
7237 0 hm_tls_ctx_free(fresh); /* # uncoverable statement */
7238 0 continue; /* # uncoverable statement */
7239 }
7240 0 hm_quic_ctx_swap(aTHX_ l, qfresh); /* # uncoverable statement */
7241 }
7242  
7243 2 hm_tls_ctx_free(l->tls_ctx);
7244 2 l->tls_ctx = fresh;
7245 2 done++;
7246 }
7247 3 return done;
7248 }
7249  
7250 /* The bus wakeup, on this worker's loop.
7251 *
7252 * Lives here rather than in hm_sa_bus.h because it is the one part that needs
7253 * both halves: hm_sa_bus.h deliberately knows nothing about the server, and
7254 * the loop knows nothing about the ring.
7255 *
7256 * The callback MUST NOT CROAK. It is called from the event loop with no Perl
7257 * frame around it, and a die from a subscriber would unwind through the loop
7258 * and take the worker with it - so the dispatch below is the only thing here,
7259 * and anything Perl-facing wraps itself in G_EVAL before it gets this far. */
7260 5 static void hm_bus_wake_cb(pTHX_ int fd, int mask, void *ud) {
7261 PERL_UNUSED_ARG(fd);
7262 PERL_UNUSED_ARG(mask);
7263 PERL_UNUSED_ARG(ud);
7264 PERL_UNUSED_CONTEXT;
7265 /* Empty the pipe and clear the flag BEFORE dispatching, so a publish that
7266 * lands while we are dispatching sets it again and pokes afresh, rather
7267 * than being folded into a wakeup that has already been handled. The
7268 * order inside the ring's wake_drained matters too - see hm_sa_bus.h. */
7269 5 hm_sa_bus_waker_drained();
7270 5 (void)hm_sa_bus_dispatch();
7271 5 }
7272  
7273 /* The one-second tick: the loop's counters into this worker's scoreboard
7274 * row in one seqlock bracket, a heartbeat on the peer row, and the next
7275 * tick armed. A C timer is one-shot and freed on fire, so re-arming here is
7276 * the whole of the repetition. Stops with the loop: a draining worker keeps
7277 * mirroring until its last connection closes, and nothing here holds the
7278 * loop open once it wants to end. */
7279 250 static void hm_board_tick(pTHX_ void *ud) {
7280 250 hm_loop *loop = (hm_loop *)ud;
7281 250 hm_sa_board_mirror((uint64_t)loop->requests, (uint64_t)loop->accepts,
7282 250 (uint64_t)loop->denied, loop->nconns,
7283 250 (uint64_t)loop->bytes_out, (uint64_t)loop->datagrams,
7284 250 (uint64_t)loop->h3_requests);
7285 /*
7286 # uncoverable branch false class:ignore_covered_err
7287 # uncoverable condition right count:1 class:ignore_covered_err
7288 # uncoverable condition right count:2 class:ignore_covered_err */
7289 250 ▶ if (HM_SA && hm_sa_region) HM_SA->beat(hm_sa_region);
Branch: 2 branches
BranchTrueFalseTotal
if (HM_SA && hm_sa_region) HM_SA->beat(hm_sa_region); 250 0 250
if (HM_SA && hm_sa_region) HM_SA->beat(hm_sa_region); 250 0 250
7290 250 ▶ if (!loop->stopping)
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->stopping) 247 3 250
7291 247 (void)hm_add_timer_watch_c(loop, 1.0, hm_board_tick, loop);
7292 250 }
7293  
7294 /* The polling fallback's tick: drain the ring, re-arm. */
7295 71 static void hm_bus_poll_cb(pTHX_ void *ud) {
7296 71 hm_loop *loop = (hm_loop *)ud;
7297 71 (void)hm_sa_bus_dispatch();
7298 /*
7299 # uncoverable branch false class:ignore_covered_err
7300 # uncoverable condition right count:1 class:ignore_covered_err */
7301 71 ▶ if (!loop->stop) (void)hm_add_timer_watch_c(loop, 0.05, hm_bus_poll_cb, loop);
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->stop) (void)hm_add_timer_watch_c(loop, 0.05, hm_bus_poll_cb, loop); 71 0 71
7302 71 }
7303  
7304 134 static void hm_bus_worker_attach(pTHX_ hm_loop *loop) {
7305 int fd;
7306 134 ▶ if (!hm_sa_bus_live()) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_sa_bus_live()) return; 8 126 134
7307 /* A worker inherited the parent's cursors along with everything else, and
7308 * a cursor is a position in a stream this process has not been reading.
7309 * Left alone it either replays what the parent already handled or skips
7310 * what it has not. From now on. */
7311 126 hm_sa_bus_reset_cursors();
7312  
7313 /* THE LAST WORD ON WHETHER THIS PROCESS CAN BE WOKEN.
7314 *
7315 * hm_spawn asks for a slot by worker index, which is what keeps two
7316 * workers off one descriptor. It can come back empty-handed: the index it
7317 * asked for may still be held by a worker that is draining after a HUP,
7318 * and single-worker mode never goes through hm_spawn at all. Either way
7319 * the process ends up with no descriptor.
7320 *
7321 * Before this, that was the end of it - no watch was installed and this
7322 * worker never dispatched again, so a published invalidation or room
7323 * broadcast reached every worker but this one, for as long as it ran, with
7324 * nothing in any statistic to say so. Single-worker mode never delivered
7325 * to its own subscribers at all.
7326 *
7327 * So take whatever is going rather than go deaf. Which slot a worker holds
7328 * has never mattered; holding one is the whole of it. */
7329 126 fd = hm_sa_bus_waker_fd();
7330 126 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 58 68 126
7331 58 (void)hm_sa_bus_waker_take(-1);
7332 58 fd = hm_sa_bus_waker_fd();
7333 }
7334 126 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 6 120 126
7335 /* No descriptor: the slots were all held, or this process attached
7336 * the arena by name (a re-exec successor's pool does) and the pipes
7337 * in it belong to another process. Poll the ring instead, every
7338 * fifty milliseconds. Slower to notice a message than a poke, never
7339 * deaf. */
7340 6 hm_errlog("Hyperman: worker %d has no wakeup descriptor; polling the "
7341 6 "bus every 50ms instead", hm_os_getpid());
7342 6 (void)hm_add_timer_watch_c(loop, 0.05, hm_bus_poll_cb, loop);
7343 6 return;
7344 }
7345 120 hm_add_io_watch_c(aTHX_ loop, fd, HM_EV_READ, hm_bus_wake_cb, NULL);
7346 /* Anything published between the fork and this attach is already on the
7347 * ring with no poke coming, because nothing was watching to be poked. */
7348 120 (void)hm_sa_bus_dispatch();
7349 }
7350  
7351 134 static void hm_worker(pTHX_ const hm_worker_cfg *cfg, const int *fds) {
7352 134 hm_loop *loop = hm_loop_new(aTHX_ NULL);
7353 /*
7354 # uncoverable branch true
7355 # uncoverable condition left count:1 class:ignore_covered_err */
7356 134 ▶ if (!loop) croak("Hyperman: cannot create event loop");
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) croak("Hyperman: cannot create event loop"); 0 134 134
7357 134 ▶ if (cfg->idle_t > 0) loop->idle_timeout = cfg->idle_t;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->idle_t > 0) loop->idle_timeout = cfg->idle_t; 1 133 134
7358 134 ▶ if (cfg->header_t > 0) loop->header_timeout = cfg->header_t;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->header_t > 0) loop->header_timeout = cfg->header_t; 4 130 134
7359 134 ▶ if (cfg->body_t > 0) loop->body_timeout = cfg->body_t;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->body_t > 0) loop->body_timeout = cfg->body_t; 3 131 134
7360 134 ▶ if (cfg->request_t > 0) loop->request_timeout = cfg->request_t;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->request_t > 0) loop->request_timeout = cfg->request_t; 1 133 134
7361 134 ▶ if (cfg->body_min_rate) loop->body_min_rate = cfg->body_min_rate;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->body_min_rate) loop->body_min_rate = cfg->body_min_rate; 1 133 134
7362 134 ▶ if (cfg->max_pipe > 0) loop->max_pipeline = cfg->max_pipe;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->max_pipe > 0) loop->max_pipeline = cfg->max_pipe; 2 132 134
7363 134 ▶ if (cfg->grace > 0) loop->shutdown_grace = cfg->grace;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->grace > 0) loop->shutdown_grace = cfg->grace; 17 117 134
7364 134 loop->max_requests = cfg->max_requests;
7365 /* Only when the caller actually said so: -1 leaves whatever the loop
7366 * decided for itself from the backend and the environment. */
7367 134 ▶ if (cfg->completion >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->completion >= 0) 1 133 134
7368 /*
7369 # uncoverable condition left count:1 class:ignore_covered_err
7370 # uncoverable condition left count:2 class:ignore_covered_err
7371 # uncoverable condition right count:2 class:ignore_covered_err */
7372 1 ▶ loop->completion = (cfg->completion && loop->be->submit_recv) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
loop->completion = (cfg->completion && loop->be->submit_recv) ? 1 : 0; 0 1 1
loop->completion = (cfg->completion && loop->be->submit_recv) ? 1 : 0; 0 0 0
7373 134 loop->compress = cfg->compress;
7374 134 ▶ if (cfg->compress_min) loop->compress_min = cfg->compress_min;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->compress_min) loop->compress_min = cfg->compress_min; 2 132 134
7375 134 ▶ if (cfg->compress_level) loop->compress_level = cfg->compress_level;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->compress_level) loop->compress_level = cfg->compress_level; 1 133 134
7376 134 ▶ if (cfg->max_read) loop->max_read = cfg->max_read;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->max_read) loop->max_read = cfg->max_read; 12 122 134
7377 134 loop->http3_max_conns = cfg->http3_max_conns;
7378 268 loop->compress_types = cfg->compress_types
7379 /*
7380 # uncoverable statement class:ignore_covered_err
7381 # uncoverable condition left count:1 */
7382 134 ▶ ? SvREFCNT_inc(cfg->compress_types) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? SvREFCNT_inc(cfg->compress_types) : NULL; 0 134 134
7383 134 loop->logtok = cfg->logtok; /* compiled once, in the parent */
7384 134 loop->nlogtok = cfg->nlogtok;
7385 134 loop->log_json = cfg->log_json;
7386 134 loop->log_wants_t0 = cfg->log_wants_t0;
7387 /*
7388 # uncoverable branch true class:ignore_covered_err
7389 # uncoverable condition left count:1 class:ignore_covered_err */
7390 134 ▶ if (hm_worker_listeners(loop, cfg, fds) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_worker_listeners(loop, cfg, fds) < 0) { 0 134 134
7391 0 hm_loop_free(aTHX_ loop); /* # uncoverable statement */
7392 0 hm_exit(1); /* # uncoverable statement */
7393 }
7394 134 ▶ if (cfg->log_fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->log_fd >= 0) 8 126 134
7395 8 loop->log_fd = cfg->log_fd; /* fast C writer wins */
7396 126 ▶ else if (cfg->log_cb && SvOK(cfg->log_cb)) /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
else if (cfg->log_cb && SvOK(cfg->log_cb)) /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 122 126
else if (cfg->log_cb && SvOK(cfg->log_cb)) /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 0 4
7397 4 loop->log_cb = SvREFCNT_inc(cfg->log_cb);
7398 134 hm_attach_server(aTHX_ loop, cfg->app);
7399 /* v4 on_worker_start: the loop exists and has not started turning, and in
7400 * a prefork server this is already the child. The one moment a consumer
7401 * can attach something loop-bound and have it belong to the process that
7402 * will actually serve. Fires here rather than at either call site so the
7403 * single-worker case, which never forks, gets it too. */
7404 134 hm_worker_hook_fire(aTHX_ (void *)loop);
7405  
7406 /* The bus wakeup. The descriptors were made before the fork; this worker
7407 * takes the one that is its own and puts it on the loop, so a publish from
7408 * a sibling returns this loop from epoll with the message already on the
7409 * ring rather than leaving it to be found whenever somebody next looks.
7410 *
7411 * After hm_worker_hook_fire, so an application's own on_worker_start has
7412 * already run and anything it subscribed is registered before the first
7413 * wakeup can arrive. */
7414 134 hm_bus_worker_attach(aTHX_ loop);
7415 /* A peer slot of this worker's own in the Shared::Arena, keyed on the
7416 * pid it has now rather than the one it inherited. */
7417 134 hm_sa_worker_join();
7418 /* This worker's scoreboard row, mirrored now and then once a second.
7419 * The tick also beats the peer row, so a worker that only ever receives
7420 * on the bus never looks dead to the ring's hole escalation. */
7421 134 ▶ if (hm_sa_board_live() && hm_sa_board_take() >= 0) /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (hm_sa_board_live() && hm_sa_board_take() >= 0) /* # uncoverable condition right count:2 class:ignore_covered_err */ 130 4 134
if (hm_sa_board_live() && hm_sa_board_take() >= 0) /* # uncoverable condition right count:2 class:ignore_covered_err */ 130 0 130
7422 130 hm_board_tick(aTHX_ loop);
7423  
7424 134 hm_loop_run(aTHX_ loop, NULL);
7425 134 hm_loop_free(aTHX_ loop);
7426 134 }
7427  
7428 #ifndef _WIN32
7429 /* Fork one worker. With reuseport each worker binds its own listeners; with
7430 * affinity (Linux) worker widx is pinned to core widx % ncpu. */
7431 82 static pid_t hm_spawn(pTHX_ const hm_worker_cfg *cfg, int widx) {
7432 82 pid_t pid = fork();
7433 166 ▶ if (pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) { 84 82 166
7434 int stackfds[8];
7435 84 int *fds = NULL;
7436  
7437 /* A RESPAWNED worker is forked from inside the supervisor's loop,
7438 * where the pool's signals are handled by hm_sup_sig and BLOCKED.
7439 * The child inherits both. Until the worker's own loop has taken
7440 * over its signals, a TERM landing here would run the supervisor's
7441 * handler and set a flag nobody in this process reads: the signal
7442 * is swallowed, the worker never learns the pool is shutting down,
7443 * and the supervisor waits for it for ever. Found by a test that
7444 * killed a worker and sent TERM the moment its replacement had a
7445 * scoreboard row. Default dispositions and an empty mask, so a
7446 * TERM in that window ends the child, which is what TERM means. */
7447 {
7448 sigset_t none;
7449 84 sigemptyset(&none);
7450 84 signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL);
7451 84 signal(SIGHUP, SIG_DFL); signal(SIGUSR1, SIG_DFL);
7452 84 signal(SIGUSR2, SIG_DFL); signal(SIGCHLD, SIG_DFL);
7453 84 signal(SIGALRM, SIG_DFL);
7454 84 alarm(0);
7455 84 sigprocmask(SIG_SETMASK, &none, NULL);
7456 }
7457  
7458 /* Tell perl it has been forked. $$ is a plain SV that perl only
7459 * refreshes inside pp_fork; forking from C here happens behind its
7460 * back, so without this the worker keeps reporting the supervisor's
7461 * pid - and POSIX::getpid is `sub getpid { $$ }`, so that reads wrong
7462 * too. Anything in the application that names a log line, a temp file
7463 * or a pid file after $$ then collides across the whole pool. This is
7464 * what pp_fork itself does in the child. */
7465 {
7466 84 GV *pidgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV);
7467 /*
7468 # uncoverable branch false class:ignore_covered_err
7469 # uncoverable condition right count:1 class:ignore_covered_err */
7470 84 ▶ if (pidgv) {
Branch: 1 branch
BranchTrueFalseTotal
if (pidgv) { 84 0 84
7471 84 SvREADONLY_off(GvSV(pidgv));
7472 84 sv_setiv(GvSV(pidgv), (IV)getpid());
7473 84 SvREADONLY_on(GvSV(pidgv));
7474 }
7475 }
7476  
7477 #if defined(__linux__) && defined(CPU_SET)
7478 /*
7479 # uncoverable branch true
7480 # uncoverable condition left count:1 */
7481 84 ▶ if (cfg->affinity) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->affinity) { 0 84 84
7482 0 long ncpu = sysconf(_SC_NPROCESSORS_ONLN); /* # uncoverable statement */
7483 /*
7484 # uncoverable statement
7485 # uncoverable branch true
7486 # uncoverable branch false
7487 # uncoverable condition left count:1
7488 # uncoverable condition right count:1 */
7489 0 ▶ if (ncpu > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ncpu > 0) { 0 0 0
7490 cpu_set_t set;
7491 0 CPU_ZERO(&set); /* # uncoverable statement */
7492 0 ▶ CPU_SET((int)(widx % ncpu), &set); /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
CPU_SET((int)(widx % ncpu), &set); /* # uncoverable statement */ 0 0 0
7493 0 sched_setaffinity(0, sizeof(set), &set); /* # uncoverable statement */
7494 }
7495 }
7496 #else
7497 (void)widx;
7498 #endif
7499 84 ▶ if (cfg->reuseport) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) { 2 82 84
7500 2 int i, n = cfg->nlspecs;
7501 /* Two descriptors per listener now, TCP in the first half and
7502 * QUIC in the second, so hm_worker_listeners reads fds[i] and
7503 * fds[n + i]. */
7504 4 fds = 2 * n <= (int)(sizeof(stackfds)/sizeof(stackfds[0]))
7505 ? stackfds
7506 2 ▶ : (int *)hm_xmalloc(sizeof(int) * 2 * n); /* # uncoverable statement class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
: (int *)hm_xmalloc(sizeof(int) * 2 * n); /* # uncoverable statement class:ignore_covered_err */ 2 0 2
7507 4 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 2 2 4
7508 4 fds[i] = hm_make_listener((struct sockaddr *)&cfg->lspecs[i].sa,
7509 2 cfg->lspecs[i].salen, 1);
7510 /*
7511 # uncoverable branch true class:ignore_covered_err
7512 # uncoverable condition left count:1 class:ignore_covered_err */
7513 2 ▶ if (fds[i] < 0) hm_exit(1);
Branch: 1 branch
BranchTrueFalseTotal
if (fds[i] < 0) hm_exit(1); 0 2 2
7514 2 fds[n + i] = -1; /* # uncoverable statement class:ignore_covered_err */
7515 /*
7516 # uncoverable statement class:ignore_covered_err
7517 # uncoverable branch true
7518 # uncoverable condition left count:1 */
7519 2 ▶ if (cfg->lspecs[i].http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->lspecs[i].http3) { 0 2 2
7520 0 fds[n + i] = hm_make_udp_listener((struct sockaddr *)&cfg->lspecs[i].sa, /* # uncoverable statement */
7521 0 cfg->lspecs[i].salen, 1); /* # uncoverable statement */
7522 /*
7523 # uncoverable statement
7524 # uncoverable branch true
7525 # uncoverable branch false
7526 # uncoverable condition left count:1
7527 # uncoverable condition right count:1 */
7528 0 ▶ if (fds[n + i] < 0) hm_exit(1);
Branch: 1 branch
BranchTrueFalseTotal
if (fds[n + i] < 0) hm_exit(1); 0 0 0
7529 }
7530 }
7531 }
7532 /* This child's own waker slot, claimed before hm_worker so the
7533 * attach below finds it. Index by worker number, so two workers never
7534 * share a descriptor. */
7535 84 (void)hm_sa_bus_waker_take(widx);
7536 84 hm_worker(aTHX_ cfg, fds);
7537 84 hm_exit(0);
7538 }
7539 82 return pid;
7540 }
7541 #endif /* !_WIN32 */
7542  
7543 /* The full server: validate + bind, then either run in-process (1 worker)
7544 * or supervise a pool (respawn with backoff, HUP/USR2 recycle, USR1 stats,
7545 * TERM/INT bounded drain). */
7546 /* ---- privileges and the pid file ----------------------------------------- */
7547  
7548 11 static int hm_all_digits(const char *s) {
7549 /*
7550 # uncoverable branch true
7551 # uncoverable condition left count:1 class:ignore_covered_err */
7552 11 ▶ if (!*s) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!*s) return 0; 0 11 11
7553 39 ▶ for (; *s; s++) if (*s < '0' || *s > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
for (; *s; s++) if (*s < '0' || *s > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 32 0 32
for (; *s; s++) if (*s < '0' || *s > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 4 28 32
for (; *s; s++) if (*s < '0' || *s > '9') return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 32 7 39
7554 7 return 1;
7555 }
7556  
7557 /* Turn user/group names into ids. Called before anything is bound: a typo
7558 * in `user` must not leave a server listening as root. */
7559 114 static void hm_resolve_drop(pTHX_ hm_worker_cfg *cfg) {
7560 114 ▶ if (!cfg->drop_user && !cfg->drop_group && !cfg->umask_set && !cfg->pid_path) /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 4 branches
BranchTrueFalseTotal
if (!cfg->drop_user && !cfg->drop_group && !cfg->umask_set && !cfg->pid_path) /* # uncoverable condition right count:2 class:ignore_covered_err */ 105 9 114
if (!cfg->drop_user && !cfg->drop_group && !cfg->umask_set && !cfg->pid_path) /* # uncoverable condition right count:2 class:ignore_covered_err */ 105 0 105
if (!cfg->drop_user && !cfg->drop_group && !cfg->umask_set && !cfg->pid_path) /* # uncoverable condition right count:2 class:ignore_covered_err */ 104 1 105
if (!cfg->drop_user && !cfg->drop_group && !cfg->umask_set && !cfg->pid_path) /* # uncoverable condition right count:2 class:ignore_covered_err */ 92 12 104
7561 92 return;
7562 #ifdef _WIN32
7563 croak("Hyperman->run: user, group, umask and pid_file are not supported "
7564 "on Windows");
7565 #else
7566 22 cfg->drop_name[0] = '\0';
7567 22 ▶ if (cfg->drop_user) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_user) { 9 13 22
7568 9 ▶ if (hm_all_digits(cfg->drop_user)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_all_digits(cfg->drop_user)) { 6 3 9
7569 struct passwd *pw;
7570 6 cfg->drop_uid = atol(cfg->drop_user);
7571 6 cfg->drop_uid_set = 1;
7572 6 pw = getpwuid((uid_t)cfg->drop_uid);
7573 6 ▶ if (pw) {
Branch: 1 branch
BranchTrueFalseTotal
if (pw) { 3 3 6
7574 3 strncpy(cfg->drop_name, pw->pw_name, sizeof(cfg->drop_name) - 1);
7575 3 ▶ if (!cfg->drop_group) { cfg->drop_gid = (long)pw->pw_gid; cfg->drop_gid_set = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg->drop_group) { cfg->drop_gid = (long)pw->pw_gid; cfg->drop_gid_set = 1; } 1 2 3
7576 /*
7577 # uncoverable branch false
7578 # uncoverable condition right count:1 class:ignore_covered_err */
7579 3 ▶ } else if (!cfg->drop_group) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!cfg->drop_group) { 3 0 3
7580 /* No entry to take a group from: without one the workers
7581 * would keep gid 0 and root's supplementary groups behind a
7582 * harmless-looking uid. */
7583 3 croak("Hyperman->run: user %s has no passwd entry; name a "
7584 "group => as well", cfg->drop_user);
7585 }
7586 } else {
7587 3 struct passwd *pw = getpwnam(cfg->drop_user);
7588 3 ▶ if (!pw) croak("Hyperman->run: user '%s': no such user", cfg->drop_user);
Branch: 1 branch
BranchTrueFalseTotal
if (!pw) croak("Hyperman->run: user '%s': no such user", cfg->drop_user); 2 1 3
7589 1 cfg->drop_uid = (long)pw->pw_uid;
7590 1 cfg->drop_uid_set = 1;
7591 1 strncpy(cfg->drop_name, pw->pw_name, sizeof(cfg->drop_name) - 1);
7592 /*
7593 # uncoverable branch false class:ignore_covered_err
7594 # uncoverable condition right count:1 class:ignore_covered_err */
7595 1 ▶ if (!cfg->drop_group) { cfg->drop_gid = (long)pw->pw_gid; cfg->drop_gid_set = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg->drop_group) { cfg->drop_gid = (long)pw->pw_gid; cfg->drop_gid_set = 1; } 1 0 1
7596 }
7597 }
7598 17 ▶ if (cfg->drop_group) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_group) { 2 15 17
7599 2 ▶ if (hm_all_digits(cfg->drop_group)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_all_digits(cfg->drop_group)) { 1 1 2
7600 1 cfg->drop_gid = atol(cfg->drop_group);
7601 } else {
7602 1 struct group *gr = getgrnam(cfg->drop_group);
7603 /*
7604 # uncoverable branch false
7605 # uncoverable condition right count:1 class:ignore_covered_err */
7606 1 ▶ if (!gr) croak("Hyperman->run: group '%s': no such group", cfg->drop_group);
Branch: 1 branch
BranchTrueFalseTotal
if (!gr) croak("Hyperman->run: group '%s': no such group", cfg->drop_group); 1 0 1
7607 0 cfg->drop_gid = (long)gr->gr_gid; /* # uncoverable statement */
7608 }
7609 1 cfg->drop_gid_set = 1;
7610 }
7611 #endif
7612 }
7613  
7614 /* Group first, then the user: once the uid is gone the gid cannot follow.
7615 * Each step is checked and a failure CROAKS - a server that could not drop
7616 * must not go on serving as root as if it had. */
7617 77 static void hm_drop_privileges(pTHX_ const hm_worker_cfg *cfg) {
7618 #ifndef _WIN32
7619 77 ▶ if (cfg->umask_set) umask((mode_t)cfg->umask_val);
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->umask_set) umask((mode_t)cfg->umask_val); 1 76 77
7620 /* Not root: a re-exec successor forked by a supervisor that had already
7621 * dropped. It cannot change its ids and need not, if it already has the
7622 * ones asked for; anything else is refused, as before. */
7623 /*
7624 # uncoverable branch true class:ignore_covered_err
7625 # uncoverable condition left count:1 class:ignore_covered_err
7626 # uncoverable condition left count:2 class:ignore_covered_err
7627 # uncoverable condition right count:2 class:ignore_covered_err
7628 # uncoverable condition left count:3 class:ignore_covered_err
7629 # uncoverable condition right count:3 class:ignore_covered_err */
7630 77 ▶ if (geteuid() != 0 && (cfg->drop_uid_set || cfg->drop_gid_set)) {
Branch: 3 branches
BranchTrueFalseTotal
if (geteuid() != 0 && (cfg->drop_uid_set || cfg->drop_gid_set)) { 77 0 77
if (geteuid() != 0 && (cfg->drop_uid_set || cfg->drop_gid_set)) { 77 0 77
if (geteuid() != 0 && (cfg->drop_uid_set || cfg->drop_gid_set)) { 0 77 77
7631 /*
7632 # uncoverable statement
7633 # uncoverable branch true
7634 # uncoverable branch false
7635 # uncoverable condition left count:1
7636 # uncoverable condition right count:1
7637 # uncoverable condition left count:2
7638 # uncoverable condition right count:2
7639 # uncoverable condition left count:3
7640 # uncoverable condition right count:3 */
7641 0 ▶ if (cfg->drop_uid_set && (getuid() != (uid_t)cfg->drop_uid
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->drop_uid_set && (getuid() != (uid_t)cfg->drop_uid 0 0 0
if (cfg->drop_uid_set && (getuid() != (uid_t)cfg->drop_uid 0 0 0
7642 0 ▶ || geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
|| geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */ 0 0 0
7643 0 croak("Hyperman->run: not root, and not uid %ld either: cannot " /* # uncoverable statement */
7644 "become user '%s'", cfg->drop_uid, cfg->drop_user); /* # uncoverable statement */
7645 /*
7646 # uncoverable statement
7647 # uncoverable branch true
7648 # uncoverable branch false
7649 # uncoverable condition left count:1
7650 # uncoverable condition right count:1
7651 # uncoverable condition left count:2
7652 # uncoverable condition right count:2 */
7653 0 ▶ if (cfg->drop_gid_set && getegid() != (gid_t)cfg->drop_gid)
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->drop_gid_set && getegid() != (gid_t)cfg->drop_gid) 0 0 0
if (cfg->drop_gid_set && getegid() != (gid_t)cfg->drop_gid) 0 0 0
7654 0 croak("Hyperman->run: not root, and not gid %ld either: cannot " /* # uncoverable statement */
7655 "change group", cfg->drop_gid); /* # uncoverable statement */
7656 0 return; /* # uncoverable statement */
7657 }
7658 /*
7659 # uncoverable statement class:ignore_covered_err
7660 # uncoverable branch true
7661 # uncoverable condition left count:1 */
7662 77 ▶ if (cfg->drop_gid_set) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_gid_set) { 0 77 77
7663 /*
7664 # uncoverable statement
7665 # uncoverable branch true
7666 # uncoverable branch false
7667 # uncoverable condition left count:1
7668 # uncoverable condition right count:1 */
7669 0 ▶ if (cfg->drop_name[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_name[0]) { 0 0 0
7670 /*
7671 # uncoverable statement
7672 # uncoverable branch true
7673 # uncoverable branch false
7674 # uncoverable condition left count:1
7675 # uncoverable condition right count:1 */
7676 0 ▶ if (initgroups(cfg->drop_name, (gid_t)cfg->drop_gid) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (initgroups(cfg->drop_name, (gid_t)cfg->drop_gid) < 0) 0 0 0
7677 0 croak("Hyperman->run: initgroups(%s): %s", cfg->drop_name, strerror(errno)); /* # uncoverable statement */
7678 } else {
7679 0 gid_t g = (gid_t)cfg->drop_gid; /* # uncoverable statement */
7680 /*
7681 # uncoverable statement
7682 # uncoverable branch true
7683 # uncoverable branch false
7684 # uncoverable condition left count:1
7685 # uncoverable condition right count:1 */
7686 0 ▶ if (setgroups(1, &g) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (setgroups(1, &g) < 0) 0 0 0
7687 0 croak("Hyperman->run: setgroups: %s", strerror(errno)); /* # uncoverable statement */
7688 }
7689 /*
7690 # uncoverable statement
7691 # uncoverable branch true
7692 # uncoverable branch false
7693 # uncoverable condition left count:1
7694 # uncoverable condition right count:1 */
7695 0 ▶ if (setgid((gid_t)cfg->drop_gid) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (setgid((gid_t)cfg->drop_gid) < 0) 0 0 0
7696 0 croak("Hyperman->run: setgid(%ld): %s", cfg->drop_gid, strerror(errno)); /* # uncoverable statement */
7697 }
7698 /*
7699 # uncoverable statement class:ignore_covered_err
7700 # uncoverable branch true
7701 # uncoverable condition left count:1 */
7702 77 ▶ if (cfg->drop_uid_set) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_uid_set) { 0 77 77
7703 /*
7704 # uncoverable statement
7705 # uncoverable branch true
7706 # uncoverable branch false
7707 # uncoverable condition left count:1
7708 # uncoverable condition right count:1 */
7709 0 ▶ if (setuid((uid_t)cfg->drop_uid) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (setuid((uid_t)cfg->drop_uid) < 0) 0 0 0
7710 0 croak("Hyperman->run: setuid(%ld): %s", cfg->drop_uid, strerror(errno)); /* # uncoverable statement */
7711 /*
7712 # uncoverable statement
7713 # uncoverable branch true
7714 # uncoverable branch false
7715 # uncoverable condition left count:1
7716 # uncoverable condition right count:1
7717 # uncoverable condition left count:2
7718 # uncoverable condition right count:2
7719 # uncoverable condition left count:3
7720 # uncoverable condition right count:3 */
7721 0 ▶ if (cfg->drop_uid != 0 && (getuid() != (uid_t)cfg->drop_uid
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->drop_uid != 0 && (getuid() != (uid_t)cfg->drop_uid 0 0 0
if (cfg->drop_uid != 0 && (getuid() != (uid_t)cfg->drop_uid 0 0 0
7722 0 ▶ || geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
|| geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */ 0 0 0
7723 0 croak("Hyperman->run: still not uid %ld after setuid", cfg->drop_uid); /* # uncoverable statement */
7724 }
7725 #else
7726 (void)cfg;
7727 #endif
7728 }
7729  
7730 /* The pid file is written whole and renamed into place, so a reader never
7731 * sees it empty, and removed at exit ONLY if it still holds this pid: two
7732 * supervisors overlap during a re-exec reload, and the one leaving must not
7733 * take the other's file with it. */
7734 #ifndef O_NOFOLLOW
7735 #define O_NOFOLLOW 0
7736 #endif
7737 /* loud: a failure croaks (boot). Quiet: -1 and a log line, for the
7738 * supervisor re-asserting its own pid after a successor died. */
7739 83 static int hm_write_pidfile_(pTHX_ const hm_worker_cfg *cfg, int loud) {
7740 83 const char *path = cfg->pid_path;
7741 char tmp[1024], num[32];
7742 83 int fd = -1, n, tries, in_place = 0;
7743 83 ▶ if (!path) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!path) return 0; 69 14 83
7744 /* The temporary is created EXCLUSIVELY and never through a symlink: it
7745 * is written as root, before the drop, in a directory others may be
7746 * able to write to, and a predictable name opened with O_TRUNC was an
7747 * invitation to point it at a file of theirs. The suffix is random too,
7748 * so a planted name is not even a denial of service. */
7749 22 ▶ for (tries = 0; tries < 8 && fd < 0; tries++) { /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
for (tries = 0; tries < 8 && fd < 0; tries++) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 22 0 22
for (tries = 0; tries < 8 && fd < 0; tries++) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 14 8 22
7750 14 unsigned long r = (unsigned long)(hm_now_ns() ^ ((uint64_t)hm_os_getpid() << 20));
7751 14 n = snprintf(tmp, sizeof(tmp), "%s.%lx.tmp", path, r + (unsigned long)tries * 7919UL);
7752 14 ▶ if (n <= 0 || n >= (int)sizeof(tmp)) /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (n <= 0 || n >= (int)sizeof(tmp)) /* # uncoverable condition left count:1 class:ignore_covered_err */ 14 0 14
if (n <= 0 || n >= (int)sizeof(tmp)) /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 13 14
7753 1 croak("Hyperman->run: pid_file path too long");
7754 13 fd = hm_os_open_file(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644);
7755 13 ▶ if (fd < 0 && errno != EEXIST) break; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 && errno != EEXIST) break; /* # uncoverable condition right count:2 class:ignore_covered_err */ 5 8 13
if (fd < 0 && errno != EEXIST) break; /* # uncoverable condition right count:2 class:ignore_covered_err */ 5 0 5
7756 }
7757 /* Eight random names cannot all exist: an EEXIST that outlasts the loop
7758 * is a directory that will not create anything for this user, which
7759 * DragonFly reports this way where others say EACCES (CPAN Testers,
7760 * 0.68). It is handled as that refusal below. */
7761 /*
7762 # uncoverable branch true
7763 # uncoverable condition left count:1
7764 # uncoverable condition left count:2 */
7765 13 ▶ if (fd < 0 && errno == EEXIST) errno = EACCES;
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 && errno == EEXIST) errno = EACCES; 5 8 13
if (fd < 0 && errno == EEXIST) errno = EACCES; 0 5 5
7766 #ifndef _WIN32
7767 /*
7768 # uncoverable branch true class:ignore_covered_err
7769 # uncoverable condition left count:1 class:ignore_covered_err
7770 # uncoverable condition left count:2 class:ignore_covered_err
7771 # uncoverable condition left count:3 class:ignore_covered_err
7772 # uncoverable condition left count:4 class:ignore_covered_err
7773 # uncoverable condition right count:4 class:ignore_covered_err */
7774 13 ▶ if (fd < 0 && (errno == EACCES || errno == EPERM) && geteuid() != 0) {
Branch: 4 branches
BranchTrueFalseTotal
if (fd < 0 && (errno == EACCES || errno == EPERM) && geteuid() != 0) { 5 8 13
if (fd < 0 && (errno == EACCES || errno == EPERM) && geteuid() != 0) { 1 4 5
if (fd < 0 && (errno == EACCES || errno == EPERM) && geteuid() != 0) { 0 1 1
if (fd < 0 && (errno == EACCES || errno == EPERM) && geteuid() != 0) { 4 0 4
7775 /* A re-exec successor already running as the dropped user, in a
7776 * directory only root may create in (/run): the file itself was
7777 * chowned to that user when root wrote it, so it is rewritten in
7778 * place. Not atomic - a reader can catch it empty - but a pid file
7779 * the successor cannot update at all named a dead process. */
7780 4 fd = hm_os_open_file(path, O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0644); /* # uncoverable statement class:ignore_covered_err */
7781 4 in_place = 1; /* # uncoverable statement class:ignore_covered_err */
7782 }
7783 #endif
7784 13 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 4 9 13
7785 /*
7786 # uncoverable branch false
7787 # uncoverable condition right count:1 class:ignore_covered_err
7788 # uncoverable condition right count:2 class:ignore_covered_err */
7789 4 ▶ if (loud) croak("Hyperman->run: pid_file '%s': %s", in_place ? path : tmp,
Branch: 2 branches
BranchTrueFalseTotal
if (loud) croak("Hyperman->run: pid_file '%s': %s", in_place ? path : tmp, 4 0 4
if (loud) croak("Hyperman->run: pid_file '%s': %s", in_place ? path : tmp, 1 3 4
7790 strerror(errno));
7791 0 hm_errlog("Hyperman: pid_file '%s': %s\n", path, strerror(errno)); /* # uncoverable statement */
7792 0 return -1; /* # uncoverable statement */
7793 }
7794 9 n = (int)hm_itoa(num, (long)hm_os_getpid());
7795 9 num[n++] = '\n';
7796 /*
7797 # uncoverable branch true
7798 # uncoverable condition left count:1 class:ignore_covered_err */
7799 9 ▶ if (hm_os_write_file(fd, num, (size_t)n) != n) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_os_write_file(fd, num, (size_t)n) != n) { 0 9 9
7800 0 int e = errno; /* # uncoverable statement */
7801 0 hm_os_close(fd); /* # uncoverable statement */
7802 /*
7803 # uncoverable statement
7804 # uncoverable branch true
7805 # uncoverable branch false
7806 # uncoverable condition left count:1
7807 # uncoverable condition right count:1 */
7808 0 ▶ if (!in_place) (void)unlink(tmp);
Branch: 1 branch
BranchTrueFalseTotal
if (!in_place) (void)unlink(tmp); 0 0 0
7809 /*
7810 # uncoverable statement
7811 # uncoverable branch true
7812 # uncoverable branch false
7813 # uncoverable condition left count:1
7814 # uncoverable condition right count:1 */
7815 0 ▶ if (loud) croak("Hyperman->run: pid_file '%s': write: %s", path, strerror(e));
Branch: 1 branch
BranchTrueFalseTotal
if (loud) croak("Hyperman->run: pid_file '%s': write: %s", path, strerror(e)); 0 0 0
7816 0 hm_errlog("Hyperman: pid_file '%s': write: %s\n", path, strerror(e)); /* # uncoverable statement */
7817 0 return -1; /* # uncoverable statement */
7818 }
7819 #ifndef _WIN32
7820 /* Owned by the user the server will run as, so the successor of a
7821 * re-exec (born dropped) and the exit path can both still write it. */
7822 /*
7823 # uncoverable branch true class:ignore_covered_err
7824 # uncoverable condition left count:1 class:ignore_covered_err
7825 # uncoverable condition left count:2 class:ignore_covered_err
7826 # uncoverable condition right count:2 class:ignore_covered_err */
7827 9 ▶ if (cfg->drop_uid_set && geteuid() == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->drop_uid_set && geteuid() == 0) 0 9 9
if (cfg->drop_uid_set && geteuid() == 0) 0 0 0
7828 0 (void)fchown(fd, (uid_t)cfg->drop_uid, /* # uncoverable statement */
7829 /*
7830 # uncoverable statement
7831 # uncoverable condition left count:1
7832 # uncoverable condition right count:1 */
7833 0 ▶ cfg->drop_gid_set ? (gid_t)cfg->drop_gid : (gid_t)-1);
Branch: 1 branch
BranchTrueFalseTotal
cfg->drop_gid_set ? (gid_t)cfg->drop_gid : (gid_t)-1); 0 0 0
7834 #endif
7835 9 hm_os_close(fd);
7836 /*
7837 # uncoverable branch true class:ignore_covered_err
7838 # uncoverable condition left count:1 class:ignore_covered_err */
7839 9 ▶ if (in_place) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (in_place) return 0; 1 8 9
7840 /*
7841 # uncoverable branch true
7842 # uncoverable condition left count:1 class:ignore_covered_err */
7843 8 ▶ if (rename(tmp, path) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (rename(tmp, path) < 0) { 0 8 8
7844 0 int e = errno; /* # uncoverable statement */
7845 0 (void)unlink(tmp); /* # uncoverable statement */
7846 /*
7847 # uncoverable statement
7848 # uncoverable branch true
7849 # uncoverable branch false
7850 # uncoverable condition left count:1
7851 # uncoverable condition right count:1 */
7852 0 ▶ if (loud) croak("Hyperman->run: pid_file '%s': rename: %s", path, strerror(e));
Branch: 1 branch
BranchTrueFalseTotal
if (loud) croak("Hyperman->run: pid_file '%s': rename: %s", path, strerror(e)); 0 0 0
7853 0 hm_errlog("Hyperman: pid_file '%s': rename: %s\n", path, strerror(e)); /* # uncoverable statement */
7854 0 return -1; /* # uncoverable statement */
7855 }
7856 8 return 0;
7857 }
7858 82 static void hm_write_pidfile(pTHX_ const hm_worker_cfg *cfg) {
7859 82 (void)hm_write_pidfile_(aTHX_ cfg, 1);
7860 77 }
7861  
7862 /* Removed at exit if it still holds this pid. A process that dropped
7863 * privileges may not unlink in the directory any more (/run is root's);
7864 * then the file is emptied instead, which is what a reader should take as
7865 * "not running", where a stale pid is a live lie. */
7866 77 static void hm_unlink_pidfile(const char *path) {
7867 char buf[32];
7868 int fd, n;
7869 84 ▶ if (!path) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!path) return; 69 8 77
7870 8 fd = hm_os_open_file(path, O_RDONLY | O_NOFOLLOW, 0);
7871 /*
7872 # uncoverable branch true
7873 # uncoverable condition left count:1 class:ignore_covered_err */
7874 8 ▶ if (fd < 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return; 0 8 8
7875 8 n = (int)read(fd, buf, sizeof(buf) - 1);
7876 8 hm_os_close(fd);
7877 /*
7878 # uncoverable branch true
7879 # uncoverable condition left count:1 class:ignore_covered_err */
7880 8 ▶ if (n <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return; 0 8 8
7881 8 buf[n] = '\0';
7882 8 ▶ if (atol(buf) != (long)hm_os_getpid()) return;
Branch: 1 branch
BranchTrueFalseTotal
if (atol(buf) != (long)hm_os_getpid()) return; 3 5 8
7883 /*
7884 # uncoverable branch false class:ignore_covered_err
7885 # uncoverable condition right count:1 class:ignore_covered_err */
7886 5 ▶ if (unlink(path) == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (unlink(path) == 0) return; 4 1 5
7887 /*
7888 # uncoverable statement class:ignore_covered_err
7889 # uncoverable branch true class:ignore_covered_err
7890 # uncoverable branch false class:ignore_covered_err
7891 # uncoverable condition left count:1 class:ignore_covered_err
7892 # uncoverable condition right count:1 class:ignore_covered_err
7893 # uncoverable condition left count:2 class:ignore_covered_err
7894 # uncoverable condition right count:2 class:ignore_covered_err */
7895 1 ▶ if (errno == EACCES || errno == EPERM) {
Branch: 2 branches
BranchTrueFalseTotal
if (errno == EACCES || errno == EPERM) { 0 1 1
if (errno == EACCES || errno == EPERM) { 0 0 0
7896 1 fd = hm_os_open_file(path, O_WRONLY | O_TRUNC | O_NOFOLLOW, 0); /* # uncoverable statement class:ignore_covered_err */
7897 /*
7898 # uncoverable statement class:ignore_covered_err
7899 # uncoverable branch true class:ignore_covered_err
7900 # uncoverable branch false class:ignore_covered_err
7901 # uncoverable condition left count:1 class:ignore_covered_err
7902 # uncoverable condition right count:1 class:ignore_covered_err */
7903 1 ▶ if (fd >= 0) hm_os_close(fd);
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) hm_os_close(fd); 1 0 1
7904 }
7905 }
7906  
7907 /* Remove a variable from the C environment AND perl's %ENV, which is a hash
7908 * of its own, filled at startup: unsetenv alone leaves the application
7909 * reading the old value from the hash. Deleting through the hash updates
7910 * the C side via its magic; the explicit unsetenv covers a perl built
7911 * without that. */
7912 8 static void hm_env_unset(pTHX_ const char *name) {
7913 8 HV *penv = GvHV(PL_envgv);
7914 /*
7915 # uncoverable branch false class:ignore_covered_err
7916 # uncoverable condition right count:1 class:ignore_covered_err */
7917 8 ▶ if (penv) (void)hv_delete(penv, name, (I32)strlen(name), G_DISCARD);
Branch: 1 branch
BranchTrueFalseTotal
if (penv) (void)hv_delete(penv, name, (I32)strlen(name), G_DISCARD); 8 0 8
7918 #ifndef _WIN32
7919 8 unsetenv(name);
7920 #endif
7921 8 }
7922  
7923 /* Socket activation: a service manager that bound the sockets hands them
7924 * over as fds 3.., naming the count in LISTEN_FDS and this pid in
7925 * LISTEN_PID. Specs marked `inherit` (or all of them under listen_fds) take
7926 * them in order instead of binding. Each one is checked to be a listening
7927 * socket of the family the spec resolved to, and both variables are removed
7928 * at once so no worker - and no server an application forks - adopts them
7929 * again. The same helper will seat a re-exec successor (08). */
7930 104 static void hm_adopt_fds(pTHX_ hm_worker_cfg *cfg) {
7931 104 const char *nfds = getenv("LISTEN_FDS"), *lpid = getenv("LISTEN_PID");
7932 104 int i, n, next = 3, want = 0;
7933 /* A spec that already holds a socket was seated by hm_adopt_env: a
7934 * re-exec successor of a socket-activated server. LISTEN_FDS was
7935 * removed from the environment at the first boot, so counting those
7936 * specs made every USR2 under systemd croak "not set". */
7937 216 ▶ for (i = 0; i < cfg->nlspecs; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) 112 104 216
7938 112 ▶ if ((cfg->listen_fds || cfg->lspecs[i].inherit) && cfg->lspecs[i].fd < 0) /* # uncoverable condition right count:3 class:ignore_covered_err */
Branch: 3 branches
BranchTrueFalseTotal
if ((cfg->listen_fds || cfg->lspecs[i].inherit) && cfg->lspecs[i].fd < 0) /* # uncoverable condition right count:3 class:ignore_covered_err */ 103 9 112
if ((cfg->listen_fds || cfg->lspecs[i].inherit) && cfg->lspecs[i].fd < 0) /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 102 103
if ((cfg->listen_fds || cfg->lspecs[i].inherit) && cfg->lspecs[i].fd < 0) /* # uncoverable condition right count:3 class:ignore_covered_err */ 10 0 10
7939 10 want++;
7940 104 ▶ if (!want) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!want) return; 95 9 104
7941 #ifdef _WIN32
7942 croak("Hyperman->run: socket activation is not supported on Windows");
7943 #else
7944 9 ▶ if (!nfds || !lpid) /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!nfds || !lpid) /* # uncoverable condition left count:2 class:ignore_covered_err */ 8 1 9
if (!nfds || !lpid) /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 8 8
7945 1 croak("Hyperman->run: a listener asks to inherit a socket but LISTEN_FDS "
7946 "and LISTEN_PID are not set");
7947 8 ▶ if (atol(lpid) != (long)hm_os_getpid())
Branch: 1 branch
BranchTrueFalseTotal
if (atol(lpid) != (long)hm_os_getpid()) 2 6 8
7948 2 croak("Hyperman->run: LISTEN_PID is %s, this is %d: the sockets were "
7949 "not handed to this process", lpid, hm_os_getpid());
7950 6 ▶ if (cfg->reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) 1 5 6
7951 1 croak("Hyperman->run: an inherited socket cannot be rebound per worker; "
7952 "drop reuseport");
7953 5 n = atoi(nfds);
7954 7 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 6 1 7
7955 6 hm_listener_spec *s = &cfg->lspecs[i];
7956 struct sockaddr_storage got;
7957 6 socklen_t gl = sizeof(got);
7958 6 int fd, acc = 0;
7959 6 socklen_t al = sizeof(acc);
7960 /*
7961 # uncoverable branch true class:ignore_covered_err
7962 # uncoverable condition left count:1 class:ignore_covered_err
7963 # uncoverable condition left count:2 class:ignore_covered_err
7964 # uncoverable condition right count:2 class:ignore_covered_err
7965 # uncoverable condition left count:3 class:ignore_covered_err */
7966 6 ▶ if (!(cfg->listen_fds || s->inherit) || s->fd >= 0) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(cfg->listen_fds || s->inherit) || s->fd >= 0) continue; 0 6 6
if (!(cfg->listen_fds || s->inherit) || s->fd >= 0) continue; 0 0 0
if (!(cfg->listen_fds || s->inherit) || s->fd >= 0) continue; 0 6 6
7967 6 ▶ if (next - 3 >= n)
Branch: 1 branch
BranchTrueFalseTotal
if (next - 3 >= n) 1 5 6
7968 1 croak("Hyperman->run: LISTEN_FDS=%d but listener %d wants one too", n, i);
7969 5 fd = next++;
7970 /*
7971 # uncoverable branch true class:ignore_covered_err
7972 # uncoverable condition left count:1 class:ignore_covered_err */
7973 5 ▶ if (s->http3)
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) 0 5 5
7974 0 croak("Hyperman->run: an inherited listener cannot carry http3"); /* # uncoverable statement class:ignore_covered_err */
7975 5 ▶ if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0) 1 4 5
7976 1 croak("Hyperman->run: inherited fd %d: getsockname: %s", fd, strerror(errno));
7977 4 ▶ if (got.ss_family != s->sa.ss_family)
Branch: 1 branch
BranchTrueFalseTotal
if (got.ss_family != s->sa.ss_family) 1 3 4
7978 1 croak("Hyperman->run: inherited fd %d is address family %d, listener %d "
7979 "resolved to %d", fd, (int)got.ss_family, i, (int)s->sa.ss_family);
7980 3 ▶ if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &acc, &al) == 0 && !acc) /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &acc, &al) == 0 && !acc) /* # uncoverable condition right count:1 class:ignore_covered_err */ 3 0 3
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &acc, &al) == 0 && !acc) /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 2 3
7981 1 croak("Hyperman->run: inherited fd %d is not a listening socket", fd); /* # uncoverable statement class:ignore_covered_err */
7982 2 hm_set_nonblock(fd);
7983 /* As a bound listener is (hm_make_listener): not into anything the
7984 * application execs; hm_reexec clears it for the successor alone. */
7985 2 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
7986 2 s->fd = fd;
7987 }
7988 1 hm_env_unset(aTHX_ "LISTEN_FDS");
7989 1 hm_env_unset(aTHX_ "LISTEN_PID");
7990 1 hm_env_unset(aTHX_ "LISTEN_FDNAMES");
7991 #endif
7992 }
7993  
7994 /* ---- re-exec reload (USR2) -------------------------------------------------
7995 *
7996 * HUP reforks the pool from this process, which still holds the application
7997 * as it was compiled at boot. USR2 starts a NEW supervisor - a fresh perl, a
7998 * fresh compile of the application - that takes the bound listeners over,
7999 * forks its own pool, and only then asks this one to drain. The listen fds
8000 * are held by one process or the other the whole time, so no connection is
8001 * refused. A successor that fails to start changes nothing here; this
8002 * supervisor keeps serving and says so.
8003 *
8004 * What crosses the exec: the listener fds, named in HYPERMAN_REEXEC by the
8005 * host:port (or path) each was bound for, so the successor's configuration
8006 * may reorder or add listeners; the arena NAME, when there is one, so both
8007 * pools share the one arena during the overlap; and the old supervisor's
8008 * pid, to TERM. An anonymous arena is not shared: it is a private mapping
8009 * with no name to attach to, and the successor starts a fresh one (the
8010 * denylist and the rate counters begin again at the handoff). */
8011  
8012 #ifndef _WIN32
8013 5 static void hm_reexec(pTHX_ const hm_worker_cfg *cfg, const sigset_t *orig) {
8014 char env[4096];
8015 5 size_t n = 0;
8016 int i, k;
8017 pid_t pid;
8018 SV *perl;
8019 5 ▶ if (hm_resup_pid > 0 && kill(hm_resup_pid, 0) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (hm_resup_pid > 0 && kill(hm_resup_pid, 0) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 4 5
if (hm_resup_pid > 0 && kill(hm_resup_pid, 0) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
8020 1 hm_errlog("Hyperman: USR2 ignored: successor %d is still starting",
8021 (int)hm_resup_pid);
8022 1 return;
8023 }
8024 /*
8025 # uncoverable branch true class:ignore_covered_err
8026 # uncoverable condition left count:1 class:ignore_covered_err
8027 # uncoverable condition left count:2 class:ignore_covered_err */
8028 4 ▶ if (!hm_boot_argv || !hm_boot_argv[0]) {
Branch: 2 branches
BranchTrueFalseTotal
if (!hm_boot_argv || !hm_boot_argv[0]) { 4 0 4
if (!hm_boot_argv || !hm_boot_argv[0]) { 0 4 4
8029 0 hm_errlog("Hyperman: USR2 ignored: no argv to re-exec with"); /* # uncoverable statement */
8030 0 return; /* # uncoverable statement */
8031 }
8032 4 k = snprintf(env + n, sizeof(env) - n, "sup=%d", hm_os_getpid());
8033 /*
8034 # uncoverable branch true class:ignore_covered_err
8035 # uncoverable condition left count:1 class:ignore_covered_err
8036 # uncoverable condition left count:2 class:ignore_covered_err */
8037 4 ▶ if (k < 0 || (size_t)k >= sizeof(env) - n) return;
Branch: 2 branches
BranchTrueFalseTotal
if (k < 0 || (size_t)k >= sizeof(env) - n) return; 4 0 4
if (k < 0 || (size_t)k >= sizeof(env) - n) return; 0 4 4
8038 4 n += (size_t)k;
8039 4 ▶ if (cfg->arena_name && cfg->arena_name_len) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->arena_name && cfg->arena_name_len) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 1 4
if (cfg->arena_name && cfg->arena_name_len) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 3 0 3
8040 3 k = snprintf(env + n, sizeof(env) - n, ";arena=%.*s",
8041 3 (int)cfg->arena_name_len, cfg->arena_name);
8042 /*
8043 # uncoverable branch true class:ignore_covered_err
8044 # uncoverable condition left count:1 class:ignore_covered_err
8045 # uncoverable condition left count:2 class:ignore_covered_err */
8046 3 ▶ if (k < 0 || (size_t)k >= sizeof(env) - n) {
Branch: 2 branches
BranchTrueFalseTotal
if (k < 0 || (size_t)k >= sizeof(env) - n) { 3 0 3
if (k < 0 || (size_t)k >= sizeof(env) - n) { 0 3 3
8047 0 hm_errlog("Hyperman: USR2 ignored: the arena name does not fit the " /* # uncoverable statement */
8048 "handover environment");
8049 0 return; /* # uncoverable statement */
8050 }
8051 3 n += (size_t)k;
8052 }
8053 9 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 5 4 9
8054 5 const hm_listener_spec *s = &cfg->lspecs[i];
8055 /*
8056 # uncoverable branch true
8057 # uncoverable condition left count:1 class:ignore_covered_err */
8058 5 ▶ if (s->fd < 0) continue; /* reuseport: nothing held */
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd < 0) continue; /* reuseport: nothing held */ 0 5 5
8059 5 ▶ if (s->path)
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) 1 4 5
8060 1 k = snprintf(env + n, sizeof(env) - n, ";u=%s|%d", s->path, s->fd);
8061 else
8062 4 k = snprintf(env + n, sizeof(env) - n, ";l=%s|%d|%d|%d",
8063 /*
8064 # uncoverable condition right count:1
8065 # uncoverable condition right count:2 */
8066 4 ▶ s->host && *s->host ? s->host : "0.0.0.0", s->port,
Branch: 1 branch
BranchTrueFalseTotal
s->host && *s->host ? s->host : "0.0.0.0", s->port, 4 0 4
8067 4 ▶ s->fd, s->udp_fd);
Branch: 1 branch
BranchTrueFalseTotal
s->fd, s->udp_fd); 4 0 4
8068 /*
8069 # uncoverable branch true class:ignore_covered_err
8070 # uncoverable condition left count:1 class:ignore_covered_err
8071 # uncoverable condition left count:2 class:ignore_covered_err */
8072 5 ▶ if (k < 0 || (size_t)k >= sizeof(env) - n) {
Branch: 2 branches
BranchTrueFalseTotal
if (k < 0 || (size_t)k >= sizeof(env) - n) { 5 0 5
if (k < 0 || (size_t)k >= sizeof(env) - n) { 0 5 5
8073 0 hm_errlog("Hyperman: USR2 ignored: too many listeners to hand over"); /* # uncoverable statement */
8074 0 return; /* # uncoverable statement */
8075 }
8076 5 n += (size_t)k;
8077 }
8078 4 perl = get_sv("\030", 0); /* $^X */
8079 /*
8080 # uncoverable branch true class:ignore_covered_err
8081 # uncoverable condition left count:1 class:ignore_covered_err
8082 # uncoverable condition left count:2 class:ignore_covered_err */
8083 4 ▶ if (!perl || !SvOK(perl)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!perl || !SvOK(perl)) { 4 0 4
if (!perl || !SvOK(perl)) { 0 4 4
8084 0 hm_errlog("Hyperman: USR2 ignored: $^X is not set"); /* # uncoverable statement */
8085 0 return; /* # uncoverable statement */
8086 }
8087 4 pid = fork();
8088 /*
8089 # uncoverable branch true
8090 # uncoverable condition left count:1 class:ignore_covered_err */
8091 8 ▶ if (pid < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid < 0) { 0 8 8
8092 0 hm_errlog("Hyperman: USR2: fork: %s", strerror(errno)); /* # uncoverable statement */
8093 0 return; /* # uncoverable statement */
8094 }
8095 8 ▶ if (pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) { 4 4 8
8096 /* The supervisor runs with its signals BLOCKED and the mask survives
8097 * exec, as does a pending alarm: a successor born with either would
8098 * never wake in its own sigsuspend. */
8099 4 sigprocmask(SIG_SETMASK, orig, NULL);
8100 4 alarm(0);
8101 4 signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL);
8102 4 signal(SIGHUP, SIG_DFL); signal(SIGUSR1, SIG_DFL);
8103 4 signal(SIGUSR2, SIG_DFL); signal(SIGCHLD, SIG_DFL);
8104 4 signal(SIGALRM, SIG_DFL);
8105 9 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 5 4 9
8106 5 const hm_listener_spec *s = &cfg->lspecs[i];
8107 /*
8108 # uncoverable branch false class:ignore_covered_err
8109 # uncoverable condition right count:1 class:ignore_covered_err */
8110 5 ▶ if (s->fd >= 0) (void)fcntl(s->fd, F_SETFD, 0);
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd >= 0) (void)fcntl(s->fd, F_SETFD, 0); 5 0 5
8111 /*
8112 # uncoverable branch true class:ignore_covered_err
8113 # uncoverable condition left count:1 class:ignore_covered_err */
8114 5 ▶ if (s->udp_fd >= 0) (void)fcntl(s->udp_fd, F_SETFD, 0);
Branch: 1 branch
BranchTrueFalseTotal
if (s->udp_fd >= 0) (void)fcntl(s->udp_fd, F_SETFD, 0); 0 5 5
8115 }
8116 4 setenv("HYPERMAN_REEXEC", env, 1);
8117 4 execv(SvPV_nolen(perl), hm_boot_argv);
8118 4 _exit(127); /* # uncoverable statement class:ignore_covered_err */
8119 }
8120 4 hm_resup_pid = pid;
8121 4 hm_errlog("Hyperman: USR2: successor %d started; serving until it takes over",
8122 (int)pid);
8123 }
8124  
8125 /* The successor's half: HYPERMAN_REEXEC names the sockets and the arena.
8126 * Runs after the addresses are resolved and before anything binds. */
8127 105 static void hm_adopt_env(pTHX_ hm_worker_cfg *cfg) {
8128 105 const char *raw = getenv("HYPERMAN_REEXEC");
8129 105 char *buf, *tok, *save = NULL;
8130 int i;
8131 105 ▶ if (!raw || !*raw) return; /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!raw || !*raw) return; /* # uncoverable condition left count:2 class:ignore_covered_err */ 5 100 105
if (!raw || !*raw) return; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 5 5
8132 5 buf = strdup(raw);
8133 /*
8134 # uncoverable branch true
8135 # uncoverable condition left count:1 class:ignore_covered_err */
8136 5 ▶ if (!buf) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!buf) return; 0 5 5
8137 5 hm_env_unset(aTHX_ "HYPERMAN_REEXEC");
8138 11 ▶ for (i = 0; i < cfg->nlspecs; i++) { cfg->lspecs[i].fd = -1; cfg->lspecs[i].udp_fd = -1; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { cfg->lspecs[i].fd = -1; cfg->lspecs[i].udp_fd = -1; } 6 5 11
8139 21 ▶ for (tok = strtok_r(buf, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) {
Branch: 1 branch
BranchTrueFalseTotal
for (tok = strtok_r(buf, ";", &save); tok; tok = strtok_r(NULL, ";", &save)) { 17 4 21
8140 17 ▶ if (strncmp(tok, "sup=", 4) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (strncmp(tok, "sup=", 4) == 0) { 5 12 17
8141 5 hm_resup_old = (pid_t)atol(tok + 4);
8142 12 ▶ } else if (strncmp(tok, "arena=", 6) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (strncmp(tok, "arena=", 6) == 0) { 4 8 12
8143 4 ▶ if (!cfg->arena_name || !cfg->arena_name_len) { /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (!cfg->arena_name || !cfg->arena_name_len) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 2 2 4
if (!cfg->arena_name || !cfg->arena_name_len) { /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 2 2
8144 2 cfg->arena_name = strdup(tok + 6); /* process lifetime */
8145 2 cfg->arena_name_len = strlen(tok + 6);
8146 }
8147 8 ▶ } else if (strncmp(tok, "l=", 2) == 0 || strncmp(tok, "u=", 2) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (strncmp(tok, "l=", 2) == 0 || strncmp(tok, "u=", 2) == 0) { 3 5 8
} else if (strncmp(tok, "l=", 2) == 0 || strncmp(tok, "u=", 2) == 0) { 2 1 3
8148 7 int unix_ = tok[0] == 'u';
8149 7 char *f1, *f2, *f3, *f4, *s2 = NULL;
8150 7 int fd = -1, udp = -1, port = 0, matched = 0;
8151 const char *name;
8152 7 f1 = strtok_r(tok + 2, "|", &s2);
8153 7 f2 = strtok_r(NULL, "|", &s2);
8154 7 f3 = strtok_r(NULL, "|", &s2);
8155 7 f4 = strtok_r(NULL, "|", &s2);
8156 /*
8157 # uncoverable branch true class:ignore_covered_err
8158 # uncoverable condition left count:1 class:ignore_covered_err
8159 # uncoverable condition left count:2 class:ignore_covered_err */
8160 7 ▶ if (!f1 || !f2) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!f1 || !f2) continue; 7 0 7
if (!f1 || !f2) continue; 0 7 7
8161 7 name = f1;
8162 7 ▶ if (unix_) { fd = atoi(f2); }
Branch: 1 branch
BranchTrueFalseTotal
if (unix_) { fd = atoi(f2); } 2 5 7
8163 /*
8164 # uncoverable condition left count:1 class:ignore_covered_err
8165 # uncoverable condition right count:2 class:ignore_covered_err */
8166 5 ▶ else { if (!f3) continue; port = atoi(f2); fd = atoi(f3); udp = f4 ? atoi(f4) : -1; }
Branch: 2 branches
BranchTrueFalseTotal
else { if (!f3) continue; port = atoi(f2); fd = atoi(f3); udp = f4 ? atoi(f4) : -1; } 0 5 5
else { if (!f3) continue; port = atoi(f2); fd = atoi(f3); udp = f4 ? atoi(f4) : -1; } 5 0 5
8167 /* reuseport pools rebind per worker and hold nothing to adopt */
8168 /*
8169 # uncoverable branch false class:ignore_covered_err
8170 # uncoverable condition right count:1 class:ignore_covered_err */
8171 7 ▶ if (!cfg->reuseport) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg->reuseport) { 7 0 7
8172 10 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 8 2 10
8173 8 hm_listener_spec *s = &cfg->lspecs[i];
8174 8 ▶ if (s->fd >= 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd >= 0) continue; 1 7 8
8175 12 ▶ if (unix_ ? (s->path && strcmp(s->path, name) == 0)
Branch: 4 branches
BranchTrueFalseTotal
if (unix_ ? (s->path && strcmp(s->path, name) == 0) 2 5 7
if (unix_ ? (s->path && strcmp(s->path, name) == 0) 1 1 2
if (unix_ ? (s->path && strcmp(s->path, name) == 0) 1 0 1
if (unix_ ? (s->path && strcmp(s->path, name) == 0) 5 2 7
8176 5 ▶ : (!s->path && s->port == port
Branch: 1 branch
BranchTrueFalseTotal
: (!s->path && s->port == port 4 1 5
8177 10 ▶ && strcmp(s->host && *s->host ? s->host : "0.0.0.0", name) == 0)) {
Branch: 4 branches
BranchTrueFalseTotal
&& strcmp(s->host && *s->host ? s->host : "0.0.0.0", name) == 0)) { 5 0 5
&& strcmp(s->host && *s->host ? s->host : "0.0.0.0", name) == 0)) { 4 0 4
&& strcmp(s->host && *s->host ? s->host : "0.0.0.0", name) == 0)) { 4 0 4
&& strcmp(s->host && *s->host ? s->host : "0.0.0.0", name) == 0)) { 4 0 4
8178 struct sockaddr_storage got;
8179 5 socklen_t gl = sizeof(got);
8180 5 int acc = 0;
8181 5 socklen_t al = sizeof(acc);
8182 /*
8183 # uncoverable condition left count:2 class:ignore_covered_err
8184 # uncoverable condition left count:3 class:ignore_covered_err
8185 # uncoverable condition right count:3 class:ignore_covered_err
8186 # uncoverable condition left count:4 class:ignore_covered_err */
8187 5 ▶ if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0
Branch: 1 branch
BranchTrueFalseTotal
if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0 4 1 5
8188 4 ▶ || got.ss_family != s->sa.ss_family
Branch: 1 branch
BranchTrueFalseTotal
|| got.ss_family != s->sa.ss_family 4 0 4
8189 4 ▶ || (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &acc, &al) == 0 && !acc))
Branch: 2 branches
BranchTrueFalseTotal
|| (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &acc, &al) == 0 && !acc)) 4 0 4
|| (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &acc, &al) == 0 && !acc)) 0 4 4
8190 1 croak("Hyperman->run: re-exec: handed fd %d for %s is not "
8191 "the listener it was said to be", fd, name);
8192 4 hm_set_nonblock(fd); /* # uncoverable statement class:ignore_covered_err */
8193 4 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); /* # uncoverable statement class:ignore_covered_err */
8194 4 s->fd = fd; /* # uncoverable statement class:ignore_covered_err */
8195 /*
8196 # uncoverable statement class:ignore_covered_err
8197 # uncoverable branch true
8198 # uncoverable condition left count:1
8199 # uncoverable condition left count:2
8200 # uncoverable condition right count:2 */
8201 4 ▶ if (udp >= 0 && s->http3) {
Branch: 2 branches
BranchTrueFalseTotal
if (udp >= 0 && s->http3) { 0 4 4
if (udp >= 0 && s->http3) { 0 0 0
8202 0 hm_set_nonblock(udp); /* # uncoverable statement */
8203 0 (void)fcntl(udp, F_SETFD, fcntl(udp, F_GETFD, 0) | FD_CLOEXEC); /* # uncoverable statement */
8204 0 s->udp_fd = udp; /* # uncoverable statement */
8205 /*
8206 # uncoverable statement class:ignore_covered_err
8207 # uncoverable branch true
8208 # uncoverable condition left count:1 */
8209 4 ▶ } else if (udp >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (udp >= 0) { 0 4 4
8210 0 hm_os_close(udp); /* # uncoverable statement */
8211 }
8212 4 matched = 1;
8213 4 break;
8214 }
8215 }
8216 }
8217 6 ▶ if (!matched) { /* a listener the new config dropped */
Branch: 1 branch
BranchTrueFalseTotal
if (!matched) { /* a listener the new config dropped */ 2 4 6
8218 /*
8219 # uncoverable branch false class:ignore_covered_err
8220 # uncoverable condition right count:1 class:ignore_covered_err */
8221 2 ▶ if (fd >= 0) hm_os_close(fd);
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) hm_os_close(fd); 2 0 2
8222 /*
8223 # uncoverable branch true class:ignore_covered_err
8224 # uncoverable condition left count:1 class:ignore_covered_err */
8225 2 ▶ if (udp >= 0) hm_os_close(udp);
Branch: 1 branch
BranchTrueFalseTotal
if (udp >= 0) hm_os_close(udp); 0 2 2
8226 }
8227 }
8228 }
8229 4 free(buf);
8230 4 hm_errlog("Hyperman: re-exec successor %d: sockets adopted from supervisor %d",
8231 4 hm_os_getpid(), (int)hm_resup_old);
8232 }
8233  
8234 /* The successor's pool is up: tell the old supervisor to drain. Waited for a
8235 * scoreboard row per child (ten seconds at most), or one second flat when
8236 * there is no board, so the old pool is not torn down ahead of the new one
8237 * answering. */
8238 27 static void hm_reexec_takeover(const pid_t *kids, int nkids) {
8239 int i, tries;
8240 27 ▶ if (hm_resup_old <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_resup_old <= 0) return; 23 4 27
8241 /*
8242 # uncoverable branch false class:ignore_covered_err
8243 # uncoverable condition right count:1 class:ignore_covered_err */
8244 4 ▶ if (hm_sa_board_live()) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_board_live()) { 4 0 4
8245 /*
8246 # uncoverable branch false class:ignore_covered_err
8247 # uncoverable condition right count:1 class:ignore_covered_err */
8248 8 ▶ for (tries = 0; tries < 100; tries++) {
Branch: 1 branch
BranchTrueFalseTotal
for (tries = 0; tries < 100; tries++) { 8 0 8
8249 8 int ready = 1;
8250 18 ▶ for (i = 0; i < nkids; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nkids; i++) { 14 4 18
8251 sa_sb_reading rd;
8252 14 ▶ if (hm_sa_board_row_of((uint64_t)kids[i], &rd) < 0) { ready = 0; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_board_row_of((uint64_t)kids[i], &rd) < 0) { ready = 0; break; } 4 10 14
8253 }
8254 8 ▶ if (ready) break;
Branch: 1 branch
BranchTrueFalseTotal
if (ready) break; 4 4 8
8255 4 poll(NULL, 0, 100);
8256 }
8257 } else {
8258 0 poll(NULL, 0, 1000); /* # uncoverable statement class:ignore_covered_err */
8259 }
8260 /*
8261 # uncoverable branch false class:ignore_covered_err
8262 # uncoverable condition right count:1 class:ignore_covered_err */
8263 4 ▶ if (kill(hm_resup_old, SIGTERM) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (kill(hm_resup_old, SIGTERM) == 0) 4 0 4
8264 4 hm_errlog("Hyperman: re-exec: pool up, supervisor %d asked to drain",
8265 (int)hm_resup_old);
8266 4 hm_resup_old = 0;
8267 }
8268 #endif /* !_WIN32 */
8269  
8270 114 static void hm_run_server(pTHX_ hm_worker_cfg *cfg) {
8271 114 int workers = cfg->nworkers;
8272  
8273 /* Before the arena, before the bind: an unknown user or group is refused
8274 * while nothing is held, and on Windows the whole family is. */
8275 114 hm_resolve_drop(aTHX_ cfg);
8276 #ifndef _WIN32
8277 /* The umask FIRST: it is asked for so that what the server creates - the
8278 * unix socket, the pid file, the logs - comes out with it, and all of
8279 * those are made below. Applied at the drop it reached only the files
8280 * the application made. */
8281 108 ▶ if (cfg->umask_set) (void)umask((mode_t)cfg->umask_val);
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->umask_set) (void)umask((mode_t)cfg->umask_val); 1 107 108
8282 #endif
8283 /* Likewise every listen address: a host that does not resolve is a
8284 * croak here, never a bind of INADDR_ANY in its place. */
8285 {
8286 int i;
8287 char err[128];
8288 221 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 116 105 221
8289 116 hm_listener_spec *s = &cfg->lspecs[i];
8290 116 s->fd = -1; /* calloc'd, and 0 is a descriptor */
8291 116 s->udp_fd = -1;
8292 116 ▶ if (s->path) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) { 8 108 116
8293 8 ▶ if (cfg->reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) 1 7 8
8294 1 croak("Hyperman->run: reuseport cannot rebind a path listener "
8295 "per worker (each rebind would unlink the other's socket)");
8296 7 ▶ if (hm_resolve_unix(s->path, &s->sa, &s->salen, err, sizeof(err)) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (hm_resolve_unix(s->path, &s->sa, &s->salen, err, sizeof(err)) < 0) 1 6 7
8297 1 croak("Hyperman->run: listen path '%s': %s", s->path, err);
8298 }
8299 108 ▶ else if (hm_resolve(s->host, s->port, SOCK_STREAM, &s->sa, &s->salen,
Branch: 1 branch
BranchTrueFalseTotal
else if (hm_resolve(s->host, s->port, SOCK_STREAM, &s->sa, &s->salen, 1 107 108
8300 err, sizeof(err)) < 0)
8301 1 ▶ croak("Hyperman->run: listen host '%s': %s",
Branch: 1 branch
BranchTrueFalseTotal
croak("Hyperman->run: listen host '%s': %s", 1 0 1
8302 s->host ? s->host : "", err); /* # uncoverable condition right count:1 class:ignore_covered_err */
8303 }
8304 }
8305 #ifndef _WIN32
8306 105 hm_adopt_env(aTHX_ cfg); /* a re-exec successor: the old sockets */
8307 #endif
8308 104 hm_adopt_fds(aTHX_ cfg);
8309  
8310 96 ▶ if (!hm_empty_input)
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_empty_input) 83 13 96
8311 83 hm_empty_input = hm_new_input(aTHX_ "", 0); /* inherited by workers */
8312 96 ▶ if (workers < 1) /* default: one per CPU */
Branch: 1 branch
BranchTrueFalseTotal
if (workers < 1) /* default: one per CPU */ 13 83 96
8313 13 workers = hm_os_ncpu(); /* always 1 on Windows */
8314 96 cfg->nworkers = workers;
8315  
8316 /* The Shared::Arena, created HERE - before any worker forks - so every
8317 * worker inherits the one mapping, and from Perl, so Hyperman->arena is
8318 * the real object with every tenant on it. The denylist and the rate
8319 * counters are two maps in it; static `deny` entries are loaded now, in
8320 * the parent, so they are live from the first accepted connection.
8321 * Single-worker (dev) mode maps it too, so the ABI behaves the same
8322 * whether or not a supervisor forks. */
8323 96 hm_sa_open(aTHX_ cfg->arena_name, cfg->arena_name_len,
8324 96 ▶ cfg->arena_size ? cfg->arena_size
Branch: 1 branch
BranchTrueFalseTotal
cfg->arena_size ? cfg->arena_size 2 94 96
8325 94 : hm_sa_bytes(cfg->deny_cap, cfg->rate_cap,
8326 cfg->bus_slots, cfg->bus_slot_size));
8327 {
8328 96 const char *which = NULL;
8329 96 int err = 0;
8330 96 ▶ if (hm_sa_abuse_open(cfg->deny_cap, cfg->rate_cap, &which, &err) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_abuse_open(cfg->deny_cap, cfg->rate_cap, &which, &err) < 0) 2 94 96
8331 2 warn("Hyperman: could not carve the \"%s\" map in the arena "
8332 "(Shared::Arena error %d): the denylist and the rate "
8333 "counters fail open; raise arena_size", which, err);
8334 }
8335  
8336 /* QUIC's stateless-reset and (later) Retry secret, generated HERE - once,
8337 * before any worker forks - for the same reason the TLS ticket key is:
8338 * under SO_REUSEPORT a client's token can land on a different worker than
8339 * the one that issued it, and a per-worker secret would make every such
8340 * token unverifiable. Inherited across the fork, so every worker agrees. */
8341 96 hm_quic_secret_init();
8342  
8343 /* The message bus, a ring in the same arena and for the same reason: a
8344 * ring created after the fork would be one ring per worker, which is a
8345 * bus that delivers to nobody. Opened even in single-worker mode, so the
8346 * ABI behaves the same whether or not a supervisor forks. */
8347 {
8348 96 int err = 0;
8349 96 ▶ if (hm_sa_bus_open(cfg->bus_slots, cfg->bus_slot_size, &err) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_bus_open(cfg->bus_slots, cfg->bus_slot_size, &err) < 0) 2 94 96
8350 2 warn("Hyperman: could not carve the bus ring in the arena "
8351 "(Shared::Arena error %d): the bus is local-only; raise "
8352 "arena_size", err);
8353 }
8354 /* ... and the wakeup descriptors, HERE for the same reason as the ring
8355 * and one more: a pipe created inside a worker is invisible to its
8356 * siblings, so a bus built after the fork delivers to some workers and
8357 * not others.
8358 *
8359 * TWO GENERATIONS' WORTH, plus the supervisor's own. A HUP or USR2 forks
8360 * the replacement pool while the old one is still draining, so both exist
8361 * at once and both want descriptors - and sized for one generation the
8362 * fresh workers found every slot held and came up deaf, which outlives the
8363 * recycle that caused it. Shared::Arena caps this at its own ceiling. */
8364 96 ▶ (void)hm_sa_bus_wake_init((uint32_t)(workers > 0 ? 2 * workers + 1 : 2)); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
(void)hm_sa_bus_wake_init((uint32_t)(workers > 0 ? 2 * workers + 1 : 2)); /* # uncoverable condition right count:1 class:ignore_covered_err */ 96 0 96
8365 /* The worker scoreboard, one row per worker plus one, and the
8366 * distinct-client sketch when asked for. Neither is on a hot path by
8367 * default: the board is mirrored by a timer, the sketch is opt-in. */
8368 {
8369 96 int err = 0;
8370 /* Two generations' worth, like the wakers: a re-exec successor's
8371 * pool shares this board with the pool it replaces until that one
8372 * has drained, and a row is not reclaimable while its worker lives. */
8373 /*
8374 # uncoverable branch true class:ignore_covered_err
8375 # uncoverable condition right count:1 class:ignore_covered_err
8376 # uncoverable condition left count:2 class:ignore_covered_err */
8377 96 ▶ if (hm_sa_board_open((uint32_t)(workers > 0 ? 2 * workers + 2 : 2), &err) < 0)
Branch: 2 branches
BranchTrueFalseTotal
if (hm_sa_board_open((uint32_t)(workers > 0 ? 2 * workers + 2 : 2), &err) < 0) 96 0 96
if (hm_sa_board_open((uint32_t)(workers > 0 ? 2 * workers + 2 : 2), &err) < 0) 0 96 96
8378 0 warn("Hyperman: could not carve the worker scoreboard in the arena " /* # uncoverable statement class:ignore_covered_err */
8379 "(Shared::Arena error %d): pool_stats is empty; raise "
8380 "arena_size", err);
8381 /*
8382 # uncoverable branch true class:ignore_covered_err
8383 # uncoverable condition left count:1 class:ignore_covered_err
8384 # uncoverable condition left count:2 class:ignore_covered_err */
8385 96 ▶ if (cfg->distinct_clients && hm_sa_hll_open(&err) < 0)
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->distinct_clients && hm_sa_hll_open(&err) < 0) 2 94 96
if (cfg->distinct_clients && hm_sa_hll_open(&err) < 0) 0 2 2
8386 0 warn("Hyperman: could not carve the distinct-client sketch in the " /* # uncoverable statement */
8387 "arena (Shared::Arena error %d): distinct_clients is off", err); /* # uncoverable statement */
8388 }
8389 /*
8390 # uncoverable condition right count:2 class:ignore_covered_err
8391 # uncoverable condition right count:3 class:ignore_covered_err */
8392 96 ▶ if (cfg->deny && SvROK(cfg->deny) && SvTYPE(SvRV(cfg->deny)) == SVt_PVAV) {
Branch: 3 branches
BranchTrueFalseTotal
if (cfg->deny && SvROK(cfg->deny) && SvTYPE(SvRV(cfg->deny)) == SVt_PVAV) { 3 93 96
if (cfg->deny && SvROK(cfg->deny) && SvTYPE(SvRV(cfg->deny)) == SVt_PVAV) { 3 0 3
if (cfg->deny && SvROK(cfg->deny) && SvTYPE(SvRV(cfg->deny)) == SVt_PVAV) { 3 0 3
8393 3 AV *av = (AV *)SvRV(cfg->deny);
8394 3 SSize_t i, n = av_len(av) + 1;
8395 6 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 3 3 6
8396 3 SV **e = av_fetch(av, i, 0);
8397 /*
8398 # uncoverable branch false class:ignore_covered_err
8399 # uncoverable condition right count:1 class:ignore_covered_err
8400 # uncoverable condition right count:2 class:ignore_covered_err
8401 # uncoverable condition right count:3 class:ignore_covered_err */
8402 6 ▶ if (e && *e && SvOK(*e)) hm_sa_deny_add(SvPV_nolen(*e), 0);
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) hm_sa_deny_add(SvPV_nolen(*e), 0); 3 0 3
if (e && *e && SvOK(*e)) hm_sa_deny_add(SvPV_nolen(*e), 0); 3 0 3
if (e && *e && SvOK(*e)) hm_sa_deny_add(SvPV_nolen(*e), 0); 3 0 3
8403 }
8404 }
8405  
8406 #ifndef SO_REUSEPORT
8407 if (cfg->reuseport) croak("Hyperman: SO_REUSEPORT not supported on this platform");
8408 #endif
8409 #ifndef __linux__
8410 if (cfg->affinity) croak("Hyperman: CPU affinity is Linux-only");
8411 #endif
8412  
8413 /* Per listener: build the TLS context before forking, so a bad cert/key
8414 * fails fast and the (read-only) SSL_CTX is shared copy-on-write across
8415 * workers. Then bind - in the parent, unless reuseport (each worker binds
8416 * its own). Under reuseport the parent still binds one probe fd so an
8417 * unusable address (e.g. a privileged port without root) fails fast. */
8418 {
8419 int i;
8420 197 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 104 93 197
8421 104 hm_listener_spec *s = &cfg->lspecs[i];
8422 104 ▶ if (s->tls_cert && s->tls_key) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (s->tls_cert && s->tls_key) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 93 104
if (s->tls_cert && s->tls_key) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 0 11
8423 11 s->tls_ctx = hm_tls_ctx_build(aTHX_ s->tls_cert, s->tls_key,
8424 s->tls_ca, s->tls_verify,
8425 s->tls_sni, s->http2, NULL, 0);
8426 11 ▶ if (!s->tls_ctx)
Branch: 1 branch
BranchTrueFalseTotal
if (!s->tls_ctx) 3 8 11
8427 3 croak("Hyperman: TLS: could not initialise from cert '%s' "
8428 "/ key '%s'", s->tls_cert, s->tls_key);
8429 }
8430 }
8431 }
8432  
8433 /* The access-log format, compiled once here so an unknown directive is a
8434 * croak before the fork and a line is a walk over an array after it. The
8435 * tokens are process-lifetime: every worker reads the parent's copy. */
8436 93 ▶ if (cfg->log_format && strcmp(cfg->log_format, "json") == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->log_format && strcmp(cfg->log_format, "json") == 0) { 9 84 93
if (cfg->log_format && strcmp(cfg->log_format, "json") == 0) { 3 6 9
8437 3 hm_logfmt_json(aTHX_ &cfg->logtok, &cfg->nlogtok);
8438 3 cfg->log_json = 1;
8439 3 cfg->log_wants_t0 = 1;
8440 } else {
8441 char err[64];
8442 90 ▶ if (hm_logfmt_compile(aTHX_ cfg->log_format ? cfg->log_format : HM_LOG_COMBINED,
Branch: 2 branches
BranchTrueFalseTotal
if (hm_logfmt_compile(aTHX_ cfg->log_format ? cfg->log_format : HM_LOG_COMBINED, 6 84 90
if (hm_logfmt_compile(aTHX_ cfg->log_format ? cfg->log_format : HM_LOG_COMBINED, 4 86 90
8443 &cfg->logtok, &cfg->nlogtok, &cfg->log_wants_t0,
8444 err, sizeof(err)) < 0)
8445 4 croak("Hyperman->run: access_log_format: unknown directive %s", err);
8446 }
8447 /* The error log, likewise opened once and inherited. */
8448 89 ▶ if (cfg->err_path && cfg->err_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->err_path && cfg->err_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 78 89
if (cfg->err_path && cfg->err_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 0 11
8449 11 cfg->err_fd = hm_os_open_file(cfg->err_path,
8450 O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
8451 11 ▶ if (cfg->err_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->err_fd < 0) 1 10 11
8452 1 croak("Hyperman: open error_log '%s': %s", cfg->err_path, strerror(errno));
8453 }
8454 88 ▶ if (cfg->err_fd >= 0) hm_err_fd = cfg->err_fd;
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->err_fd >= 0) hm_err_fd = cfg->err_fd; 11 77 88
8455  
8456 /* Open the access-log file once in the parent so all workers share (and
8457 * O_APPEND to) the same fd - whole-line writes stay atomic between them. */
8458 88 ▶ if (cfg->log_path && cfg->log_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->log_path && cfg->log_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 80 88
if (cfg->log_path && cfg->log_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 0 8
8459 8 cfg->log_fd = hm_os_open_file(cfg->log_path,
8460 O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
8461 8 ▶ if (cfg->log_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->log_fd < 0) 1 7 8
8462 1 croak("Hyperman: open access_log '%s': %s",
8463 cfg->log_path, strerror(errno));
8464 }
8465  
8466 /* Under reuseport the workers rebind their ports themselves, which
8467 * needs the privilege for a port below 1024 that a dropped user no
8468 * longer has; that pairing is refused rather than half-honoured, and
8469 * refused here, before any bind, so it is the error a caller sees even
8470 * where this process could not bind the low port either. */
8471 87 ▶ if (cfg->reuseport && cfg->drop_uid_set) {
Branch: 2 branches
BranchTrueFalseTotal
if (cfg->reuseport && cfg->drop_uid_set) { 4 83 87
if (cfg->reuseport && cfg->drop_uid_set) { 3 1 4
8472 int i;
8473 /*
8474 # uncoverable branch false
8475 # uncoverable condition right count:1 class:ignore_covered_err */
8476 3 ▶ for (i = 0; i < cfg->nlspecs; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) 3 0 3
8477 /*
8478 # uncoverable branch false
8479 # uncoverable condition right count:1 class:ignore_covered_err */
8480 3 ▶ if (cfg->lspecs[i].port < 1024)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->lspecs[i].port < 1024) 3 0 3
8481 3 croak("Hyperman->run: user => with reuseport => 1 cannot rebind "
8482 "port %d as the dropped user; drop reuseport or use a "
8483 "port above 1023", cfg->lspecs[i].port);
8484 }
8485  
8486 {
8487 int i;
8488 174 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 92 82 174
8489 92 hm_listener_spec *s = &cfg->lspecs[i];
8490 92 ▶ if (s->fd >= 0) continue; /* adopted from LISTEN_FDS */
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd >= 0) continue; /* adopted from LISTEN_FDS */ 6 86 92
8491 #ifndef _WIN32
8492 /* `mode` through the umask around the bind, not a chmod of the
8493 * path afterwards: in a directory others can write to, the path
8494 * could be swapped for a symlink between the two and root would
8495 * chmod whatever it pointed at. A bind creates the socket with
8496 * 0777 less the umask, so the mask is the mode's complement. */
8497 86 mode_t saved_umask = 0;
8498 86 int have_saved = 0;
8499 86 ▶ if (s->path && s->mode_set) {
Branch: 2 branches
BranchTrueFalseTotal
if (s->path && s->mode_set) { 3 83 86
if (s->path && s->mode_set) { 1 2 3
8500 1 saved_umask = umask((mode_t)(~(unsigned)s->mode & 0777u));
8501 1 have_saved = 1;
8502 }
8503 #endif
8504 86 s->fd = hm_make_listener((struct sockaddr *)&s->sa, s->salen, cfg->reuseport);
8505 #ifndef _WIN32
8506 86 ▶ if (have_saved) (void)umask(saved_umask);
Branch: 1 branch
BranchTrueFalseTotal
if (have_saved) (void)umask(saved_umask); 1 85 86
8507 #endif
8508 86 ▶ if (s->fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd < 0) 2 84 86
8509 2 ▶ croak("Hyperman: bind %s%s:%d: %s", s->path ? s->path : "",
Branch: 2 branches
BranchTrueFalseTotal
croak("Hyperman: bind %s%s:%d: %s", s->path ? s->path : "", 1 1 2
croak("Hyperman: bind %s%s:%d: %s", s->path ? s->path : "", 1 1 2
8510 s->path ? "" : s->host, s->port, strerror(errno));
8511 84 s->udp_fd = -1;
8512 /*
8513 # uncoverable branch true class:ignore_covered_err
8514 # uncoverable condition left count:1 class:ignore_covered_err */
8515 84 ▶ if (s->http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) { 0 84 84
8516 0 s->udp_fd = hm_make_udp_listener((struct sockaddr *)&s->sa, s->salen, cfg->reuseport); /* # uncoverable statement class:ignore_covered_err */
8517 /*
8518 # uncoverable branch true class:ignore_covered_err
8519 # uncoverable statement class:ignore_covered_err
8520 # uncoverable branch false class:ignore_covered_err
8521 # uncoverable condition left count:1 class:ignore_covered_err
8522 # uncoverable condition right count:1 class:ignore_covered_err */
8523 0 ▶ if (s->udp_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->udp_fd < 0) 0 0 0
8524 0 croak("Hyperman: bind udp %s:%d: %s", s->host, s->port, /* # uncoverable statement */
8525 strerror(errno)); /* # uncoverable statement */
8526 }
8527 84 ▶ if (cfg->reuseport) { /* probe only */
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) { /* probe only */ 1 83 84
8528 1 hm_os_close(s->fd); s->fd = -1;
8529 /*
8530 # uncoverable branch true class:ignore_covered_err
8531 # uncoverable condition left count:1 class:ignore_covered_err */
8532 1 ▶ if (s->udp_fd >= 0) { hm_os_close(s->udp_fd); s->udp_fd = -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (s->udp_fd >= 0) { hm_os_close(s->udp_fd); s->udp_fd = -1; } 0 1 1
8533 }
8534 }
8535 }
8536  
8537 /* Everything that needed root is held: the ports, the logs, the arena.
8538 * Record who we are, then stop being root, before the first fork so
8539 * every worker is born as the configured user. */
8540 82 hm_write_pidfile(aTHX_ cfg);
8541 77 hm_drop_privileges(aTHX_ cfg);
8542  
8543 77 ▶ if (workers == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (workers == 1) { 50 27 77
8544 /* dev mode: run the worker in this process, no supervisor. reuseport
8545 * needs a real bound fd here since there is no per-worker rebind. */
8546 /*
8547 # uncoverable branch true class:ignore_covered_err
8548 # uncoverable condition left count:1 class:ignore_covered_err */
8549 50 ▶ if (cfg->reuseport) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) { 0 50 50
8550 int i;
8551 /*
8552 # uncoverable statement
8553 # uncoverable branch true
8554 # uncoverable branch false
8555 # uncoverable condition left count:1
8556 # uncoverable condition right count:1 */
8557 0 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 0 0 0
8558 0 hm_listener_spec *s = &cfg->lspecs[i]; /* # uncoverable statement */
8559 0 s->fd = hm_make_listener((struct sockaddr *)&s->sa, s->salen, 1); /* # uncoverable statement */
8560 /*
8561 # uncoverable statement
8562 # uncoverable branch true
8563 # uncoverable branch false
8564 # uncoverable condition left count:1
8565 # uncoverable condition right count:1 */
8566 0 ▶ if (s->fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd < 0) 0 0 0
8567 0 croak("Hyperman: bind %s:%d: %s", s->host, s->port, /* # uncoverable statement */
8568 strerror(errno)); /* # uncoverable statement */
8569 /*
8570 # uncoverable statement
8571 # uncoverable branch true
8572 # uncoverable branch false
8573 # uncoverable condition left count:1
8574 # uncoverable condition right count:1 */
8575 0 ▶ if (s->http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) { 0 0 0
8576 0 s->udp_fd = hm_make_udp_listener((struct sockaddr *)&s->sa, s->salen, 1); /* # uncoverable statement */
8577 /*
8578 # uncoverable statement
8579 # uncoverable branch true
8580 # uncoverable branch false
8581 # uncoverable condition left count:1
8582 # uncoverable condition right count:1 */
8583 0 ▶ if (s->udp_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->udp_fd < 0) 0 0 0
8584 0 croak("Hyperman: bind udp %s:%d: %s", s->host, s->port, /* # uncoverable statement */
8585 strerror(errno)); /* # uncoverable statement */
8586 }
8587 }
8588 }
8589 50 hm_worker(aTHX_ cfg, NULL);
8590 50 hm_unlink_pidfile(cfg->pid_path);
8591 50 return;
8592 }
8593  
8594 #ifdef _WIN32
8595 /* Not a silent downgrade: an application sized for a pool is told, at
8596 * boot, in the log it already reads. */
8597 croak("Hyperman: a worker pool needs fork(2); Windows runs a single "
8598 "worker (workers => 1).");
8599 #else
8600 {
8601 int i;
8602 27 int backoff = 0;
8603 struct sigaction sa;
8604  
8605 93 ▶ for (i = 0; i < workers; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < workers; i++) { 66 27 93
8606 66 pid_t pid = hm_spawn(aTHX_ cfg, i);
8607 /*
8608 # uncoverable branch true
8609 # uncoverable condition left count:1 class:ignore_covered_err */
8610 66 ▶ if (pid < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid < 0) { 0 66 66
8611 /* take the pool down with us: croaking out of run() leaves
8612 * nobody supervising the workers already forked, and they
8613 * would keep the listening socket alive forever. */
8614 int j;
8615 /*
8616 # uncoverable statement
8617 # uncoverable branch true
8618 # uncoverable branch false
8619 # uncoverable condition left count:1
8620 # uncoverable condition right count:1 */
8621 0 ▶ for (j = 0; j < hm_nchildren; j++) kill(hm_children[j], SIGTERM);
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < hm_nchildren; j++) kill(hm_children[j], SIGTERM); 0 0 0
8622 0 croak("Hyperman: fork: %s", strerror(errno)); /* # uncoverable statement */
8623 }
8624 66 hm_child_start[hm_nchildren] = time(NULL);
8625 66 hm_child_widx[hm_nchildren] = i;
8626 66 hm_children[hm_nchildren++] = pid;
8627 }
8628  
8629 27 memset(&sa, 0, sizeof(sa));
8630 27 sa.sa_handler = hm_sup_sig; /* no SA_RESTART: waitpid must EINTR */
8631 27 sigemptyset(&sa.sa_mask);
8632 27 sigaction(SIGTERM, &sa, NULL);
8633 27 sigaction(SIGINT, &sa, NULL);
8634 27 sigaction(SIGHUP, &sa, NULL);
8635 27 sigaction(SIGUSR1, &sa, NULL);
8636 27 sigaction(SIGUSR2, &sa, NULL);
8637 /* SIGCHLD must be delivered so sigsuspend() below wakes when a worker
8638 * exits; hm_sup_sig() treats it as a no-op wakeup. */
8639 27 sigaction(SIGCHLD, &sa, NULL);
8640 /* ALRM is the supervisor's only clock: a look at the scoreboard every
8641 * few seconds for a worker that is alive and not moving.
8642 *
8643 * An alarm the CALLER already had pending is not ours to cancel. A
8644 * watchdog that says `alarm(120); $server->run` has asked to be killed
8645 * at that deadline, and taking SIGALRM over - a handler that only sets
8646 * a flag, re-armed every tick - silently turns that into a promise
8647 * nothing keeps, leaving an unsupervised pool running for ever.
8648 *
8649 * So the pending deadline is read out and carried on the tick, which
8650 * is armed for it even with no board to watch. Letting the signal
8651 * through unhandled instead would kill the supervisor where it stood
8652 * and leave the workers holding the listening socket with nobody to
8653 * shut them down - a watchdog that takes half the pool with it is not
8654 * one. The tick is three seconds, so the deadline is met to within
8655 * that, and what follows is the death the caller asked for. */
8656 27 hm_sup_alarm_at = 0;
8657 {
8658 27 unsigned pending = alarm(0);
8659 27 ▶ if (pending) hm_sup_alarm_at = time(NULL) + (time_t)pending;
Branch: 1 branch
BranchTrueFalseTotal
if (pending) hm_sup_alarm_at = time(NULL) + (time_t)pending; 22 5 27
8660 /*
8661 # uncoverable branch false class:ignore_covered_err
8662 # uncoverable condition right count:1 class:ignore_covered_err
8663 # uncoverable condition right count:2 class:ignore_covered_err */
8664 27 ▶ if (hm_sa_board_live() || hm_sup_alarm_at) {
Branch: 2 branches
BranchTrueFalseTotal
if (hm_sa_board_live() || hm_sup_alarm_at) { 1 26 27
if (hm_sa_board_live() || hm_sup_alarm_at) { 1 0 1
8665 27 sigaction(SIGALRM, &sa, NULL);
8666 27 alarm(HM_SUP_TICK_SECS);
8667 }
8668 }
8669  
8670 /* A successor: the pool is forked and serving on the adopted sockets;
8671 * the supervisor that handed them over can drain now. AFTER the
8672 * handlers above: this waits up to ten seconds, and the pid file
8673 * already names this process, so a deploy script retrying its
8674 * `kill -USR2 $(cat pidfile)` into that window hit SIG_DFL and
8675 * killed the successor, orphaning its workers on the sockets. */
8676 27 hm_reexec_takeover(hm_children, hm_nchildren);
8677  
8678 /* Race-free supervision: keep the acted-on signals blocked, check the
8679 * flags, reap without blocking, then sigsuspend() to wait for the next
8680 * signal atomically. A plain blocking waitpid() has a lost-wakeup
8681 * window - a signal arriving between a flag check and re-entering
8682 * waitpid() goes unserviced until some child happens to exit, which
8683 * for USR1 (stats dump) on an otherwise idle pool could be never. */
8684 {
8685 sigset_t block, orig;
8686 27 sigemptyset(&block);
8687 27 sigaddset(&block, SIGTERM); sigaddset(&block, SIGINT);
8688 27 sigaddset(&block, SIGHUP); sigaddset(&block, SIGUSR1);
8689 27 sigaddset(&block, SIGUSR2); sigaddset(&block, SIGCHLD);
8690 27 sigaddset(&block, SIGALRM);
8691 27 sigprocmask(SIG_BLOCK, &block, &orig);
8692  
8693 57 for (;;) {
8694 int st;
8695 pid_t pid;
8696  
8697 84 ▶ if (hm_sup_term) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_term) { 27 57 84
8698 93 ▶ for (i = 0; i < hm_nchildren; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) 66 27 93
8699 66 kill(hm_children[i], SIGTERM);
8700 /* workers self-bound their drain with shutdown_grace.
8701 * Waited for BY PID: a re-exec successor is a child of
8702 * this process too, and it does not exit - it is the
8703 * one that asked us to; waitpid(-1) would wait for it
8704 * for ever. */
8705 93 ▶ for (i = 0; i < hm_nchildren; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) { 66 27 93
8706 /*
8707 # uncoverable branch true class:ignore_covered_err
8708 # uncoverable condition left count:1 class:ignore_covered_err
8709 # uncoverable condition left count:2 class:ignore_covered_err
8710 # uncoverable condition right count:2 class:ignore_covered_err */
8711 66 ▶ while (waitpid(hm_children[i], &st, 0) < 0 && errno == EINTR) { }
Branch: 2 branches
BranchTrueFalseTotal
while (waitpid(hm_children[i], &st, 0) < 0 && errno == EINTR) { } 0 66 66
while (waitpid(hm_children[i], &st, 0) < 0 && errno == EINTR) { } 0 0 0
8712 }
8713 27 break;
8714 }
8715  
8716 57 ▶ if (hm_sup_usr1) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_usr1) { 5 52 57
8717 5 hm_sup_usr1 = 0;
8718 /* With a scoreboard the supervisor has every worker's
8719 * numbers already: one aggregate line and one per row,
8720 * a dead row marked. Without one, each worker prints its
8721 * own line as it always did. */
8722 5 ▶ if (hm_sa_board_live()) hm_sa_board_print(stderr);
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_board_live()) hm_sa_board_print(stderr); 4 1 5
8723 else
8724 3 ▶ for (i = 0; i < hm_nchildren; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) 2 1 3
8725 2 kill(hm_children[i], SIGUSR1);
8726 }
8727  
8728 57 ▶ if (hm_sup_tick) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_tick) { 2 55 57
8729 2 hm_sup_tick = 0;
8730 /* The caller's own deadline, if it had one: take the pool
8731 * down and then let SIGALRM do what it would have done. */
8732 /*
8733 # uncoverable branch true class:ignore_covered_err
8734 # uncoverable condition left count:1 class:ignore_covered_err
8735 # uncoverable condition right count:1 class:ignore_covered_err
8736 # uncoverable condition left count:2 class:ignore_covered_err */
8737 2 ▶ if (hm_sup_alarm_at && time(NULL) >= hm_sup_alarm_at) {
Branch: 2 branches
BranchTrueFalseTotal
if (hm_sup_alarm_at && time(NULL) >= hm_sup_alarm_at) { 2 0 2
if (hm_sup_alarm_at && time(NULL) >= hm_sup_alarm_at) { 0 2 2
8738 0 hm_sup_alarmed = 1; /* # uncoverable statement */
8739 0 hm_sup_term = 1; /* # uncoverable statement */
8740 2 continue; /* # uncoverable statement class:ignore_covered_err */
8741 }
8742 2 hm_sup_watch_board();
8743 2 alarm(HM_SUP_TICK_SECS);
8744 }
8745  
8746 57 ▶ if (hm_sup_usr2) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_usr2) { 5 52 57
8747 5 hm_sup_usr2 = 0;
8748 5 hm_reexec(aTHX_ cfg, &orig);
8749 }
8750  
8751 57 ▶ if (hm_sup_hup) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_hup) { 2 55 57
8752 pid_t old[1024];
8753 time_t old_start[1024];
8754 int old_widx[1024];
8755 2 int nold = hm_nchildren, nfresh = 0;
8756 2 memcpy(old, hm_children, nold * sizeof(pid_t));
8757 2 memcpy(old_start, hm_child_start, nold * sizeof(time_t));
8758 2 memcpy(old_widx, hm_child_widx, nold * sizeof(int));
8759 2 hm_sup_hup = 0;
8760 2 hm_nchildren = 0;
8761 6 ▶ for (i = 0; i < workers; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < workers; i++) { 4 2 6
8762 /* a failed fork must never reach hm_children: -1 there
8763 * turns the TERM sweep below into kill(-1, SIGTERM),
8764 * which signals every process this uid owns. */
8765 4 pid_t pid = hm_spawn(aTHX_ cfg, i);
8766 /*
8767 # uncoverable branch true
8768 # uncoverable condition left count:1 class:ignore_covered_err */
8769 4 ▶ if (pid < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (pid < 0) continue; 0 4 4
8770 4 hm_child_start[hm_nchildren] = time(NULL);
8771 4 hm_child_widx[hm_nchildren] = i;
8772 4 hm_children[hm_nchildren++] = pid;
8773 4 nfresh++;
8774 }
8775 /* retire one old worker per fresh one. Short of processes
8776 * the survivors stay in the live set, so a HUP under fork
8777 * pressure shrinks the pool instead of emptying it. */
8778 6 ▶ for (i = 0; i < nold; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nold; i++) { 4 2 6
8779 /*
8780 # uncoverable branch false
8781 # uncoverable condition right count:1 class:ignore_covered_err */
8782 4 ▶ if (i < nfresh) {
Branch: 1 branch
BranchTrueFalseTotal
if (i < nfresh) { 4 0 4
8783 4 kill(old[i], SIGTERM); /* drain gracefully */
8784 } else {
8785 0 hm_child_start[hm_nchildren] = old_start[i]; /* # uncoverable statement */
8786 0 hm_child_widx[hm_nchildren] = old_widx[i]; /* # uncoverable statement */
8787 0 hm_children[hm_nchildren++] = old[i]; /* # uncoverable statement */
8788 }
8789 }
8790 }
8791  
8792 /* reap every exited child without blocking, respawning the
8793 * live set. Recycled workers exiting are expected; only a
8794 * death in the live set is respawned. Abnormal quick deaths
8795 * (crash loops) back off exponentially; clean exits respawn
8796 * immediately. */
8797 72 ▶ while ((pid = waitpid(-1, &st, WNOHANG)) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
while ((pid = waitpid(-1, &st, WNOHANG)) > 0) { 17 55 72
8798 17 int live = 0;
8799 17 int dead_widx = 0;
8800 17 time_t started = 0;
8801 17 ▶ if (pid == hm_resup_pid) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid == hm_resup_pid) { 1 16 17
8802 /* It never took over (a successor that did would have
8803 * TERMed us first). Nothing here changed, so nothing
8804 * is undone: this pool serves on. Except the pid
8805 * file, which it may have written before it died,
8806 * and which would then name a dead process for the
8807 * next `kill -USR2 $(cat pidfile)`: re-asserted. */
8808 1 hm_errlog("Hyperman: re-exec successor %d exited (%s %d) "
8809 "before taking over; still serving", (int)pid,
8810 1 ▶ WIFEXITED(st) ? "status" : "signal", /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
WIFEXITED(st) ? "status" : "signal", /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 0 1
8811 1 ▶ WIFEXITED(st) ? WEXITSTATUS(st) : WTERMSIG(st)); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
WIFEXITED(st) ? WEXITSTATUS(st) : WTERMSIG(st)); /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 0 1
8812 1 hm_resup_pid = 0;
8813 1 (void)hm_write_pidfile_(aTHX_ cfg, 0);
8814 1 continue;
8815 }
8816 28 ▶ for (i = 0; i < hm_nchildren; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) { 24 4 28
8817 24 ▶ if (hm_children[i] == pid) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_children[i] == pid) { 12 12 24
8818 12 started = hm_child_start[i];
8819 12 dead_widx = hm_child_widx[i];
8820 12 hm_nchildren--;
8821 12 hm_children[i] = hm_children[hm_nchildren];
8822 12 hm_child_start[i] = hm_child_start[hm_nchildren];
8823 12 hm_child_widx[i] = hm_child_widx[hm_nchildren];
8824 12 live = 1;
8825 12 break;
8826 }
8827 }
8828 16 ▶ if (!live) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!live) continue; 4 12 16
8829  
8830 {
8831 12 ▶ int crashed = !(WIFEXITED(st) && WEXITSTATUS(st) == 0); /* # uncoverable condition left count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
int crashed = !(WIFEXITED(st) && WEXITSTATUS(st) == 0); /* # uncoverable condition left count:2 class:ignore_covered_err */ 8 4 12
int crashed = !(WIFEXITED(st) && WEXITSTATUS(st) == 0); /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 8 8
8832 12 ▶ if (crashed && time(NULL) - started < 5) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (crashed && time(NULL) - started < 5) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 8 12
if (crashed && time(NULL) - started < 5) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 4 0 4
8833 4 ▶ backoff = backoff ? backoff * 2 : 1; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
backoff = backoff ? backoff * 2 : 1; /* # uncoverable condition left count:1 class:ignore_covered_err */ 0 4 4
8834 /*
8835 # uncoverable branch true class:ignore_covered_err
8836 # uncoverable condition left count:1 class:ignore_covered_err */
8837 4 ▶ if (backoff > 30) backoff = 30;
Branch: 1 branch
BranchTrueFalseTotal
if (backoff > 30) backoff = 30; 0 4 4
8838 /* keep TERM responsive during crash-loop backoff */
8839 4 sigprocmask(SIG_SETMASK, &orig, NULL);
8840 4 sleep((unsigned)backoff);
8841 4 sigprocmask(SIG_BLOCK, &block, NULL);
8842 /*
8843 # uncoverable branch false class:ignore_covered_err
8844 # uncoverable condition right count:1 class:ignore_covered_err
8845 # uncoverable condition left count:2 class:ignore_covered_err
8846 # uncoverable condition right count:2 class:ignore_covered_err */
8847 8 ▶ } else if (!crashed || time(NULL) - started >= 5) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (!crashed || time(NULL) - started >= 5) { 0 8 8
} else if (!crashed || time(NULL) - started >= 5) { 0 0 0
8848 8 backoff = 0;
8849 }
8850 }
8851 {
8852 /* The replacement takes the DEAD worker's index, not
8853 * the position it is about to occupy here.
8854 *
8855 * Those are different numbers, because the array above
8856 * is kept packed by swapping the last entry down: kill
8857 * the worker at position 0 of three and the survivor
8858 * from position 2 moves into it, so the next free
8859 * position is 2 - an index a LIVE worker still holds.
8860 * Spawned with that, the replacement asked for a waker
8861 * slot its own sibling owned, was refused, and ran
8862 * deaf to the bus for the rest of its life while the
8863 * slot its predecessor had died holding went spare. It
8864 * was pinned to that sibling's CPU too.
8865 *
8866 * So identity comes from the child that left, and only
8867 * the bookkeeping position is reused. */
8868 12 int slot = hm_nchildren;
8869 12 pid_t fresh = hm_spawn(aTHX_ cfg, dead_widx);
8870 /*
8871 # uncoverable branch false class:ignore_covered_err
8872 # uncoverable condition right count:1 class:ignore_covered_err */
8873 12 ▶ if (fresh > 0) { /* never record a -1 */
Branch: 1 branch
BranchTrueFalseTotal
if (fresh > 0) { /* never record a -1 */ 12 0 12
8874 12 hm_child_start[slot] = time(NULL);
8875 12 hm_child_widx[slot] = dead_widx;
8876 12 hm_children[slot] = fresh;
8877 12 hm_nchildren = slot + 1;
8878 }
8879 }
8880 12 ▶ if (hm_sup_term) break; /* TERM arrived during backoff */
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_term) break; /* TERM arrived during backoff */ 2 10 12
8881 }
8882  
8883 57 ▶ if (hm_sup_term) continue; /* serviced at the top of the loop */
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_term) continue; /* serviced at the top of the loop */ 2 55 57
8884  
8885 /* atomically unblock and sleep until the next signal */
8886 55 sigsuspend(&orig);
8887 }
8888  
8889 27 sigprocmask(SIG_SETMASK, &orig, NULL);
8890 27 hm_unlink_pidfile(cfg->pid_path);
8891  
8892 /* The pool is down because the caller's own alarm came due, so
8893 * finish the job the alarm was set to do. */
8894 /*
8895 # uncoverable branch true class:ignore_covered_err
8896 # uncoverable condition left count:1 class:ignore_covered_err */
8897 27 ▶ if (hm_sup_alarmed) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_alarmed) { 0 27 27
8898 0 signal(SIGALRM, SIG_DFL); /* # uncoverable statement */
8899 0 raise(SIGALRM); /* # uncoverable statement */
8900 }
8901 }
8902 }
8903 #endif /* !_WIN32 */
8904 }
8905  
8906 /* loop object <-> pointer */
8907 3036 static hm_loop *hm_loop_from_sv(pTHX_ SV *sv) {
8908 /*
8909 # uncoverable condition left count:1 class:ignore_covered_err
8910 # uncoverable condition left count:3 class:ignore_covered_err */
8911 3036 ▶ if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop")))
Branch: 3 branches
BranchTrueFalseTotal
if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop"))) 3036 0 3036
if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop"))) 3035 1 3036
if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop"))) 0 3035 3035
8912 1 croak("not a Hyperman::Loop");
8913 3035 return INT2PTR(hm_loop *, SvIV(SvRV(sv)));
8914 }
8915  
8916 /* The Perl wrapper for a loop. ONE blessed referent per loop, however many
8917 * times this is asked: Hyperman::Loop->new, psgix.loop, Hyperman->loop and
8918 * the ABI's sv_of_loop used to each mint their own, and the first wrapper
8919 * whose refcount hit zero freed a Perl-owned loop under every other one.
8920 * The loop keeps a WEAK copy, so holding the wrapper is what keeps the loop,
8921 * and the loop holding its own wrapper keeps nothing alive. */
8922 922 static SV *hm_loop_to_sv(pTHX_ hm_loop *loop) {
8923 SV *rv;
8924 922 ▶ if (loop->self_sv && SvROK(loop->self_sv)) return newSVsv(loop->self_sv);
Branch: 2 branches
BranchTrueFalseTotal
if (loop->self_sv && SvROK(loop->self_sv)) return newSVsv(loop->self_sv); 799 123 922
if (loop->self_sv && SvROK(loop->self_sv)) return newSVsv(loop->self_sv); 14 785 799
8925 908 rv = newRV_noinc(newSViv(PTR2IV(loop)));
8926 908 sv_bless(rv, gv_stashpv("Hyperman::Loop", GV_ADD));
8927 908 ▶ if (loop->self_sv) SvREFCNT_dec(loop->self_sv); /* a cleared weak ref */
Branch: 1 branch
BranchTrueFalseTotal
if (loop->self_sv) SvREFCNT_dec(loop->self_sv); /* a cleared weak ref */ 785 123 908
8928 908 loop->self_sv = newSVsv(rv);
8929 908 sv_rvweaken(loop->self_sv);
8930 908 return rv;
8931 }
8932  
8933 /* install_await: $Hyperman::Future::AWAIT pumps this loop */
8934 XS_INTERNAL(hm_xs_await_cb);
8935 1 XS_INTERNAL(hm_xs_await_cb) {
8936 1 dXSARGS;
8937 1 hm_clos *cl = hm_clos_of(aTHX_ cv);
8938 /*
8939 # uncoverable branch true class:ignore_covered_err
8940 # uncoverable condition left count:1 class:ignore_covered_err
8941 # uncoverable condition left count:2 class:ignore_covered_err */
8942 1 ▶ if (!cl || items < 1) XSRETURN_EMPTY;
Branch: 2 branches
BranchTrueFalseTotal
if (!cl || items < 1) XSRETURN_EMPTY; 1 0 1
if (!cl || items < 1) XSRETURN_EMPTY; 0 1 1
8943 1 hm_loop_run(aTHX_ hm_loop_from_sv(aTHX_ cl->a), ST(0));
8944 1 XSRETURN_EMPTY;
8945 }
8946  
8947 /* A run() option that is a count: a non-negative number, never a string
8948 * that is not one ("10M" read as 10) and never a negative ("-1" read as
8949 * UV_MAX, which for max_body was an unbounded request buffer). */
8950 40 static UV hm_opt_count(pTHX_ SV *val, const char *key) {
8951 /*
8952 # uncoverable condition left count:1 class:ignore_covered_err
8953 # uncoverable condition left count:2 class:ignore_covered_err
8954 # uncoverable condition right count:4 class:ignore_covered_err
8955 # uncoverable condition right count:5 class:ignore_covered_err */
8956 40 ▶ if (!SvOK(val) || SvROK(val)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvOK(val) || SvROK(val) 40 0 40
if (!SvOK(val) || SvROK(val) 40 0 40
8957 40 ▶ || (!SvIOK(val) && !SvNOK(val) && !looks_like_number(val))
Branch: 3 branches
BranchTrueFalseTotal
|| (!SvIOK(val) && !SvNOK(val) && !looks_like_number(val)) 4 36 40
|| (!SvIOK(val) && !SvNOK(val) && !looks_like_number(val)) 4 0 4
|| (!SvIOK(val) && !SvNOK(val) && !looks_like_number(val)) 0 4 4
8958 36 ▶ || SvNV(val) < 0)
Branch: 1 branch
BranchTrueFalseTotal
|| SvNV(val) < 0) 4 32 36
8959 16 ▶ croak("Hyperman->run: %s must be a non-negative number, not '%s'",
Branch: 1 branch
BranchTrueFalseTotal
croak("Hyperman->run: %s must be a non-negative number, not '%s'", 8 0 8
8960 key, SvOK(val) ? SvPV_nolen(val) : "undef"); /* # uncoverable condition right count:1 class:ignore_covered_err */
8961 32 return SvUV(val);
8962 }
8963  
8964 #endif /* HM_CORE_H */
« include/hyperman/hm_compress.h ↑ Summary include/hyperman/hm_parse.h »