include/hyperman/hm_core.h

filter: Statementstmt 91.8% 3037 / 3395 (103 uncoverable) Branchbran 78.2% 2240 / 3434 (515 uncoverable) Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 85.0% 5277 / 6829 (618 uncoverable) CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/hyperman/hm_future.h ↑ Summary include/hyperman/hm_compress.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 te_trailers; /* the request's TE listed "trailers", so
167 * a chunked body may end with trailer
168 * fields (hm_stream_finish). A client
169 * that did not ask is allowed to discard
170 * them and may not even parse them, so
171 * without this bit they are dropped */
172 unsigned char cont_sent; /* a 100 Continue has gone out for the
173 * request being read. Per request, and
174 * on the connection rather than on the
175 * stack, because the headers stay in rbuf
176 * and hm_process re-reads them on every
177 * readable event until the body is whole */
178 unsigned char is_head; /* the request being answered is a HEAD:
179 * the headers go out, the body does not */
180 unsigned char in_app; /* a synchronous handler for this
181 * connection is on the C stack. A ->get
182 * inside it pumps this same loop, so a
183 * close asked for meanwhile is deferred
184 * to the frame that called the app */
185 unsigned char close_deferred; /* hm_close was asked for while in_app */
186 unsigned char read_paused; /* read interest dropped while in_app with
187 * a full buffer (hm_read_pause) */
188 unsigned char pp_wait; /* awaiting the PROXY header: nothing
189 * else reads this socket until it is
190 * parsed (hm_proxy_readable) */
191 char proxy_addr[INET6_ADDRSTRLEN]; /* the proxy that connected, once
192 * the header named the real client */
193 int proxy_port;
194 unsigned char backlogged; /* hm_process stopped on a full write
195 * buffer; the drain re-queues it */
196 unsigned char req_11; /* the request on the plate is HTTP/1.1 */
197 unsigned char stream_mode; /* a streamed body's framing (HM_SM_*) */
198 unsigned char stream_done; /* a streamed body ended with keep-alive
199 * on: the drain serves the pipeline */
200 UV stream_serial; /* streamed responses begun on this conn; a
201 * Writer carries the one it belongs to, so a
202 * writer kept past its response cannot end
203 * the next one */
204 UV stream_left; /* HM_SM_LENGTH: body octets still owed */
205 size_t chunk_pos; /* chunked body: octets validated so far, so
206 * a re-scan starts at the last chunk boundary
207 * rather than at the first chunk */
208 size_t chunk_dec; /* decoded octets up to chunk_pos */
209 hm_bsrc bsrc; /* streaming body being dripped, if any */
210 int last_status; /* last response status/bytes (logging) */
211 size_t last_blen;
212 char peer[INET6_ADDRSTRLEN]; /* REMOTE_ADDR, filled at accept */
213 int peer_port; /* REMOTE_PORT, filled at accept */
214 time_t last_active;
215 time_t req_start; /* first byte of an incomplete request */
216 time_t last_rx; /* last read that delivered bytes: the body
217 * phase is timed from here, not from the
218 * request's first byte */
219 unsigned char body_phase; /* headers complete, body still arriving:
220 * hm_sweep applies body_timeout */
221 /* A body being drained to a temp file rather than accumulated in rbuf.
222 * -1 when not spilling. The fd becomes psgi.input and the handle owns it
223 * from that moment; the file is unlinked at creation, so nothing is left
224 * behind however the request ends. */
225 int spill_fd;
226 long spill_got; /* body octets already written to it */
227 hm_conn *lru_prev, *lru_next;
228 hm_conn *pool_next;
229 hm_loop *loop;
230 hm_listener *lst; /* listener this conn was accepted on */
231 };
232  
233 /* QUIC's expiry min-heap. hm_quic.h owns every operation on it; the type is
234 * here because hm_loop carries one BY VALUE, so the "has QUIC anything to do"
235 * test on the loop's hot path is a load and a compare rather than a
236 * dereference. ngtcp2 rearms a connection's expiry after essentially every
237 * packet, and none of the backend timer vtables can carry that - see the
238 * header comment in hm_quic.h for the costing. */
239 typedef struct hm_qconn hm_qconn;
240 typedef struct { hm_qconn **a; int n, cap; } hm_qheap;
241  
242 /* app-owned fd watcher: a one-shot Future, a persistent Perl callback, or a
243 * persistent C callback (the ABI path - dispatched with no Perl frame) */
244 typedef struct {
245 SV *sv; /* future or Perl cb; NULL for a C watcher */
246 unsigned char is_cb;
247 hm_abi_io_cb c_cb; /* C watcher; checked before sv */
248 void *c_ud;
249 } hm_iow;
250  
251 /* timer watcher */
252 #define HM_TW_FUTURE 0
253 #define HM_TW_CB 1
254 #define HM_TW_SWEEP 2
255 #define HM_TW_HARDSTOP 3
256 #define HM_TW_C 4 /* ABI: C callback, cancellable via handle */
257 typedef struct hm_tw_s {
258 int kind;
259 SV *sv;
260 hm_loop *loop;
261 hm_abi_timer_cb c_cb; /* HM_TW_C only */
262 void *c_ud;
263 double due; /* oneshot deadline, monotonic seconds; 0 = none */
264 /* Cancelled, and waiting on the loop's graveyard to be freed. The
265 * backends fill a whole event array before any of it is dispatched, so
266 * a timer cancelled from an earlier event in the batch may still be
267 * named by a later one; freeing it at once was a use after free. */
268 unsigned char dead;
269 struct hm_tw_s *gy_next;
270 } hm_tw;
271  
272 /* The deadline a oneshot is armed for, on the clock hm_dispatch checks it
273 * against. The backend's own timer is a wake-up hint, not the deadline:
274 * kqueue's EVFILT_TIMER on NetBSD is a callout in scheduler ticks, and in a
275 * VM those ticks run ahead of CLOCK_MONOTONIC. */
276 #define hm_tw_due(secs) ((double)hm_now_ns() / 1e9 + (secs))
277  
278 typedef struct { int fd; UV id; } hm_again;
279  
280 /* The events one hm_loop_run frame took from the backend and has not yet
281 * dispatched. A nested run (a handler's ->get) sits inside one of them, and
282 * the rest are already out of the kernel: a oneshot timer is never reported
283 * again, so a nested wait for the event next to it waited forever. Each
284 * frame links its batch here, and a nested one dispatches what its callers
285 * still hold before it waits. */
286 typedef struct hm_batch_s {
287 hm_event *evs;
288 int n, i; /* i: the next one to dispatch */
289 struct hm_batch_s *up; /* the batch of the frame that called us */
290 } hm_batch;
291  
292 /* One piece of an access-log line. The format string is compiled to these
293 * once, in the parent, so writing a line is a walk over an array and never a
294 * parse: a literal run, an $env value (the key SV carries its hash), or one
295 * of the computed fields. */
296 #define HM_LT_LIT 0 /* literal bytes */
297 #define HM_LT_ENV 1 /* $env->{key}, escaped; "-" when absent */
298 #define HM_LT_DASH 2 /* %l: always "-" */
299 #define HM_LT_STATUS 3 /* %s, %>s */
300 #define HM_LT_BYTES 4 /* %b: body bytes, "-" when there were none */
301 #define HM_LT_BYTES0 5 /* %B: body bytes, "0" when there were none */
302 #define HM_LT_TIME 6 /* %t: [dd/Mon/YYYY:HH:MM:SS +ZZZZ] */
303 #define HM_LT_TIME_ISO 7 /* json: YYYY-MM-DDTHH:MM:SS+ZZZZ */
304 #define HM_LT_REQLINE 8 /* %r: METHOD URI PROTO */
305 #define HM_LT_QUERY 9 /* %q: ?query, or nothing */
306 #define HM_LT_PID 10 /* %P */
307 #define HM_LT_DUR_US 11 /* %D: microseconds since the request was built */
308 #define HM_LT_DUR_S 12 /* %T: whole seconds of the same */
309 typedef struct {
310 int kind;
311 char *lit; /* HM_LT_LIT: owned */
312 size_t litlen;
313 SV *key; /* HM_LT_ENV: a shared-string SV, hash precomputed */
314 } hm_logtok;
315  
316 struct hm_loop {
317 int pid; /* the process that created this loop
318 (hm_os_getpid: MSVC has no pid_t) */
319 hm_backend *be;
320 hm_conn **conns; /* [HM_MAXFD] */
321 hm_iow *io_r, *io_w; /* [HM_MAXFD] app io watchers */
322 AV *deferred; /* run-soon callbacks */
323 hm_again *again; /* conns with buffered requests */
324 int again_n, again_cap;
325 hm_hline *hidx; /* header-line index overflow buffer */
326 int hidx_cap;
327 hm_conn *lru_head, *lru_tail;
328 hm_conn *pool; int pool_n;
329 /* Completion-mode receive (io_uring only, opt-in). `completion` is set
330 * once at loop start when the backend can do it and the operator asked.
331 * `quar` holds read buffers belonging to connections that closed with a
332 * recv still outstanding - see hm_quar_push. */
333 int completion;
334 struct hm_quar *quar;
335 hm_tw *tw_gy; /* cancelled timers, freed between batches */
336 int starved_retry; /* a listener waits for hm_accept_unstarve */
337 hm_tw *sweep_tw;
338 SV *app; /* server: PSGI app coderef */
339 hm_listener *listeners; /* server: bound listeners */
340 int nlisteners;
341 int attached; /* server attached (>=1 listener) */
342 int nconns;
343 int stop;
344 int stopping; /* graceful shutdown in progress */
345 int running;
346 hm_batch *batch; /* the innermost run's (see hm_batch) */
347 int perl_owned; /* created via Hyperman::Loop->new */
348 time_t now;
349 double idle_timeout;
350 double header_timeout;
351 double body_timeout; /* a body stalled this long is closed */
352 double request_timeout; /* whole request ceiling; 0 = none */
353 UV body_min_rate; /* bytes/s floor over a body; 0 = none */
354 int max_pipeline; /* fairness: requests per conn per wakeup */
355 size_t max_read; /* request size ceiling (headers + body) */
356 int compress; /* gzip responses (0 = off, the default) */
357 size_t compress_min; /* below this, gzip buys nothing */
358 int compress_level; /* gzip level; HZ_LEVEL by default */
359 SV *compress_types; /* AV of extra compressible media types */
360 SV *self_sv; /* cached psgix.loop wrapper */
361 SV *log_cb; /* access_log coderef, or NULL */
362 int log_fd; /* fast access-log fd (C writer), or -1 */
363 char *log_buf; /* pending Combined-format log lines */
364 size_t log_len, log_cap;
365 time_t log_ts_sec; /* second the cached stamp below is for */
366 char log_ts[32]; /* "dd/Mon/YYYY:HH:MM:SS +ZZZZ", 1Hz */
367 time_t date_sec; /* second the Date header below is for */
368 char date_hdr[40]; /* "Date: <IMF-fixdate>\r\n", 1Hz */
369 hm_logtok *logtok; /* the compiled access_log_format */
370 int nlogtok;
371 int log_json; /* values escaped for JSON, not CLF */
372 int log_wants_t0; /* the format reads %D/%T: stamp requests */
373 time_t log_iso_sec; /* second the ISO stamp below is for */
374 char log_iso[40]; /* "YYYY-MM-DDTHH:MM:SS+ZZZZ", 1Hz */
375 UV requests; /* requests dispatched (stats) */
376 UV accepts; /* connections accepted (stats) */
377 UV denied; /* connections dropped at accept, denylist */
378 UV bytes_out; /* response bytes queued (stats) */
379 UV datagrams; /* QUIC datagrams taken off the wire */
380 UV h3_conns; /* QUIC handshakes completed */
381 UV h3_live; /* QUIC connections open now */
382 UV h3_requests; /* requests served over HTTP/3 */
383 UV datagrams_out; /* QUIC datagrams sent (one sendto
384 * each: no GSO anywhere yet) */
385 UV http3_max_conns; /* ceiling on h3_live, 0 = unlimited */
386 hm_qheap qheap; /* QUIC expiry deadlines (hm_quic.h) */
387 UV max_requests; /* recycle worker after N (0=off) */
388 int recycle_pending; /* max_requests hit; drain at loop top */
389 double shutdown_grace; /* graceful-drain bound (secs) */
390 hm_tw *hardstop_tw;
391 };
392  
393 /* One served request, counted, and max_requests tested - for every protocol
394 * that finishes one. The bound belongs to the worker and not to HTTP/1: a
395 * site whose browsers all negotiate h2 would otherwise never reach it, and
396 * the worker it was meant to retire grows for as long as the box lets it.
397 *
398 * Not on the 101 paths (h2c upgrade, detach, tunnel), which count their
399 * request and deliberately do not test: the socket there has just left this
400 * loop for an application that means to hold it open, and a drain decided by
401 * the request that handed it over is the one moment it must not happen.
402 *
403 * A function and not a macro because the argument is read five times. */
404 871 static void hm_count_request(hm_loop *loop) {
405 871 loop->requests++;
406 /*
407 # uncoverable condition right count:3 class:ignore_covered_err
408 # uncoverable condition right count:4 class:ignore_covered_err */
409 871 ▶ if (loop->max_requests && loop->requests >= loop->max_requests
Branch: 2 branches
BranchTrueFalseTotal
if (loop->max_requests && loop->requests >= loop->max_requests 82 789 871
if (loop->max_requests && loop->requests >= loop->max_requests 8 74 82
410 8 ▶ && !loop->stopping && loop->attached)
Branch: 2 branches
BranchTrueFalseTotal
&& !loop->stopping && loop->attached) 8 0 8
&& !loop->stopping && loop->attached) 8 0 8
411 8 loop->recycle_pending = 1; /* drain at the loop iteration boundary */
412 871 }
413  
414 /* Does a Hyperman::Writer's tag slot hold this string? The four-element
415 * writer shapes (h2 and h3) have the same arity, so they are told apart by
416 * the tag and never by length - a length test routes an HTTP/3 body into an
417 * nghttp2 session. Used from xs/writer.xs. */
418 121 static int hm_writer_tag_is(pTHX_ AV *w, const char *want, STRLEN wantlen) {
419 121 SV **t = av_fetch(w, 3, 0);
420 STRLEN l;
421 const char *p;
422 /*
423 # uncoverable branch true class:ignore_covered_err
424 # uncoverable condition left count:1 class:ignore_covered_err
425 # uncoverable condition left count:2 class:ignore_covered_err
426 # uncoverable condition left count:3 class:ignore_covered_err */
427 121 ▶ if (!t || !*t || !SvOK(*t)) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!t || !*t || !SvOK(*t)) return 0; 121 0 121
if (!t || !*t || !SvOK(*t)) return 0; 121 0 121
if (!t || !*t || !SvOK(*t)) return 0; 0 121 121
428 121 p = SvPV(*t, l);
429 121 ▶ 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 */ 121 0 121
return l == wantlen && memcmp(p, want, l) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 89 32 121
430 }
431  
432 /* Find the listener owning a ready fd (listener count is tiny). */
433 31220 static hm_listener *hm_listener_for_fd(hm_loop *loop, int fd) {
434 int i;
435 32597 ▶ for (i = 0; i < loop->nlisteners; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) 31388 1209 32597
436 31388 ▶ if (loop->listeners[i].fd == fd) return &loop->listeners[i];
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].fd == fd) return &loop->listeners[i]; 30011 1377 31388
437 1209 return NULL;
438 }
439  
440 /* The same, for the QUIC side. Separate rather than a flag on the above,
441 * because a UDP listener fd is never in loop->conns[] and the caller wants
442 * to know which of the two it has. */
443 1209 static hm_listener *hm_listener_for_udp(hm_loop *loop, int fd) {
444 int i;
445 2572 ▶ for (i = 0; i < loop->nlisteners; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) 1363 1209 2572
446 /*
447 # uncoverable branch true class:ignore_covered_err
448 # uncoverable condition left count:1 class:ignore_covered_err
449 # uncoverable condition left count:2 class:ignore_covered_err
450 # uncoverable condition right count:2 class:ignore_covered_err */
451 1363 ▶ 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 1363 1363
if (loop->listeners[i].udp_fd >= 0 && loop->listeners[i].udp_fd == fd) 0 0 0
452 0 return &loop->listeners[i]; /* # uncoverable statement class:ignore_covered_err */
453 1209 return NULL;
454 }
455  
456 static SV *hm_empty_input; /* shared empty psgi.input */
457 static SV *hm_empty_input_sv(pTHX); /* ... checked still open */
458 #ifndef _WIN32
459 static pid_t hm_children[1024]; /* the supervisor's pool (POSIX only) */
460 static time_t hm_child_start[1024];
461 /* The WORKER INDEX each of those was forked with, which is not its position
462 * here: this array is kept packed by swapping the last entry down over a
463 * departed one, so a position means nothing beyond "somebody lives here". The
464 * index is an identity - it picks the worker's waker slot and its CPU - so it
465 * has to travel with the child rather than be recomputed from where the child
466 * happens to sit. */
467 static int hm_child_widx[1024];
468 static int hm_nchildren = 0;
469 #endif
470 static UV hm_id_counter = 0;
471  
472 static SV *hm_loop_to_sv(pTHX_ hm_loop *loop);
473 static void hm_on_signal(pTHX_ hm_loop *loop);
474 static void hm_deliver(pTHX_ int fd, UV id, SV *resp);
475 static int hm_flush(pTHX_ hm_conn *c);
476 static void hm_process(pTHX_ hm_conn *c);
477 static int hm_queue_response(pTHX_ hm_conn *c, SV *resp);
478 static void hm_close(pTHX_ hm_loop *loop, hm_conn *c);
479 static void hm_wb_reserve(hm_conn *c, size_t need);
480 static void hm_wb_put(hm_conn *c, const char *p, size_t n);
481 static void hm_again_push(hm_loop *loop, hm_conn *c);
482 static void hm_tw_gy_sweep(hm_loop *loop);
483 static void hm_h2_free(pTHX_ void *h2); /* defined in hm_http2.h */
484 static void hm_readable(pTHX_ hm_conn *c);
485 static void hm_read_resume(hm_loop *loop, hm_conn *c);
486  
487 /* ABI v6 stream handles, defined in hm_stream.h (included below, after the
488 * HTTP/1 and HTTP/2 halves it sits on top of). The two counters are read on
489 * the close and flush paths rather than called into, because they are zero
490 * for every connection that never opened a handle - which is nearly all of
491 * them - and a list walk per flush is not free. */
492 static int hm_stream_live_n = 0;
493 static int hm_stream_paused_n = 0;
494 static void hm_quic_readable(pTHX_ hm_loop *loop, hm_listener *lst); /* hm_quic.h */
495 static void hm_quic_expire(pTHX_ hm_loop *loop); /* hm_quic.h */
496 static void hm_quic_srv_attach(pTHX_ hm_loop *loop, hm_listener *lst, int widx);
497 static void hm_quic_srv_free(pTHX_ hm_listener *lst);
498 static void hm_quic_shutdown(pTHX_ hm_loop *loop);
499 static void hm_quic_ctx_swap(pTHX_ hm_listener *lst, void *fresh);
500 static uint64_t hm_quic_next_deadline(hm_loop *loop);
501 static void hm_quic_secret_init(void);
502 static void hm_stream_conn_gone(pTHX_ int fd, UV id);
503 static int hm_stream_deliver(pTHX_ int fd, UV cid, int64_t sid,
504 const char *buf, STRLEN len, int fin);
505 static void hm_stream_h2_gone(pTHX_ int fd, UV id, int64_t sid);
506 static void hm_stream_drained(pTHX_ hm_conn *c);
507 static int hm_h2_reentrant(hm_conn *c); /* hm_http2.h */
508  
509 #include "hm_tls.h" /* SSL_CTX, wrap, hm_cread/hm_cwrite */
510  
511 /* ---- small utilities ----------------------------------------------------- */
512  
513 18 static const char *hm_reason(int s) {
514 /*
515 # uncoverable branch true count:1
516 # uncoverable branch true count:5
517 # uncoverable branch true count:6
518 # uncoverable branch true count:7
519 # uncoverable branch true count:8
520 # uncoverable branch true count:9
521 # uncoverable branch true count:10
522 # uncoverable branch true count:11
523 # uncoverable branch true count:12
524 # uncoverable branch true count:13
525 # uncoverable branch true count:14
526 # uncoverable branch true count:15
527 # uncoverable branch true count:17 */
528 18 switch (s) {
529 10 case 100: return "Continue"; case 101: return "Switching Protocols";
530 2 case 102: return "Processing"; case 103: return "Early Hints";
531 0 case 200: return "OK"; case 201: return "Created"; /* # uncoverable statement */
532 0 case 204: return "No Content"; case 301: return "Moved Permanently"; /* # uncoverable statement */
533 0 case 302: return "Found"; case 304: return "Not Modified"; /* # uncoverable statement */
534 0 case 400: return "Bad Request"; case 401: return "Unauthorized"; /* # uncoverable statement */
535 0 case 403: return "Forbidden"; case 404: return "Not Found"; /* # uncoverable statement */
536 0 case 405: return "Method Not Allowed"; /* # uncoverable statement */
537 1 case 426: return "Upgrade Required";
538 0 case 500: return "Internal Server Error"; /* # uncoverable statement */
539 5 default: return "OK";
540 }
541 }
542  
543 /* Tiny decimal formatters: snprintf's format parsing and locale machinery
544 * are measurable at hot-path request rates. Return bytes written. */
545 775 static size_t hm_utoa(char *out, unsigned long v) {
546 char tmp[20];
547 775 size_t n = 0, i;
548 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); 586 775 1361
549 2136 ▶ 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 775 2136
550 775 return n;
551 }
552 102 static size_t hm_itoa(char *out, long v) {
553 /*
554 # uncoverable branch true
555 # uncoverable condition left count:1 class:ignore_covered_err */
556 102 ▶ 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 102 102
557 102 return hm_utoa(out, (unsigned long)v);
558 }
559  
560 /* Status line for the response: precomputed for the common statuses, built
561 * into buf (>= 64 bytes) otherwise. Sets *len, returns the line. */
562 870 static const char *hm_status_line(int s, size_t *len, char *buf) {
563 #define HM_SL(str) do { *len = sizeof(str) - 1; return str; } while (0)
564 870 switch (s) {
565 830 case 200: HM_SL("HTTP/1.1 200 OK\r\n");
566 1 case 201: HM_SL("HTTP/1.1 201 Created\r\n");
567 4 case 204: HM_SL("HTTP/1.1 204 No Content\r\n");
568 3 case 301: HM_SL("HTTP/1.1 301 Moved Permanently\r\n");
569 1 case 302: HM_SL("HTTP/1.1 302 Found\r\n");
570 3 case 304: HM_SL("HTTP/1.1 304 Not Modified\r\n");
571 1 case 400: HM_SL("HTTP/1.1 400 Bad Request\r\n");
572 1 case 401: HM_SL("HTTP/1.1 401 Unauthorized\r\n");
573 1 case 403: HM_SL("HTTP/1.1 403 Forbidden\r\n");
574 2 case 404: HM_SL("HTTP/1.1 404 Not Found\r\n");
575 1 case 405: HM_SL("HTTP/1.1 405 Method Not Allowed\r\n");
576 4 case 500: HM_SL("HTTP/1.1 500 Internal Server Error\r\n");
577 }
578 #undef HM_SL
579 {
580 18 const char *r = hm_reason(s);
581 18 size_t rl = strlen(r), n = 9;
582 18 memcpy(buf, "HTTP/1.1 ", 9);
583 18 n += hm_itoa(buf + n, (long)s);
584 18 buf[n++] = ' ';
585 18 memcpy(buf + n, r, rl); n += rl;
586 18 buf[n++] = '\r'; buf[n++] = '\n';
587 18 *len = n;
588 18 return buf;
589 }
590 }
591  
592 /* Format a peer sockaddr into a printable REMOTE_ADDR string and its port ("" /
593 * 0 on failure or for address families we don't serve). */
594 936 static void hm_fmt_peer(char *out, size_t outlen, int *port, const struct sockaddr *sa) {
595 936 out[0] = '\0';
596 /*
597 # uncoverable branch false class:ignore_covered_err
598 # uncoverable condition right count:1 class:ignore_covered_err */
599 936 ▶ if (port) *port = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (port) *port = 0; 936 0 936
600 /*
601 # uncoverable branch true
602 # uncoverable condition left count:1 class:ignore_covered_err */
603 936 ▶ if (!sa) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sa) return; 0 936 936
604 936 ▶ if (sa->sa_family == AF_INET) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa->sa_family == AF_INET) { 934 2 936
605 934 const struct sockaddr_in *s4 = (const struct sockaddr_in *)sa;
606 934 inet_ntop(AF_INET, &s4->sin_addr, out, (socklen_t)outlen);
607 /*
608 # uncoverable branch false class:ignore_covered_err
609 # uncoverable condition right count:1 class:ignore_covered_err */
610 934 ▶ if (port) *port = ntohs(s4->sin_port);
Branch: 1 branch
BranchTrueFalseTotal
if (port) *port = ntohs(s4->sin_port); 934 0 934
611 /*
612 # uncoverable branch true class:ignore_covered_err
613 # uncoverable condition left count:1 class:ignore_covered_err */
614 2 ▶ } else if (sa->sa_family == AF_INET6) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (sa->sa_family == AF_INET6) { 0 2 2
615 0 const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)sa; /* # uncoverable statement class:ignore_covered_err */
616 /* An IPv4 client of a dual-stack listener arrives as ::ffff:a.b.c.d.
617 * Formatted as the IPv4 it is: the denylist and the rate limiter
618 * key on the string, and "1.2.3.4" must be one client whichever
619 * listener it came through. */
620 /*
621 # uncoverable statement class:ignore_covered_err
622 # uncoverable branch true class:ignore_covered_err
623 # uncoverable branch false class:ignore_covered_err
624 # uncoverable condition left count:1 class:ignore_covered_err
625 # uncoverable condition right count:1 class:ignore_covered_err */
626 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
627 0 inet_ntop(AF_INET, ((const unsigned char *)&s6->sin6_addr) + 12, /* # uncoverable statement */
628 out, (socklen_t)outlen); /* # uncoverable statement */
629 else
630 0 inet_ntop(AF_INET6, &s6->sin6_addr, out, (socklen_t)outlen); /* # uncoverable statement class:ignore_covered_err */
631 /*
632 # uncoverable statement class:ignore_covered_err
633 # uncoverable branch true class:ignore_covered_err
634 # uncoverable branch false class:ignore_covered_err
635 # uncoverable condition left count:1 class:ignore_covered_err
636 # uncoverable condition right count:1 class:ignore_covered_err */
637 0 ▶ if (port) *port = ntohs(s6->sin6_port);
Branch: 1 branch
BranchTrueFalseTotal
if (port) *port = ntohs(s6->sin6_port); 0 0 0
638 }
639 }
640  
641 92 static void hm_set_nonblock(int fd) { hm_os_set_nonblock(fd); }
642  
643 /* fd of a filehandle / IO ref, or a plain fd number */
644 20 static int hm_fd_of(pTHX_ SV *sv) {
645 /*
646 # uncoverable branch false
647 # uncoverable condition right count:1 class:ignore_covered_err */
648 20 ▶ if (SvROK(sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(sv)) { 20 0 20
649 20 IO *io = sv_2io(sv);
650 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
651 1 croak("Hyperman: not an open filehandle");
652 }
653 0 return (int)SvIV(sv); /* # uncoverable statement */
654 }
655  
656 /* a fresh anonymous glob with an IO slot (standard idiom) */
657 930 static GV *hm_anon_glob(pTHX) {
658 930 GV *gv = newGVgen("Hyperman");
659 930 ▶ (void)GvIOn(gv);
Branch: 5 branches
BranchTrueFalseTotal
(void)GvIOn(gv); 930 0 930
(void)GvIOn(gv); 0 930 930
(void)GvIOn(gv); 0 0 0
(void)GvIOn(gv); 930 0 930
(void)GvIOn(gv); 0 930 930
660 930 SvREFCNT_inc((SV *)gv);
661 930 (void)hv_delete(GvSTASH(gv), GvNAME(gv), GvNAMELEN(gv), G_DISCARD);
662 930 return gv;
663 }
664  
665 /* A read handle over an already-open descriptor, rewound. The handle owns the
666 * descriptor from this point. */
667 5 static SV *hm_input_from_fd(pTHX_ int fd) {
668 PerlIO *fp;
669 GV *gv;
670 IO *io;
671 /*
672 # uncoverable branch true
673 # uncoverable condition left count:1 class:ignore_covered_err */
674 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
675 5 fp = PerlIO_fdopen(fd, "rb");
676 /*
677 # uncoverable branch true
678 # uncoverable condition left count:1 class:ignore_covered_err */
679 5 ▶ if (!fp) { PerlLIO_close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) { PerlLIO_close(fd); return NULL; } 0 5 5
680 5 gv = hm_anon_glob(aTHX);
681 /*
682 # uncoverable branch true
683 # uncoverable condition left count:1 class:ignore_covered_err */
684 5 ▶ if (!gv) { PerlIO_close(fp); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!gv) { PerlIO_close(fp); return NULL; } 0 5 5
685 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
686 5 IoIFP(io) = fp;
687 5 IoTYPE(io) = IoTYPE_RDONLY;
688 5 return newRV_noinc((SV *)gv);
689 }
690  
691 /* A temp file for a body being drained out of the read buffer.
692 *
693 * Unlinked the instant it exists, so the descriptor is its only reference: it
694 * goes away when the request ends, when the handler dies, or when the worker
695 * is killed, and there is no cleanup path anywhere to forget. Nothing is
696 * inherited across a fork either, which is the failure this workspace keeps
697 * meeting from the other direction. */
698 /* Where a body temp file goes. TMPDIR is the POSIX spelling of the question
699 * and TEMP the Windows one - asking only the first left Windows falling back
700 * to a "/tmp" that is not there, which is a failed mkstemp on every request
701 * carrying a body. */
702 6 static const char *hm_tmpdir(void) {
703 6 const char *d = getenv("TMPDIR");
704 /*
705 # uncoverable branch true class:ignore_covered_err
706 # uncoverable condition left count:1 class:ignore_covered_err
707 # uncoverable condition left count:2 class:ignore_covered_err
708 # uncoverable condition right count:2 class:ignore_covered_err */
709 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
710 #ifdef _WIN32
711 if ((d = getenv("TEMP")) && *d) return d;
712 if ((d = getenv("TMP")) && *d) return d;
713 return ".";
714 #else
715 6 return "/tmp";
716 #endif
717 }
718  
719 /* dir + "/hm-body-XXXXXX" into buf, or 0 if the directory will not fit. */
720 6 static int hm_body_tmppath(char *buf, size_t cap) {
721 6 const char *dir = hm_tmpdir();
722 6 size_t dl = strlen(dir);
723 /*
724 # uncoverable branch true
725 # uncoverable condition left count:1 class:ignore_covered_err */
726 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
727 6 my_strlcpy(buf, dir, cap);
728 /*
729 # uncoverable branch false class:ignore_covered_err
730 # uncoverable condition right count:1 class:ignore_covered_err
731 # uncoverable condition right count:2 class:ignore_covered_err
732 # uncoverable condition right count:3 class:ignore_covered_err */
733 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
734 6 my_strlcat(buf, "/", cap);
735 6 my_strlcat(buf, "hm-body-XXXXXX", cap);
736 6 return 1;
737 }
738  
739 5 static int hm_body_tmpfile(void) {
740 char path[512];
741 int fd;
742 /*
743 # uncoverable branch true
744 # uncoverable condition left count:1 class:ignore_covered_err */
745 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
746 5 fd = mkstemp(path);
747 /*
748 # uncoverable branch true
749 # uncoverable condition left count:1 class:ignore_covered_err */
750 5 ▶ if (fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return -1; 0 5 5
751 5 (void)unlink(path);
752 5 return fd;
753 }
754  
755 /* Above this, the body goes to a temp file instead of a second copy in
756 * memory. Below it, the copy is cheaper than an inode and three syscalls. */
757 #ifndef HM_SPILL_BODY
758 # define HM_SPILL_BODY (1024 * 1024)
759 #endif
760  
761 /* psgi.input over a temp file, for a body large enough that a second copy in
762 * memory is the wrong trade.
763 *
764 * The file is UNLINKED as soon as it is open, and the handle keeps it alive:
765 * it vanishes when the handle is closed, whether that is a normal response, a
766 * handler that died, or the worker being killed mid-request. There is no
767 * cleanup path to forget and nothing on disk for another process to find.
768 *
769 * Returns NULL to fall back to the in-memory handle, because a server that
770 * cannot make a temp file should still serve the request.
771 */
772 1 static SV *hm_new_input_file(pTHX_ const char *body, STRLEN len) {
773 char path[512];
774 int fd;
775 1 STRLEN off = 0;
776  
777 /*
778 # uncoverable branch true
779 # uncoverable condition left count:1 class:ignore_covered_err */
780 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
781  
782 1 fd = mkstemp(path);
783 /*
784 # uncoverable branch true
785 # uncoverable condition left count:1 class:ignore_covered_err */
786 1 ▶ if (fd < 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return NULL; 0 1 1
787 1 (void)PerlLIO_unlink(path); /* the handle is the only reference */
788  
789 2 ▶ while (off < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (off < len) { 1 1 2
790 1 SSize_t n = PerlLIO_write(fd, body + off, len - off);
791 /*
792 # uncoverable branch true
793 # uncoverable condition left count:1 class:ignore_covered_err */
794 1 ▶ if (n <= 0) { PerlLIO_close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { PerlLIO_close(fd); return NULL; } 0 1 1
795 1 off += (STRLEN)n;
796 }
797 /*
798 # uncoverable branch true
799 # uncoverable condition left count:1 class:ignore_covered_err */
800 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
801  
802 1 return hm_input_from_fd(aTHX_ fd);
803 }
804  
805 /* psgi.input: an in-memory read handle over the request body, via the
806 * PerlIO :scalar layer - the C equivalent of open($fh,'<',\$body).
807 *
808 * WINDOWS TAKES THE FILE AT EVERY SIZE. PerlIO_openn is declared in perlio.h
809 * but is not among the symbols perl5xx.dll exports, so the :scalar layer
810 * cannot be reached from XS there at all - it is a link error, which is what
811 * the first Windows build of this core hit. The temp file needs nothing but
812 * PerlIO_fdopen, which IS exported, and it is the path every platform
813 * already runs for a body over HM_SPILL_BODY rather than a second one
814 * written for this. The trade is an inode and three syscalls on a Windows
815 * request that carries a body. */
816 111 static SV *hm_new_input(pTHX_ const char *body, STRLEN len) {
817 #ifdef _WIN32
818 SV *f = hm_new_input_file(aTHX_ body, len);
819 return f ? f : &PL_sv_undef;
820 #else
821 static int layer_loaded = 0;
822 SV *bufsv;
823 111 ▶ if (len > HM_SPILL_BODY) {
Branch: 1 branch
BranchTrueFalseTotal
if (len > HM_SPILL_BODY) { 1 110 111
824 1 SV *f = hm_new_input_file(aTHX_ body, len);
825 /*
826 # uncoverable branch false
827 # uncoverable condition right count:1 class:ignore_covered_err */
828 1 ▶ if (f) return f;
Branch: 1 branch
BranchTrueFalseTotal
if (f) return f; 1 0 1
829 }
830 110 bufsv = newSVpvn(body, len);
831 110 SV *rv = newRV_noinc(bufsv);
832 PerlIO *fp;
833 GV *gv;
834 IO *io;
835 110 ▶ if (!layer_loaded) {
Branch: 1 branch
BranchTrueFalseTotal
if (!layer_loaded) { 83 27 110
836 83 load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("PerlIO::scalar"), NULL);
837 83 layer_loaded = 1;
838 }
839 /* The layer takes its own reference to the body, so the RV is ours to
840 * drop here. It must not be mortal: this runs in the event loop's scope,
841 * whose temps are freed only when the loop returns, so a mortal kept one
842 * body per request for the life of the worker. */
843 110 fp = PerlIO_openn(aTHX_ ":scalar", "r", -1, 0, 0, NULL, 1, &rv);
844 110 SvREFCNT_dec(rv);
845 /*
846 # uncoverable branch true
847 # uncoverable condition left count:1 class:ignore_covered_err */
848 110 ▶ if (!fp) return &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) return &PL_sv_undef; 0 110 110
849 110 gv = hm_anon_glob(aTHX);
850 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
851 110 IoIFP(io) = fp;
852 110 IoTYPE(io) = IoTYPE_RDONLY;
853 110 return newRV_noinc((SV *)gv);
854 #endif
855 }
856  
857 /* The shared empty psgi.input, as every bodyless request gets it: one glob
858 * for the whole worker, because a fresh :scalar handle per request is a
859 * glob, an IO and a layer for a body that is not there. One check keeps the
860 * sharing honest: an application that closed it (or re-opened it over
861 * something else) left a handle with no input stream, and the next request
862 * would read a closed filehandle. A new one replaces it then. */
863 851 static SV *hm_empty_input_sv(pTHX) {
864 /*
865 # uncoverable branch false class:ignore_covered_err
866 # uncoverable condition right count:1 class:ignore_covered_err
867 # uncoverable condition right count:2 class:ignore_covered_err */
868 851 ▶ if (hm_empty_input && SvROK(hm_empty_input)) {
Branch: 2 branches
BranchTrueFalseTotal
if (hm_empty_input && SvROK(hm_empty_input)) { 851 0 851
if (hm_empty_input && SvROK(hm_empty_input)) { 851 0 851
869 851 SV *gv = SvRV(hm_empty_input);
870 851 ▶ 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 */ 851 0 851
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 851 0 851
IO *io = SvTYPE(gv) == SVt_PVGV ? GvIO((GV *)gv) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 0 851 851
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 */ 851 0 851
871 851 ▶ 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 */ 851 0 851
if (io && IoIFP(io)) return SvREFCNT_inc(hm_empty_input); /* # uncoverable condition right count:1 class:ignore_covered_err */ 850 1 851
872 1 SvREFCNT_dec(hm_empty_input);
873 1 hm_empty_input = NULL;
874 }
875 1 hm_empty_input = hm_new_input(aTHX_ "", 0);
876 1 return SvREFCNT_inc(hm_empty_input);
877 }
878  
879 /* psgix.io: a dup of the client socket, so an app that hijacks it keeps
880 * the socket alive after the server side closes. Absent on Windows:
881 * duplicating a socket there is WSADuplicateSocket, not dup(2), and the
882 * result would have to be re-wrapped for perl's IO layer - unproven, and
883 * psgix.io is optional in PSGI, so it is simply not offered. */
884 815 static SV *hm_fh_for_fd(pTHX_ int fd) {
885 #ifdef _WIN32
886 (void)fd;
887 return &PL_sv_undef;
888 #else
889 815 int nfd = dup(fd);
890 PerlIO *fp;
891 GV *gv;
892 IO *io;
893 /*
894 # uncoverable branch true class:ignore_covered_err
895 # uncoverable condition left count:1 class:ignore_covered_err */
896 815 ▶ if (nfd < 0) return &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
if (nfd < 0) return &PL_sv_undef; 0 815 815
897 815 fp = PerlIO_fdopen(nfd, "r+");
898 /*
899 # uncoverable branch true
900 # uncoverable condition left count:1 class:ignore_covered_err */
901 815 ▶ 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 815 815
902 815 gv = hm_anon_glob(aTHX);
903 815 ▶ io = GvIO(gv);
Branch: 4 branches
BranchTrueFalseTotal
io = GvIO(gv); 815 0 815
io = GvIO(gv); 0 815 815
io = GvIO(gv); 0 0 0
io = GvIO(gv); 815 0 815
904 815 IoIFP(io) = fp;
905 815 IoOFP(io) = fp;
906 815 IoTYPE(io) = IoTYPE_RDWR;
907 815 return newRV_noinc((SV *)gv);
908 #endif
909 }
910  
911 /* Read out a filehandle / IO::Handle-like response body, honouring
912 * ->getline/->close on objects (PSGI body protocol). Returns a PV SV. */
913 4 static SV *hm_slurp_body(pTHX_ SV *body) {
914 4 SV *out = newSVpvs("");
915 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
916 3 ▶ && gv_fetchmethod_autoload(SvSTASH(SvRV(body)), "getline", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
&& gv_fetchmethod_autoload(SvSTASH(SvRV(body)), "getline", 0)) { 3 0 3
917 6 for (;;) {
918 9 dSP;
919 SV *chunk;
920 int n;
921 9 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 9 9
922 9 ▶ XPUSHs(body);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(body); 0 9 9
923 9 PUTBACK;
924 9 n = call_method("getline", G_SCALAR | G_EVAL);
925 9 SPAGAIN;
926 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
927 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
928 3 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 3 0 3
929 3 break;
930 }
931 6 sv_catsv(out, chunk);
932 6 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 6 0 6
933 }
934 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
935 2 dSP;
936 2 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 2 2
937 2 ▶ XPUSHs(body);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(body); 0 2 2
938 2 PUTBACK;
939 2 call_method("close", G_DISCARD | G_EVAL);
940 2 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 2 0 2
941 }
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 # uncoverable condition left count:3 class:ignore_covered_err
947 # uncoverable condition right count:3 class:ignore_covered_err */
948 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
949 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
950 /* sv_2io croaks on anything that is not a handle, and this is not
951 * under an eval: a body of [200, [], {}] would unwind the loop */
952 1 IO *io = sv_2io(body);
953 /*
954 # uncoverable branch false class:ignore_covered_err
955 # uncoverable condition right count:1 class:ignore_covered_err
956 # uncoverable condition right count:2 class:ignore_covered_err */
957 1 ▶ if (io && IoIFP(io)) {
Branch: 2 branches
BranchTrueFalseTotal
if (io && IoIFP(io)) { 1 0 1
if (io && IoIFP(io)) { 1 0 1
958 char buf[8192];
959 SSize_t got;
960 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
961 1 sv_catpvn(out, buf, got);
962 1 PerlIO_close(IoIFP(io));
963 1 IoIFP(io) = NULL;
964 1 IoOFP(io) = NULL;
965 }
966 }
967 4 return out;
968 }
969  
970 /* ---- streaming body sources ---------------------------------------------- *
971 * The lift: can this filehandle-ish body be streamed rather than slurped?
972 *
973 * - a glob / IO ref over a regular file lifts to (fd, tell, remaining):
974 * remaining is the Content-Length header when the response carries one,
975 * else file-size minus position (which is then also what the auto
976 * Content-Length announces).
977 * - a blessed object lifts when it has BOTH getline and fileno over a
978 * regular file AND the response promises a Content-Length - the range
979 * contract Punk::SendFile::Reader satisfies; the raw fd position is
980 * taken as the read point, so hand over a handle that has not been
981 * buffer-read from. Without a usable fd, a getline object with a
982 * Content-Length still streams, one chunk per getline (kind 2).
983 *
984 * Anything else returns 0 and the caller slurps, exactly as before. */
985  
986 2 static UV hm_bsrc_method_uv(pTHX_ SV *obj, const char *meth, int *ok) {
987 2 dSP;
988 2 UV out = 0;
989 int n;
990 2 *ok = 0;
991 2 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 2 2
992 2 ▶ XPUSHs(obj);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(obj); 0 2 2
993 2 PUTBACK;
994 2 n = call_method(meth, G_SCALAR | G_EVAL);
995 2 SPAGAIN;
996 /*
997 # uncoverable branch false class:ignore_covered_err
998 # uncoverable condition right count:1 class:ignore_covered_err */
999 2 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 2 0 2
1000 2 SV *r = POPs;
1001 /*
1002 # uncoverable branch false class:ignore_covered_err
1003 # uncoverable condition right count:1 class:ignore_covered_err
1004 # uncoverable condition right count:2 class:ignore_covered_err
1005 # uncoverable condition right count:3 class:ignore_covered_err */
1006 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
1007 2 out = (UV)SvUV(r);
1008 2 *ok = 1;
1009 }
1010 }
1011 2 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 2 0 2
1012 2 return out;
1013 }
1014  
1015 18 static int hm_bsrc_lift(pTHX_ SV *body, hm_bsrc *bs, int has_len, UV clen) {
1016 /*
1017 # uncoverable branch true
1018 # uncoverable condition left count:1 class:ignore_covered_err */
1019 18 ▶ if (!SvROK(body)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(body)) return 0; 0 18 18
1020  
1021 18 ▶ if (sv_isobject(body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sv_isobject(body)) { 6 12 18
1022 6 HV *stash = SvSTASH(SvRV(body));
1023 6 int fd = -1, ok = 0;
1024 /*
1025 # uncoverable branch true
1026 # uncoverable condition left count:1 class:ignore_covered_err */
1027 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
1028 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
1029 3 ▶ if (gv_fetchmethod_autoload(stash, "fileno", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (gv_fetchmethod_autoload(stash, "fileno", 0)) { 2 1 3
1030 2 UV v = hm_bsrc_method_uv(aTHX_ body, "fileno", &ok);
1031 /*
1032 # uncoverable branch false class:ignore_covered_err
1033 # uncoverable condition right count:1 class:ignore_covered_err */
1034 2 ▶ if (ok) fd = (int)v;
Branch: 1 branch
BranchTrueFalseTotal
if (ok) fd = (int)v; 2 0 2
1035 }
1036 3 ▶ if (fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { 2 1 3
1037 struct stat st;
1038 off_t pos;
1039 /*
1040 # uncoverable branch false class:ignore_covered_err
1041 # uncoverable condition right count:1 class:ignore_covered_err
1042 # uncoverable condition right count:2 class:ignore_covered_err
1043 # uncoverable condition right count:3 class:ignore_covered_err */
1044 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
1045 2 ▶ && (pos = lseek(fd, 0, SEEK_CUR)) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& (pos = lseek(fd, 0, SEEK_CUR)) >= 0) { 2 0 2
1046 2 bs->kind = 1;
1047 2 bs->fd = fd;
1048 2 bs->off = pos;
1049 2 bs->remaining = clen;
1050 2 bs->sv = SvREFCNT_inc(body);
1051 2 return 1;
1052 }
1053 }
1054 1 bs->kind = 2;
1055 1 bs->remaining = clen;
1056 1 bs->sv = SvREFCNT_inc(body);
1057 1 return 1;
1058 }
1059  
1060 /*
1061 # uncoverable branch false class:ignore_covered_err
1062 # uncoverable condition right count:1 class:ignore_covered_err
1063 # uncoverable condition left count:2 class:ignore_covered_err
1064 # uncoverable condition right count:2 class:ignore_covered_err */
1065 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
1066 12 IO *io = sv_2io(body);
1067 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
1068 struct stat st;
1069 int fd;
1070 off_t pos;
1071 /*
1072 # uncoverable branch true
1073 # uncoverable condition left count:1 class:ignore_covered_err */
1074 12 ▶ if (!fp) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!fp) return 0; 0 12 12
1075 12 fd = PerlIO_fileno(fp);
1076 /*
1077 # uncoverable condition left count:2 class:ignore_covered_err
1078 # uncoverable condition left count:3 class:ignore_covered_err */
1079 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
1080 11 pos = (off_t)PerlIO_tell(fp);
1081 /*
1082 # uncoverable branch true class:ignore_covered_err
1083 # uncoverable condition left count:1 class:ignore_covered_err
1084 # uncoverable condition left count:2 class:ignore_covered_err */
1085 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
1086 11 bs->kind = 1;
1087 11 bs->fd = fd;
1088 11 bs->off = pos;
1089 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
1090 11 bs->sv = SvREFCNT_inc(body);
1091 11 return 1;
1092 }
1093 0 return 0; /* # uncoverable statement */
1094 }
1095  
1096 /* Close out a source: the PSGI body contract says the server closes the
1097 * handle it was given (hm_slurp_body has always done so). Objects get
1098 * their close method; a glob's PerlIO is closed directly. */
1099 14 static void hm_bsrc_release(pTHX_ hm_bsrc *bs) {
1100 /*
1101 # uncoverable branch true
1102 # uncoverable condition left count:1 class:ignore_covered_err */
1103 14 ▶ if (!bs->kind) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!bs->kind) return; 0 14 14
1104 /*
1105 # uncoverable branch false class:ignore_covered_err
1106 # uncoverable condition right count:1 class:ignore_covered_err */
1107 14 ▶ if (bs->sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (bs->sv) { 14 0 14
1108 14 ▶ if (sv_isobject(bs->sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sv_isobject(bs->sv)) { 3 11 14
1109 /*
1110 # uncoverable branch false class:ignore_covered_err
1111 # uncoverable condition right count:1 class:ignore_covered_err */
1112 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
1113 3 dSP;
1114 3 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 3 3
1115 3 ▶ XPUSHs(bs->sv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(bs->sv); 0 3 3
1116 3 PUTBACK;
1117 3 call_method("close", G_DISCARD | G_EVAL);
1118 3 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 3 0 3
1119 }
1120 }
1121 else {
1122 11 IO *io = sv_2io(bs->sv);
1123 /*
1124 # uncoverable branch false class:ignore_covered_err
1125 # uncoverable condition right count:1 class:ignore_covered_err
1126 # uncoverable condition right count:2 class:ignore_covered_err */
1127 11 ▶ if (io && IoIFP(io)) {
Branch: 2 branches
BranchTrueFalseTotal
if (io && IoIFP(io)) { 11 0 11
if (io && IoIFP(io)) { 11 0 11
1128 11 PerlIO_close(IoIFP(io));
1129 11 IoIFP(io) = NULL;
1130 11 IoOFP(io) = NULL;
1131 }
1132 }
1133 14 SvREFCNT_dec(bs->sv);
1134 }
1135 14 memset(bs, 0, sizeof(*bs));
1136 }
1137  
1138 /* Refill the write buffer with the next chunk of the source. Returns the
1139 * bytes added; 0 when the source is spent; -1 on a source that ended
1140 * early (file truncated under us, getline died or dried up) - the client
1141 * was promised more bytes than it will get, so the connection must not
1142 * be reused. */
1143 45 static ssize_t hm_bsrc_fill(pTHX_ hm_conn *c) {
1144 45 hm_bsrc *bs = &c->bsrc;
1145 45 ▶ if (!bs->remaining) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!bs->remaining) return 0; 1 44 45
1146 44 ▶ if (bs->kind == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (bs->kind == 1) { 1 43 44
1147 1 size_t want = bs->remaining < HM_BSRC_CHUNK
1148 ? (size_t)bs->remaining : HM_BSRC_CHUNK;
1149 ssize_t n;
1150 1 hm_wb_reserve(c, want);
1151 1 n = hm_os_pread(bs->fd, c->wbuf + c->wlen, want, bs->off);
1152 /*
1153 # uncoverable branch true
1154 # uncoverable condition left count:1 class:ignore_covered_err */
1155 1 ▶ if (n <= 0) { c->keepalive = 0; return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { c->keepalive = 0; return -1; } 0 1 1
1156 1 c->wlen += (size_t)n;
1157 1 bs->off += n;
1158 1 bs->remaining -= (UV)n;
1159 1 return n;
1160 }
1161 0 for (;;) { /* kind 2: one getline */ /* # uncoverable statement class:ignore_covered_err */
1162 43 dSP;
1163 SV *chunk;
1164 43 STRLEN l = 0;
1165 43 const char *p = NULL;
1166 int n;
1167 43 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 43 43
1168 43 ▶ XPUSHs(bs->sv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(bs->sv); 0 43 43
1169 43 PUTBACK;
1170 43 n = call_method("getline", G_SCALAR | G_EVAL);
1171 43 SPAGAIN;
1172 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
1173 /*
1174 # uncoverable branch true class:ignore_covered_err
1175 # uncoverable condition left count:1 class:ignore_covered_err
1176 # uncoverable condition left count:2 class:ignore_covered_err
1177 # uncoverable condition left count:3 class:ignore_covered_err */
1178 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
1179 0 ▶ PUTBACK; FREETMPS; LEAVE; /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; /* # uncoverable statement */ 0 0 0
1180 0 c->keepalive = 0; /* remaining > 0 here */ /* # uncoverable statement */
1181 43 return -1; /* # uncoverable statement class:ignore_covered_err */
1182 }
1183 43 p = SvPV(chunk, l);
1184 /*
1185 # uncoverable branch true class:ignore_covered_err
1186 # uncoverable condition left count:1 class:ignore_covered_err */
1187 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
1188 /*
1189 # uncoverable branch false class:ignore_covered_err
1190 # uncoverable condition right count:1 class:ignore_covered_err */
1191 43 ▶ if (l) hm_wb_put(c, p, l);
Branch: 1 branch
BranchTrueFalseTotal
if (l) hm_wb_put(c, p, l); 43 0 43
1192 43 bs->remaining -= (UV)l;
1193 43 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 43 0 43
1194 /*
1195 # uncoverable branch false
1196 # uncoverable condition right count:1 class:ignore_covered_err */
1197 43 ▶ if (l) return (ssize_t)l;
Branch: 1 branch
BranchTrueFalseTotal
if (l) return (ssize_t)l; 43 0 43
1198 /*
1199 # uncoverable statement
1200 # uncoverable branch true
1201 # uncoverable branch false
1202 # uncoverable condition left count:1
1203 # uncoverable condition right count:1 */
1204 0 ▶ if (!bs->remaining) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!bs->remaining) return 0; 0 0 0
1205 /* an empty chunk with bytes still owed: ask again */
1206 }
1207 }
1208  
1209 /* Scan a header AV for Content-Length; fills *out and returns 1 if found. */
1210 21 static int hm_hav_clen(pTHX_ AV *hav, UV *out) {
1211 SSize_t i, n;
1212 /*
1213 # uncoverable branch true
1214 # uncoverable condition left count:1 class:ignore_covered_err */
1215 21 ▶ if (!hav) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!hav) return 0; 0 21 21
1216 21 n = av_len(hav) + 1;
1217 36 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 25 11 36
1218 25 SV **k = av_fetch(hav, i, 0);
1219 STRLEN kl;
1220 const char *ks;
1221 /*
1222 # uncoverable branch true class:ignore_covered_err
1223 # uncoverable condition left count:1 class:ignore_covered_err
1224 # uncoverable condition left count:2 class:ignore_covered_err */
1225 25 ▶ if (!k || !*k) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!k || !*k) continue; 25 0 25
if (!k || !*k) continue; 0 25 25
1226 25 ks = SvPV(*k, kl);
1227 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
1228 10 SV **v = av_fetch(hav, i + 1, 0);
1229 /*
1230 # uncoverable branch false class:ignore_covered_err
1231 # uncoverable condition right count:1 class:ignore_covered_err
1232 # uncoverable condition right count:2 class:ignore_covered_err
1233 # uncoverable condition right count:3 class:ignore_covered_err */
1234 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
1235 /* Digits only. SvUV of "abc" is 0, which selected the
1236 * counted mode with a length of nothing and cut the body
1237 * at its first write; a value that is not a length is
1238 * treated as absent, and the framing chosen without it. */
1239 STRLEN vl, j;
1240 10 const char *vs = SvPV(*v, vl);
1241 /*
1242 # uncoverable branch true class:ignore_covered_err
1243 # uncoverable condition left count:1 class:ignore_covered_err
1244 # uncoverable condition left count:2 class:ignore_covered_err */
1245 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
1246 50 ▶ for (j = 0; j < vl; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < vl; j++) 41 9 50
1247 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
1248 9 *out = (UV)SvUV(*v);
1249 9 return 1;
1250 }
1251 }
1252 }
1253 11 return 0;
1254 }
1255  
1256 /* a [500, [...], [$msg]] PSGI triple (mortal) */
1257 6 static SV *hm_500_resp(pTHX_ const char *msg) {
1258 6 AV *resp = newAV();
1259 6 AV *hdrs = newAV();
1260 6 AV *body = newAV();
1261 6 av_push(hdrs, newSVpvs("Content-Type"));
1262 6 av_push(hdrs, newSVpvs("text/plain"));
1263 6 av_push(body, newSVpv(msg, 0));
1264 6 av_push(resp, newSViv(500));
1265 6 av_push(resp, newRV_noinc((SV *)hdrs));
1266 6 av_push(resp, newRV_noinc((SV *)body));
1267 6 return sv_2mortal(newRV_noinc((SV *)resp));
1268 }
1269  
1270 /* ---- connections --------------------------------------------------------- */
1271  
1272 /* Return a connection struct to the pool, or free it when the pool is full.
1273 * The buffers ride along so the steady state allocates nothing - but only
1274 * at their ordinary sizes. A read buffer grown for a 15MB body, or a write
1275 * buffer grown for one slow client, would otherwise stay that size for as
1276 * long as the pool held the struct, and a thousand of them is the whole
1277 * ceiling resident for nothing. */
1278 934 static void hm_pool_conn(hm_loop *loop, hm_conn *c) {
1279 934 ▶ 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 */ 934 0 934
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 */ 7 927 934
1280 934 ▶ 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; } 878 56 934
if (c->wbuf && c->wcap > HM_WB_KEEP) { free(c->wbuf); c->wbuf = NULL; c->wcap = 0; } 4 874 878
1281 /*
1282 # uncoverable branch false
1283 # uncoverable condition right count:1 class:ignore_covered_err */
1284 934 ▶ if (loop->pool_n < HM_POOL_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->pool_n < HM_POOL_MAX) { 934 0 934
1285 934 c->pool_next = loop->pool;
1286 934 loop->pool = c;
1287 934 loop->pool_n++;
1288 } else {
1289 /*
1290 # uncoverable statement
1291 # uncoverable branch true
1292 # uncoverable branch false
1293 # uncoverable condition left count:1
1294 # uncoverable condition right count:1 */
1295 0 ▶ if (c->wbuf) free(c->wbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->wbuf) free(c->wbuf); 0 0 0
1296 /*
1297 # uncoverable statement
1298 # uncoverable branch true
1299 # uncoverable branch false
1300 # uncoverable condition left count:1
1301 # uncoverable condition right count:1 */
1302 0 ▶ if (c->rbuf) free(c->rbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->rbuf) free(c->rbuf); 0 0 0
1303 0 free(c); /* # uncoverable statement */
1304 }
1305 934 }
1306  
1307 942 static void hm_lru_unlink(hm_loop *loop, hm_conn *c) {
1308 942 ▶ 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; 61 881 942
1309 /*
1310 # uncoverable branch false class:ignore_covered_err
1311 # uncoverable condition right count:1 class:ignore_covered_err */
1312 881 ▶ 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; 881 0 881
1313 942 ▶ 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; 133 809 942
1314 /*
1315 # uncoverable branch false class:ignore_covered_err
1316 # uncoverable condition right count:1 class:ignore_covered_err */
1317 809 ▶ 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; 809 0 809
1318 942 c->lru_prev = c->lru_next = NULL;
1319 942 }
1320  
1321 962 static void hm_lru_touch(hm_loop *loop, hm_conn *c) {
1322 962 c->last_active = loop->now;
1323 962 ▶ if (loop->lru_tail == c) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->lru_tail == c) return; 954 8 962
1324 8 hm_lru_unlink(loop, c);
1325 8 c->lru_prev = loop->lru_tail;
1326 /*
1327 # uncoverable branch false class:ignore_covered_err
1328 # uncoverable condition right count:1 class:ignore_covered_err */
1329 8 ▶ if (loop->lru_tail) loop->lru_tail->lru_next = c;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->lru_tail) loop->lru_tail->lru_next = c; 8 0 8
1330 8 loop->lru_tail = c;
1331 /*
1332 # uncoverable branch true class:ignore_covered_err
1333 # uncoverable condition left count:1 class:ignore_covered_err */
1334 8 ▶ if (!loop->lru_head) loop->lru_head = c;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->lru_head) loop->lru_head = c; 0 8 8
1335 }
1336  
1337 /* ---- completion-mode receive ---------------------------------------------
1338 *
1339 * A readiness backend says "this fd has bytes" and the core reads them. A
1340 * completion backend is asked for the read UP FRONT and hands back bytes that
1341 * are already in the buffer - which is how the read syscall stops being a
1342 * syscall per request and becomes part of one batched submission per turn of
1343 * the loop.
1344 *
1345 * What that costs is that the kernel holds a pointer into c->rbuf for a while,
1346 * and the two things the core does casually with that buffer - GROW it, and
1347 * POOL it for the next connection - both become memory corruption if they
1348 * happen while a read is outstanding. Growth is handled by only ever growing
1349 * before arming (hm_arm_recv). Pooling is handled here.
1350 *
1351 * The identity problem is the other half. A completion can outlive the
1352 * connection that asked for it: hm_close closes the fd, the number is reused
1353 * by a new connection moments later, and the old read lands looking exactly
1354 * like the new one's. So every read carries a token of fd plus the
1355 * connection's generation id, and a completion whose token does not match the
1356 * connection now holding that fd is somebody else's. */
1357  
1358 #define HM_RECV_TOKEN(c) \
1359 (((uint64_t)(c)->id << 17) | (uint64_t)(unsigned)(c)->fd)
1360  
1361 /* A read buffer whose connection is gone but whose kernel read is not. Parked
1362 * under the token the kernel will hand back, and freed when it does. */
1363 typedef struct hm_quar {
1364 uint64_t token;
1365 char *buf;
1366 struct hm_quar *next;
1367 } hm_quar;
1368  
1369 /*
1370 # uncoverable statement
1371 # uncoverable subroutine */
1372 0 static void hm_quar_push(hm_loop *loop, uint64_t token, char *buf) {
1373 hm_quar *q;
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 (!buf) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!buf) return; 0 0 0
1381 0 q = (hm_quar *)malloc(sizeof(hm_quar)); /* # uncoverable statement */
1382 /* Out of memory with a read outstanding: the buffer CANNOT be freed, so
1383 * it is leaked deliberately. One leaked read buffer beats handing the
1384 * kernel a pointer into the heap it no longer owns. */
1385 /*
1386 # uncoverable statement
1387 # uncoverable branch true
1388 # uncoverable branch false
1389 # uncoverable condition left count:1
1390 # uncoverable condition right count:1 */
1391 0 ▶ if (!q) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!q) return; 0 0 0
1392 0 q->token = token; /* # uncoverable statement */
1393 0 q->buf = buf; /* # uncoverable statement */
1394 0 q->next = loop->quar; /* # uncoverable statement */
1395 0 loop->quar = q; /* # uncoverable statement */
1396 }
1397  
1398 /*
1399 # uncoverable statement
1400 # uncoverable subroutine */
1401 0 static void hm_quar_release(hm_loop *loop, uint64_t token) {
1402 0 hm_quar **pp = &loop->quar, *q; /* # uncoverable statement */
1403 /*
1404 # uncoverable statement
1405 # uncoverable branch true
1406 # uncoverable branch false
1407 # uncoverable condition left count:1
1408 # uncoverable condition right count:1 */
1409 0 ▶ while ((q = *pp)) {
Branch: 1 branch
BranchTrueFalseTotal
while ((q = *pp)) { 0 0 0
1410 /*
1411 # uncoverable statement
1412 # uncoverable branch true
1413 # uncoverable branch false
1414 # uncoverable condition left count:1
1415 # uncoverable condition right count:1 */
1416 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
1417 0 pp = &q->next; /* # uncoverable statement */
1418 }
1419 }
1420  
1421 171 static void hm_quar_free_all(hm_loop *loop) {
1422 171 hm_quar *q = loop->quar, *n;
1423 /*
1424 # uncoverable branch true class:ignore_covered_err
1425 # uncoverable condition left count:1 class:ignore_covered_err */
1426 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
1427 171 loop->quar = NULL;
1428 171 }
1429  
1430 /* Ask for this connection's next read. 1 if one is now outstanding, 0 if the
1431 * caller must fall back to a readiness watcher - which is always correct, so
1432 * every refusal here is a performance decision and never a correctness one. */
1433 862 static int hm_arm_recv(hm_loop *loop, hm_conn *c) {
1434 size_t want;
1435 /*
1436 # uncoverable branch false class:ignore_covered_err
1437 # uncoverable condition right count:1 class:ignore_covered_err
1438 # uncoverable condition left count:2 class:ignore_covered_err
1439 # uncoverable condition right count:2 class:ignore_covered_err */
1440 862 ▶ if (!loop->completion || !loop->be->submit_recv) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!loop->completion || !loop->be->submit_recv) return 0; 0 862 862
if (!loop->completion || !loop->be->submit_recv) return 0; 0 0 0
1441 /* TLS reads belong to OpenSSL: the bytes on the socket are ciphertext and
1442 * the engine may already hold plaintext this would never see. */
1443 /*
1444 # uncoverable statement
1445 # uncoverable branch true
1446 # uncoverable branch false
1447 # uncoverable condition left count:1
1448 # uncoverable condition right count:1
1449 # uncoverable condition left count:2
1450 # uncoverable condition right count:2
1451 # uncoverable condition left count:3
1452 # uncoverable condition right count:3
1453 # uncoverable condition left count:4
1454 # uncoverable condition right count:4 */
1455 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
1456 /*
1457 # uncoverable statement
1458 # uncoverable branch true
1459 # uncoverable branch false
1460 # uncoverable condition left count:1
1461 # uncoverable condition right count:1 */
1462 0 ▶ if (c->rlen == c->rcap) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen == c->rcap) { 0 0 0
1463 /* Grow BEFORE the kernel is given the pointer. Never while a read is
1464 * outstanding, which is why this cannot live in the completion. */
1465 size_t ncap;
1466 /*
1467 # uncoverable statement
1468 # uncoverable branch true
1469 # uncoverable branch false
1470 # uncoverable condition left count:1
1471 # uncoverable condition right count:1 */
1472 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
1473 * the oversize/413 answer */
1474 0 ncap = c->rcap * 2; /* # 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 (ncap > loop->max_read) ncap = loop->max_read;
Branch: 1 branch
BranchTrueFalseTotal
if (ncap > loop->max_read) ncap = loop->max_read; 0 0 0
1482 0 c->rbuf = (char *)hm_xrealloc(c->rbuf, ncap); /* # uncoverable statement */
1483 0 c->rcap = ncap; /* # uncoverable statement */
1484 }
1485 0 want = c->rcap - c->rlen; /* # uncoverable statement */
1486 /*
1487 # uncoverable statement
1488 # uncoverable branch true
1489 # uncoverable branch false
1490 # uncoverable condition left count:1
1491 # uncoverable condition right count:1 */
1492 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
1493 0 HM_RECV_TOKEN(c)) != 0) /* # uncoverable statement */
1494 0 return 0; /* # uncoverable statement */
1495 0 c->recv_inflight = 1; /* # uncoverable statement */
1496 0 return 1; /* # uncoverable statement */
1497 }
1498  
1499 static int hm_read_lend(hm_loop *loop, hm_conn *c);
1500 static void hm_read_unlend(hm_loop *loop, hm_conn *c);
1501  
1502 /* Requests are waiting in rbuf behind a park, a streamed body or a full write
1503 * buffer, and whoever serves them will memmove the buffer down. A completion
1504 * armed now holds rbuf + rlen, and after the move it lands past the new rlen
1505 * while rlen counts it from the front: the parser re-reads the tail of the
1506 * request it already served and waits for the rest of it until the idle
1507 * sweep. (t/27 on every Linux smoker with liburing: the request after a
1508 * pipelined one behind a sendfile body was never read.) */
1509 /*
1510 # uncoverable statement
1511 # uncoverable subroutine */
1512 0 static int hm_recv_unsafe(hm_conn *c) {
1513 0 return c->rlen > 0 /* # uncoverable statement */
1514 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
1515 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
1516 }
1517  
1518 /* Arm the next read however this connection reads: a completion if it can,
1519 * a readiness watcher otherwise. */
1520 871 static void hm_rearm_read(hm_loop *loop, hm_conn *c) {
1521 /* A readiness read happens at rlen as it stands at the time, so it is
1522 * safe across the move; given back once the buffer has been served. */
1523 /*
1524 # uncoverable branch true class:ignore_covered_err
1525 # uncoverable condition left count:1 class:ignore_covered_err */
1526 871 ▶ if (c->recv_lent) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_lent) { 0 871 871
1527 /*
1528 # uncoverable statement
1529 # uncoverable branch true
1530 # uncoverable branch false
1531 # uncoverable condition left count:1
1532 # uncoverable condition right count:1 */
1533 0 ▶ if (hm_recv_unsafe(c)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_recv_unsafe(c)) return; 0 0 0
1534 0 hm_read_unlend(loop, c); /* # uncoverable statement */
1535 0 c->recv_lent = 0; /* # uncoverable statement */
1536 }
1537 /* Already reading off readiness: the watcher is persistent and
1538 * level-triggered, so re-adding it would be a syscall per response on
1539 * epoll for no effect at all. */
1540 871 ▶ if (c->recv_fallback) return;
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_fallback) return; 9 862 871
1541 /* A read is already outstanding: the kernel holds rbuf + rlen and will
1542 * complete into it. A readiness watcher added now would read the same
1543 * bytes into the same offset first. hm_arm_recv refuses for the same
1544 * reason, but its refusal is not a request to fall back. */
1545 /*
1546 # uncoverable branch true
1547 # uncoverable condition left count:1 class:ignore_covered_err */
1548 862 ▶ if (c->recv_inflight) return;
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_inflight) return; 0 862 862
1549 /*
1550 # uncoverable branch true class:ignore_covered_err
1551 # uncoverable condition left count:1 class:ignore_covered_err
1552 # uncoverable condition left count:2 class:ignore_covered_err
1553 # uncoverable condition right count:2 class:ignore_covered_err */
1554 862 ▶ if (loop->completion && hm_recv_unsafe(c)) {
Branch: 2 branches
BranchTrueFalseTotal
if (loop->completion && hm_recv_unsafe(c)) { 0 862 862
if (loop->completion && hm_recv_unsafe(c)) { 0 0 0
1555 /*
1556 # uncoverable statement
1557 # uncoverable branch true
1558 # uncoverable branch false
1559 # uncoverable condition left count:1
1560 # uncoverable condition right count:1 */
1561 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
1562 0 return; /* # uncoverable statement */
1563 }
1564 /*
1565 # uncoverable branch true
1566 # uncoverable condition left count:1 class:ignore_covered_err */
1567 862 ▶ if (hm_arm_recv(loop, c)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_arm_recv(loop, c)) return; 0 862 862
1568 862 c->recv_fallback = 1;
1569 862 loop->be->add_io(loop->be, c->fd, HM_EV_READ, 0);
1570 }
1571  
1572 /* Lend a completion-mode connection a readiness watcher for as long as an
1573 * application call that may wait on it is on the stack: an HTTP/2 handler
1574 * waiting for its body to drain is waiting for window updates on this very
1575 * socket. No completion is outstanding then - HM_EV_RECV re-arms only after
1576 * hm_process returns, and arming one under it would let the kernel write into
1577 * a buffer nghttp2 is consuming - so without the watcher the handler pumps a
1578 * loop that never reads its connection. 1 if lent. */
1579 0 static int hm_read_lend(hm_loop *loop, hm_conn *c) {
1580 /*
1581 # uncoverable branch false class:ignore_covered_err
1582 # uncoverable condition right count:1 class:ignore_covered_err
1583 # uncoverable condition left count:2 class:ignore_covered_err
1584 # uncoverable condition right count:2 class:ignore_covered_err
1585 # uncoverable condition left count:3 class:ignore_covered_err
1586 # uncoverable condition right count:3 class:ignore_covered_err */
1587 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
1588 0 c->recv_fallback = 1; /* # uncoverable statement */
1589 0 loop->be->add_io(loop->be, c->fd, HM_EV_READ, 0); /* # uncoverable statement */
1590 0 return 1; /* # uncoverable statement */
1591 }
1592  
1593 /* And take it back: the caller's hm_rearm_read returns it to completion. */
1594 /*
1595 # uncoverable statement
1596 # uncoverable subroutine */
1597 0 static void hm_read_unlend(hm_loop *loop, hm_conn *c) {
1598 /*
1599 # uncoverable statement
1600 # uncoverable branch true
1601 # uncoverable branch false
1602 # uncoverable condition left count:1
1603 # uncoverable condition right count:1 */
1604 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
1605 0 c->read_paused = 0; /* # uncoverable statement */
1606 0 c->recv_fallback = 0; /* # uncoverable statement */
1607 0 }
1608  
1609 931 static void hm_close(pTHX_ hm_loop *loop, hm_conn *c) {
1610 /* A synchronous handler for this connection is on the stack: its ->get
1611 * pumped this loop and the loop found the peer gone, or the sweep found
1612 * it idle. The frame that called the app still holds c and will finish
1613 * with it (hm_process's consumed/memmove, hm_queue_response), so the
1614 * struct cannot be pooled - the next accept would hand it to a new
1615 * client and the first client's response would land on the second's
1616 * socket. Stop reading, mark it, and let that frame close it. */
1617 931 ▶ if (c->in_app) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->in_app) { 1 930 931
1618 /*
1619 # uncoverable branch false class:ignore_covered_err
1620 # uncoverable condition right count:1 class:ignore_covered_err */
1621 1 ▶ if (!c->close_deferred) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->close_deferred) { 1 0 1
1622 1 c->close_deferred = 1;
1623 1 loop->be->remove_io(loop->be, c->fd,
1624 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
1625 1 c->writing = 0;
1626 }
1627 1 return;
1628 }
1629 /* Stream handles open on this connection die with it. They are told
1630 * first, while the connection is still consistent, and they are only
1631 * marked dead - the handle itself belongs to whoever opened it until
1632 * it calls stream_close. */
1633 930 ▶ 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 918 930
1634 /* Before anything else touches the buffers: if the kernel is still
1635 * holding a pointer into this connection's read buffer, take the buffer
1636 * away from the connection so the pooling below cannot hand it to the
1637 * next one. The connection is pooled with a NULL rbuf and hm_new_conn
1638 * allocates a fresh one. */
1639 /* c is never NULL here - every caller passes a live connection, and this
1640 * function dereferences it unconditionally a few lines down. The `c &&`
1641 * these two guards used to carry was dead, and it told a static analyser
1642 * the opposite of the truth: cppcheck reported four null dereferences
1643 * from it, all of them the guard's fault rather than the code's. */
1644 /*
1645 # uncoverable branch true class:ignore_covered_err
1646 # uncoverable condition left count:1 class:ignore_covered_err */
1647 930 ▶ if (c->recv_inflight) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->recv_inflight) { 0 930 930
1648 /*
1649 # uncoverable statement
1650 # uncoverable branch true
1651 # uncoverable branch false
1652 # uncoverable condition left count:1
1653 # uncoverable condition right count:1 */
1654 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
1655 0 hm_quar_push(loop, HM_RECV_TOKEN(c), c->rbuf); /* # uncoverable statement */
1656 0 c->rbuf = NULL; /* # uncoverable statement */
1657 0 c->rcap = 0; /* # uncoverable statement */
1658 0 c->rlen = 0; /* # uncoverable statement */
1659 0 c->recv_inflight = 0; /* # uncoverable statement */
1660 }
1661 930 ▶ 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 929 930
1662 1 PerlLIO_close(c->spill_fd);
1663 1 c->spill_fd = -1;
1664 1 c->spill_got = 0;
1665 }
1666 930 int fd = c->fd;
1667 930 SV *pending = c->resp_f; /* cancelled below, once state is consistent */
1668 930 c->resp_f = NULL;
1669 930 ▶ 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 929 930
1670 930 ▶ 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 929 930
1671 930 ▶ if (c->ssl) hm_tls_conn_free(c);
Branch: 1 branch
BranchTrueFalseTotal
if (c->ssl) hm_tls_conn_free(c); 61 869 930
1672 930 hm_os_close(fd);
1673 930 hm_lru_unlink(loop, c);
1674 930 loop->conns[fd] = NULL;
1675 930 loop->nconns--;
1676 930 ▶ 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; } 810 120 930
1677 930 ▶ 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; } 810 120 930
1678 /*
1679 # uncoverable branch true class:ignore_covered_err
1680 # uncoverable condition left count:1 class:ignore_covered_err */
1681 930 ▶ 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 930 930
1682 930 ▶ 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; } 808 122 930
1683 930 ▶ 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; } 808 122 930
1684 930 ▶ 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; } 808 122 930
1685 930 ▶ 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; } 810 120 930
1686 930 ▶ 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; } 810 120 930
1687 /* Detached from the connection BEFORE it is torn down: freeing the
1688 * session cancels every stream's parked Future, and a continuation
1689 * that fires on that cancel looks the stream up through c->h2. */
1690 930 ▶ 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 930 930
1691 930 hm_pool_conn(loop, c);
1692 930 ▶ 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 929 930
if (loop->stopping && loop->nconns == 0) loop->stop = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
1693 /* client went away while awaiting: cancel the response Future so
1694 * in-flight async work can abort (propagates up the then-chain) */
1695 930 ▶ if (pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (pending) { 1 929 930
1696 1 dSP;
1697 1 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 1 1
1698 1 ▶ XPUSHs(pending);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(pending); 0 1 1
1699 1 PUTBACK;
1700 1 call_method("cancel", G_DISCARD | G_EVAL);
1701 1 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 1 0 1
1702 1 SvREFCNT_dec(pending);
1703 }
1704 }
1705  
1706 /* ---- detach: hand a live HTTP/1 connection to the application ------------ *
1707 * The seam a protocol upgrade (WebSocket) needs: the socket stays open and
1708 * becomes the app's, while the server forgets it entirely so the app's own
1709 * io watchers on that fd fire (hm_dispatch routes to loop->io_r/io_w only
1710 * when conns[fd] is NULL).
1711 *
1712 * Two phases, because the callers of the app frame keep using the conn after
1713 * it returns (hm_process's consumed/memmove, hm_deliver's flush):
1714 *
1715 * hm_detach - immediate: validate, disarm the server's watchers so
1716 * no further bytes are pulled in, flag the conn.
1717 * hm_conn_release - deferred: hm_close minus the close(2) and minus the
1718 * watcher removal, run once the caller is done with the
1719 * conn. After it, conns[fd] is NULL and the fd is the
1720 * application's to own and to close.
1721 *
1722 * The app must not have produced any response bytes for this request, and
1723 * returns a sentinel (conventionally [101, [], []]) which is discarded. */
1724 10 static int hm_detach(pTHX_ hm_loop *loop, int fd, UV id) {
1725 hm_conn *c;
1726 #ifdef _WIN32
1727 /* The fd is a CRT wrapper around a SOCKET (hm_win.h). Handing that to
1728 * perl's IO layer to own, after this server stops watching it, has not
1729 * been proven on a real Windows box - so it is refused rather than
1730 * half-supported. A WebSocket tier over this server falls back to
1731 * psgi.streaming, which is its documented second transport. */
1732 (void)loop; (void)fd; (void)id; (void)c;
1733 return -6;
1734 #else
1735 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
1736 9 c = loop->conns[fd];
1737 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
1738 /*
1739 # uncoverable branch true
1740 # uncoverable condition left count:1 class:ignore_covered_err */
1741 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
1742 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
1743 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
1744 7 ▶ || c->bsrc.kind) return -4; /* output still draining */
Branch: 1 branch
BranchTrueFalseTotal
|| c->bsrc.kind) return -4; /* output still draining */ 0 6 6
1745 6 ▶ if (c->detached) return -5; /* already handed over */
Branch: 1 branch
BranchTrueFalseTotal
if (c->detached) return -5; /* already handed over */ 2 4 6
1746 4 loop->be->remove_io(loop->be, fd,
1747 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
1748 4 c->writing = 0;
1749 4 c->detached = 1;
1750 4 return 0;
1751 #endif
1752 }
1753  
1754 /* Deferred half of hm_detach: forget the connection without closing its fd. */
1755 4 static void hm_conn_release(pTHX_ hm_loop *loop, hm_conn *c) {
1756 4 int fd = c->fd;
1757 4 SV *pending = c->resp_f;
1758 /* The fd survives, the connection object does not: a handle naming it
1759 * is as dead as it would be after a close. */
1760 /*
1761 # uncoverable branch true class:ignore_covered_err
1762 # uncoverable condition left count:1 class:ignore_covered_err */
1763 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
1764 4 c->resp_f = NULL; /* # uncoverable statement class:ignore_covered_err */
1765 /*
1766 # uncoverable statement class:ignore_covered_err
1767 # uncoverable branch true
1768 # uncoverable condition left count:1 */
1769 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
1770 4 hm_lru_unlink(loop, c);
1771 4 loop->conns[fd] = NULL;
1772 4 loop->nconns--;
1773 /*
1774 # uncoverable branch false class:ignore_covered_err
1775 # uncoverable condition right count:1 class:ignore_covered_err */
1776 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
1777 /*
1778 # uncoverable branch false class:ignore_covered_err
1779 # uncoverable condition right count:1 class:ignore_covered_err */
1780 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
1781 /*
1782 # uncoverable branch true class:ignore_covered_err
1783 # uncoverable condition left count:1 class:ignore_covered_err */
1784 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
1785 /*
1786 # uncoverable branch false class:ignore_covered_err
1787 # uncoverable condition right count:1 class:ignore_covered_err */
1788 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
1789 /*
1790 # uncoverable branch false class:ignore_covered_err
1791 # uncoverable condition right count:1 class:ignore_covered_err */
1792 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
1793 /*
1794 # uncoverable branch false class:ignore_covered_err
1795 # uncoverable condition right count:1 class:ignore_covered_err */
1796 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
1797 /*
1798 # uncoverable branch false class:ignore_covered_err
1799 # uncoverable condition right count:1 class:ignore_covered_err */
1800 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
1801 /*
1802 # uncoverable branch false class:ignore_covered_err
1803 # uncoverable condition right count:1 class:ignore_covered_err */
1804 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
1805 4 hm_pool_conn(loop, c);
1806 /*
1807 # uncoverable branch true class:ignore_covered_err
1808 # uncoverable condition left count:1 class:ignore_covered_err
1809 # uncoverable condition left count:2 class:ignore_covered_err
1810 # uncoverable condition right count:2 class:ignore_covered_err */
1811 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
1812 /* the request's own Future, if any, is simply dropped - the app owns
1813 * the socket now, so there is nothing left to cancel it for */
1814 /*
1815 # uncoverable statement class:ignore_covered_err
1816 # uncoverable branch true
1817 # uncoverable condition left count:1 */
1818 4 ▶ if (pending) SvREFCNT_dec(pending);
Branch: 1 branch
BranchTrueFalseTotal
if (pending) SvREFCNT_dec(pending); 0 4 4
1819 4 }
1820  
1821 935 static hm_conn *hm_new_conn(hm_loop *loop, int fd, hm_listener *lst) {
1822 hm_conn *c;
1823 935 ▶ if (loop->pool) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->pool) { 794 141 935
1824 char *wbuf, *rbuf; size_t wcap, rcap;
1825 794 c = loop->pool;
1826 794 loop->pool = c->pool_next;
1827 794 loop->pool_n--;
1828 794 wbuf = c->wbuf; wcap = c->wcap; /* keep the buffers */
1829 794 rbuf = c->rbuf; rcap = c->rcap;
1830 794 memset(c, 0, sizeof(*c));
1831 794 c->wbuf = wbuf; c->wcap = wcap;
1832 794 c->rbuf = rbuf; c->rcap = rcap;
1833 } else {
1834 141 c = (hm_conn *)hm_xcalloc(1, sizeof(hm_conn));
1835 }
1836 935 ▶ if (!c->rbuf) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->rbuf) { 147 788 935
1837 147 c->rbuf = (char *)hm_xmalloc(HM_RBUF);
1838 147 c->rcap = HM_RBUF;
1839 }
1840 935 c->fd = fd;
1841 935 c->keepalive = 1;
1842 935 c->spill_fd = -1; /* 0 is a real fd; the zeroed struct is not
1843 * "not spilling" without this */
1844 935 c->spill_got = 0;
1845 935 c->id = ++hm_id_counter;
1846 935 c->loop = loop;
1847 935 c->lst = lst;
1848 935 c->last_active = loop->now;
1849 935 loop->conns[fd] = c;
1850 935 loop->nconns++;
1851 #ifndef HM_HAVE_ACCEPT4
1852 hm_set_nonblock(fd); /* accept4 did it where there is one */
1853 #endif
1854 935 ▶ 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 */ 935 0 935
if (!(lst && lst->is_unix)) { /* # uncoverable condition left count:1 class:ignore_covered_err */ 933 2 935
1855 933 int one = 1;
1856 933 hm_os_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
1857 }
1858 935 ▶ 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 */ 935 0 935
if (lst && lst->proxy_protocol) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 14 921 935
1859 /* The PROXY header comes first, on the raw socket, before TLS can
1860 * wrap it and before any request byte is read. Readiness reads for
1861 * life (recv_fallback), the header-phase timeout from now, and no
1862 * TLS until hm_proxy_readable has the client's address. */
1863 14 c->pp_wait = 1;
1864 14 c->recv_fallback = 1;
1865 14 c->req_start = loop->now;
1866 14 loop->be->add_io(loop->be, fd, HM_EV_READ, 0);
1867 }
1868 921 ▶ 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 */ 921 0 921
else if (lst && lst->tls_ctx) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 60 861 921
1869 /* TLS wraps first: the handshake is driven off readiness, and
1870 * hm_arm_recv would decline a TLS connection anyway. The handshake
1871 * is timed as a request header is (req_start): a peer that opens a
1872 * socket and never finishes its ClientHello was holding a slot for
1873 * idle_timeout. A wrap that fails (SSL_new under memory pressure)
1874 * closes rather than serving plaintext on a TLS listener. */
1875 60 c->req_start = loop->now;
1876 /*
1877 # uncoverable branch true
1878 # uncoverable condition left count:1 class:ignore_covered_err */
1879 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
1880 0 hm_errlog("Hyperman: TLS setup failed for a new connection; closed\n"); /* # uncoverable statement */
1881 0 c->tls_failed = 1; /* hm_accept closes it, with aTHX */ /* # uncoverable statement */
1882 } else {
1883 60 loop->be->add_io(loop->be, fd, HM_EV_READ, 0);
1884 }
1885 }
1886 861 else hm_rearm_read(loop, c);
1887 /* append to LRU tail */
1888 935 c->lru_prev = loop->lru_tail;
1889 935 ▶ if (loop->lru_tail) loop->lru_tail->lru_next = c;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->lru_tail) loop->lru_tail->lru_next = c; 149 786 935
1890 935 loop->lru_tail = c;
1891 935 ▶ if (!loop->lru_head) loop->lru_head = c;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->lru_head) loop->lru_head = c; 786 149 935
1892 935 return c;
1893 }
1894  
1895 /* ---- HTTP parse ---------------------------------------------------------- */
1896  
1897 /* Find a request header's value in the header block (case-insensitive name).
1898 * Returns a pointer to the (trimmed) value and sets *vlen, or NULL. */
1899 417 static const char *hm_find_header(const char *head, size_t headlen,
1900 const char *name, size_t nlen, size_t *vlen) {
1901 417 const char *p = (const char *)memchr(head, '\n', headlen); /* skip req line */
1902 417 const char *hend = head + headlen;
1903 /*
1904 # uncoverable branch true
1905 # uncoverable condition left count:1 class:ignore_covered_err */
1906 417 ▶ if (!p) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return NULL; 0 417 417
1907 417 p++;
1908 1359 ▶ while (p < hend) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < hend) { 962 397 1359
1909 962 const char *eol = (const char *)memchr(p, '\r', hend - p);
1910 962 ▶ 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); 558 404 962
1911 962 const char *colon = (const char *)memchr(p, ':', len);
1912 962 ▶ if (colon && (size_t)(colon - p) == nlen
Branch: 2 branches
BranchTrueFalseTotal
if (colon && (size_t)(colon - p) == nlen 962 0 962
if (colon && (size_t)(colon - p) == nlen 40 922 962
1913 40 ▶ && hm_strncasecmp(p, name, nlen) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(p, name, nlen) == 0) { 20 20 40
1914 20 const char *v = colon + 1;
1915 20 size_t vl = (size_t)((p + len) - v);
1916 /*
1917 # uncoverable condition right count:1 class:ignore_covered_err
1918 # uncoverable condition left count:3 class:ignore_covered_err */
1919 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
1920 /*
1921 # uncoverable branch true
1922 # uncoverable condition left count:1 class:ignore_covered_err
1923 # uncoverable condition right count:1 class:ignore_covered_err
1924 # uncoverable condition left count:2 class:ignore_covered_err
1925 # uncoverable condition left count:3 class:ignore_covered_err */
1926 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
1927 20 *vlen = vl;
1928 20 return v;
1929 }
1930 942 ▶ p = eol ? eol + 2 : hend;
Branch: 1 branch
BranchTrueFalseTotal
p = eol ? eol + 2 : hend; 545 397 942
1931 }
1932 397 return NULL;
1933 }
1934  
1935 /* Is "trailers" one of the t-codings in a TE value? The value is a
1936 * comma-separated list, each member a token with optional ;parameters and
1937 * optional whitespace, so each token is compared whole and without regard
1938 * to case. "x-trailers" or "trailersx" is a different token. */
1939 0 static int hm_te_names_trailers(const char *v, size_t vl) {
1940 0 size_t i = 0;
1941 0 ▶ while (i < vl) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < vl) { 0 0 0
1942 size_t start;
1943 0 ▶ while (i < vl && (v[i] == ' ' || v[i] == '\t' || v[i] == ',')) i++;
Branch: 4 branches
BranchTrueFalseTotal
while (i < vl && (v[i] == ' ' || v[i] == '\t' || v[i] == ',')) i++; 0 0 0
while (i < vl && (v[i] == ' ' || v[i] == '\t' || v[i] == ',')) i++; 0 0 0
while (i < vl && (v[i] == ' ' || v[i] == '\t' || v[i] == ',')) i++; 0 0 0
while (i < vl && (v[i] == ' ' || v[i] == '\t' || v[i] == ',')) i++; 0 0 0
1944 0 start = i;
1945 0 ▶ while (i < vl && v[i] != ',' && v[i] != ';' && v[i] != ' ' && v[i] != '\t') i++;
Branch: 5 branches
BranchTrueFalseTotal
while (i < vl && v[i] != ',' && v[i] != ';' && v[i] != ' ' && v[i] != '\t') i++; 0 0 0
while (i < vl && v[i] != ',' && v[i] != ';' && v[i] != ' ' && v[i] != '\t') i++; 0 0 0
while (i < vl && v[i] != ',' && v[i] != ';' && v[i] != ' ' && v[i] != '\t') i++; 0 0 0
while (i < vl && v[i] != ',' && v[i] != ';' && v[i] != ' ' && v[i] != '\t') i++; 0 0 0
while (i < vl && v[i] != ',' && v[i] != ';' && v[i] != ' ' && v[i] != '\t') i++; 0 0 0
1946 0 ▶ if (i - start == 8 && hm_strncasecmp(v + start, "trailers", 8) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (i - start == 8 && hm_strncasecmp(v + start, "trailers", 8) == 0) 0 0 0
if (i - start == 8 && hm_strncasecmp(v + start, "trailers", 8) == 0) 0 0 0
1947 0 return 1;
1948 0 ▶ while (i < vl && v[i] != ',') i++;
Branch: 2 branches
BranchTrueFalseTotal
while (i < vl && v[i] != ',') i++; 0 0 0
while (i < vl && v[i] != ',') i++; 0 0 0
1949 }
1950 0 return 0;
1951 }
1952  
1953 /* case-insensitive substring search */
1954 9 static int hm_ci_contains(const char *hay, size_t hl, const char *needle) {
1955 9 size_t nl = strlen(needle), i;
1956 /*
1957 # uncoverable branch true
1958 # uncoverable condition left count:1 class:ignore_covered_err */
1959 9 ▶ if (nl > hl) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (nl > hl) return 0; 0 9 9
1960 36 ▶ for (i = 0; i + nl <= hl; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + nl <= hl; i++) 27 9 36
1961 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
1962 9 return 0;
1963 }
1964  
1965 /* ---- Expect: 100-continue (RFC 9110 10.1.1) -------------------------------
1966 * A client that expects to send a large body may ask permission first and
1967 * wait for an interim 100 before spending the upload. A server that never
1968 * answers does not break such a client - it stalls it, for however long the
1969 * client is prepared to wait (a second, in curl and in most of the Java
1970 * clients) on every request. So the answer is worth having for its own sake,
1971 * and the refusals are worth having more: a body over max_body is refused
1972 * here, on the headers, rather than after the client has sent it all.
1973 */
1974 #define HM_EXPECT_NONE 0
1975 #define HM_EXPECT_CONTINUE 1
1976 #define HM_EXPECT_OTHER 2
1977  
1978 /* The request line's HTTP version. Only "is it 1.1" is asked: 100-continue
1979 * is an HTTP/1.1 expectation and a 1.0 client's Expect MUST be ignored. */
1980 945 static int hm_req_is_11(const char *head, size_t headlen) {
1981 945 const char *eol = (const char *)memchr(head, '\r', headlen);
1982 945 ▶ size_t ll = eol ? (size_t)(eol - head) : headlen;
Branch: 1 branch
BranchTrueFalseTotal
size_t ll = eol ? (size_t)(eol - head) : headlen; 716 229 945
1983 945 ▶ 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 */ 945 0 945
return ll >= 8 && memcmp(head + ll - 8, "HTTP/1.1", 8) == 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 417 528 945
1984 }
1985  
1986 /* Classify the Expect field. The value is a list, and 100-continue is the
1987 * only member this server understands, so anything else - including
1988 * 100-continue with something else beside it - is an expectation it cannot
1989 * meet and earns a 417 rather than a silent promise it will not keep. */
1990 945 static int hm_expectation(const char *head, size_t headlen) {
1991 945 size_t vl = 0;
1992 const char *v;
1993 945 ▶ 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; 528 417 945
1994 417 v = hm_find_header(head, headlen, "expect", 6, &vl);
1995 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
1996 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
1997 18 return HM_EXPECT_CONTINUE;
1998 2 return HM_EXPECT_OTHER;
1999 }
2000  
2001 /* Send the interim response, once per request. Called only where the headers
2002 * have been accepted AND the body is not all here yet: a request already
2003 * carrying its whole body is answered with its final status instead, which
2004 * RFC 9110 allows and every client handles, and a request that is going to
2005 * be refused is refused before this is ever reached. */
2006 48 static void hm_send_continue(hm_conn *c, int expect) {
2007 static const char cont[] = "HTTP/1.1 100 Continue\r\n\r\n";
2008 48 ▶ if (expect != HM_EXPECT_CONTINUE || c->cont_sent) return;
Branch: 2 branches
BranchTrueFalseTotal
if (expect != HM_EXPECT_CONTINUE || c->cont_sent) return; 10 38 48
if (expect != HM_EXPECT_CONTINUE || c->cont_sent) return; 5 5 10
2009 5 c->cont_sent = 1;
2010 5 hm_wb_put(c, cont, sizeof(cont) - 1);
2011 }
2012  
2013 /* Percent-decode a path once (RFC 3875 PATH_INFO): %XX only, no '+'. */
2014 882 static SV *hm_pct_decode(pTHX_ const char *p, STRLEN n) {
2015 882 SV *sv = newSV(n + 1);
2016 882 char *d = SvPVX(sv);
2017 882 STRLEN i = 0, o = 0;
2018 882 SvPOK_on(sv);
2019 3650 ▶ while (i < n) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < n) { 2768 882 3650
2020 2768 ▶ 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 2757 2768
if (p[i] == '%' && i + 2 < n /* # uncoverable condition right count:4 class:ignore_covered_err */ 10 1 11
2021 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
2022 9 int hi = p[i+1], lo = p[i+2];
2023 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
2024 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
2025 9 d[o++] = (char)((hi << 4) | lo);
2026 9 i += 3;
2027 } else {
2028 2759 d[o++] = p[i++];
2029 }
2030 }
2031 882 d[o] = 0;
2032 882 SvCUR_set(sv, o);
2033 882 return sv;
2034 }
2035  
2036 /* ---- $env fast path ------------------------------------------------------
2037 * The fixed $env keys as shared-string SVs: the hash is computed once and
2038 * cached in the shared string table, so hv_store_ent skips both the hashing
2039 * and the key copy on every request. Values that never vary per process
2040 * ([1,1], the 0/1 flags, psgi.errors) are read-only singletons shared by
2041 * refcount; per-connection constants (REMOTE_*, SERVER_*) are cached on the
2042 * connection. Anything a middleware conventionally assigns in place
2043 * (psgi.url_scheme, SCRIPT_NAME, PATH_INFO) stays a fresh SV per request. */
2044  
2045 enum {
2046 HMK_REQUEST_METHOD, HMK_REQUEST_URI, HMK_PATH_INFO, HMK_QUERY_STRING,
2047 HMK_SERVER_PROTOCOL, HMK_SCRIPT_NAME, HMK_SERVER_NAME, HMK_SERVER_PORT,
2048 HMK_REMOTE_ADDR, HMK_REMOTE_HOST, HMK_REMOTE_PORT,
2049 HMK_PSGI_VERSION, HMK_PSGI_URL_SCHEME, HMK_PSGI_MULTITHREAD,
2050 HMK_PSGI_MULTIPROCESS, HMK_PSGI_RUN_ONCE, HMK_PSGI_STREAMING,
2051 HMK_PSGI_NONBLOCKING, HMK_PSGI_ERRORS, HMK_PSGIX_LOOP, HMK_PSGIX_IO,
2052 HMK_PSGI_INPUT, HMK_PSGIX_INPUT_BUFFERED, HMK_CONTENT_LENGTH,
2053 HMK_CONTENT_TYPE, HMK_PSGIX_HM_CONN, HMK_PSGIX_HM_STREAM, HMK_PSGIX_PROXY_ADDR,
2054 HMK_COUNT
2055 };
2056 static const char *const hm_env_key_name[HMK_COUNT] = {
2057 "REQUEST_METHOD", "REQUEST_URI", "PATH_INFO", "QUERY_STRING",
2058 "SERVER_PROTOCOL", "SCRIPT_NAME", "SERVER_NAME", "SERVER_PORT",
2059 "REMOTE_ADDR", "REMOTE_HOST", "REMOTE_PORT",
2060 "psgi.version", "psgi.url_scheme", "psgi.multithread",
2061 "psgi.multiprocess", "psgi.run_once", "psgi.streaming",
2062 "psgi.nonblocking", "psgi.errors", "psgix.loop", "psgix.io",
2063 "psgi.input", "psgix.input.buffered", "CONTENT_LENGTH",
2064 "CONTENT_TYPE", "psgix.hyperman.conn", "psgix.hyperman.stream",
2065 "psgix.proxy_addr"
2066 };
2067 static SV *hm_env_key[HMK_COUNT];
2068 static SV *hm_env_zero, *hm_env_one; /* read-only 0/1 flag values */
2069 static SV *hm_env_version; /* read-only [1,1] */
2070 static SV *hm_env_errors; /* read-only \*STDERR */
2071  
2072 /* The HTTP_* keys for the headers real traffic actually sends, as shared
2073 * key SVs made once. Storing with a plain char* key makes hv_common hash
2074 * the string and cut a fresh HEK against the shared string table on every
2075 * request, then release it again at env teardown; storing through a shared
2076 * SV reuses the precomputed hash and the one HEK for the process's life.
2077 * A browser request carries a dozen of these, so it pays per header, per
2078 * request. Anything not in this table just takes the char* path it always
2079 * took. Grouped by key length so the lookup is a couple of memcmps. */
2080 static const char *const hm_hdrk_name[] = {
2081 "HTTP_TE", /* 7 */
2082 "HTTP_DNT", /* 8 */
2083 "HTTP_HOST", /* 9 */
2084 "HTTP_RANGE", /* 10 */
2085 "HTTP_ACCEPT", "HTTP_COOKIE", "HTTP_ORIGIN", "HTTP_PRAGMA", /* 11 */
2086 "HTTP_REFERER", "HTTP_UPGRADE", /* 12 */
2087 "HTTP_USER_AGENT", "HTTP_CONNECTION", /* 15 */
2088 "HTTP_AUTHORIZATION", "HTTP_CACHE_CONTROL",
2089 "HTTP_IF_NONE_MATCH", /* 18 */
2090 "HTTP_ACCEPT_ENCODING", "HTTP_ACCEPT_LANGUAGE",
2091 "HTTP_X_FORWARDED_FOR", /* 20 */
2092 "HTTP_X_REQUESTED_WITH", /* 21 */
2093 "HTTP_IF_MODIFIED_SINCE", "HTTP_X_FORWARDED_PROTO",
2094 "HTTP_SEC_WEBSOCKET_KEY", /* 22 */
2095 "HTTP_SEC_WEBSOCKET_VERSION", /* 26 */
2096 NULL
2097 };
2098 #define HM_HDRK_MAXLEN 26
2099 #define HM_HDRK_PERLEN 5
2100 static SV *hm_hdrk_sv[sizeof(hm_hdrk_name) / sizeof(char *)];
2101 /* index+1 of each candidate, per key length; 0 ends the row */
2102 static unsigned char hm_hdrk_by_len[HM_HDRK_MAXLEN + 1][HM_HDRK_PERLEN];
2103  
2104 /* the cached key SV for keybuf/klen, or NULL for the char* fallback */
2105 1051 static SV *hm_hdrk_lookup(const char *keybuf, size_t klen) {
2106 const unsigned char *row;
2107 int i;
2108 /*
2109 # uncoverable branch true
2110 # uncoverable condition left count:1 class:ignore_covered_err */
2111 1051 ▶ if (klen > HM_HDRK_MAXLEN) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (klen > HM_HDRK_MAXLEN) return NULL; 0 1051 1051
2112 1051 row = hm_hdrk_by_len[klen];
2113 1357 ▶ 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 */ 1357 0 1357
for (i = 0; i < HM_HDRK_PERLEN && row[i]; i++) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 1236 121 1357
2114 1236 int idx = row[i] - 1;
2115 1236 ▶ if (memcmp(keybuf, hm_hdrk_name[idx], klen) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (memcmp(keybuf, hm_hdrk_name[idx], klen) == 0) 930 306 1236
2116 930 return hm_hdrk_sv[idx];
2117 }
2118 121 return NULL;
2119 }
2120  
2121 /* The two bytes a repeated request header folds with. PSGI joins with the
2122 * comma of a list header (RFC 9110 5.3). Cookie is the one request header
2123 * whose list is "; " (RFC 6265 4.2.1), and an HTTP/2 client may send each
2124 * cookie as its own field (RFC 9113 8.2.3), which browsers do: folded with
2125 * a comma the session cookie's value grows a tail and its signature fails
2126 * on every request. The same fold serves HTTP/1.1, where a client that
2127 * splits Cookie is out of spec but the app is still owed one value. */
2128 1 static const char *hm_hdr_join_sep(const char *keybuf, size_t klen) {
2129 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
2130 }
2131  
2132 882 static void hm_env_init(pTHX) {
2133 int i;
2134 AV *ver;
2135 882 ▶ if (hm_env_key[0]) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_env_key[0]) return; 794 88 882
2136 2552 ▶ for (i = 0; i < HMK_COUNT; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < HMK_COUNT; i++) 2464 88 2552
2137 2464 hm_env_key[i] = newSVpvn_share(hm_env_key_name[i],
2138 strlen(hm_env_key_name[i]), 0);
2139 88 hm_env_zero = newSViv(0); SvREADONLY_on(hm_env_zero);
2140 88 hm_env_one = newSViv(1); SvREADONLY_on(hm_env_one);
2141 88 ver = newAV();
2142 88 av_push(ver, newSViv(1)); av_push(ver, newSViv(1));
2143 88 SvREADONLY_on((SV *)ver);
2144 88 hm_env_version = newRV_noinc((SV *)ver); SvREADONLY_on(hm_env_version);
2145 88 hm_env_errors = newRV_inc((SV *)PL_stderrgv); SvREADONLY_on(hm_env_errors);
2146  
2147 2112 ▶ for (i = 0; hm_hdrk_name[i]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; hm_hdrk_name[i]; i++) { 2024 88 2112
2148 2024 size_t l = strlen(hm_hdrk_name[i]);
2149 int j;
2150 2024 hm_hdrk_sv[i] = newSVpvn_share(hm_hdrk_name[i], (I32)l, 0);
2151 /*
2152 # uncoverable branch false class:ignore_covered_err
2153 # uncoverable condition right count:1 class:ignore_covered_err */
2154 3520 ▶ for (j = 0; j < HM_HDRK_PERLEN; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < HM_HDRK_PERLEN; j++) { 3520 0 3520
2155 3520 ▶ if (!hm_hdrk_by_len[l][j]) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_hdrk_by_len[l][j]) { 2024 1496 3520
2156 2024 hm_hdrk_by_len[l][j] = (unsigned char)(i + 1);
2157 2024 break;
2158 }
2159 }
2160 }
2161 }
2162  
2163 #define hm_env_store(env, k, val) \
2164 (void)hv_store_ent((env), hm_env_key[(k)], (val), 0)
2165  
2166 /* Build a full PSGI env from the request line, the header lines indexed by
2167 * idx (from hm_parse_index) and, if present, the request body. Sets
2168 * c->keepalive from the request. */
2169 882 static HV *hm_build_env(pTHX_ char *head, size_t headlen,
2170 const char *body, long clen, hm_conn *c,
2171 const hm_hline *idx, int nlines) {
2172 882 HV *env = newHV();
2173 882 hm_env_init(aTHX);
2174  
2175 /* A fresh HV starts with 8 buckets and this function stores 25-odd keys
2176 * before the app adds its own, so left alone every request pays two
2177 * bucket-split reallocs (8 -> 16 -> 32) plus the rehash walk each one
2178 * does. Ask for the final size up front. 64 rather than 32: a typical
2179 * browser request carries a dozen HTTP_* headers on top of ours, and
2180 * middleware adds more. */
2181 882 hv_ksplit(env, 64);
2182  
2183 /* request line */
2184 882 char *line_end = (char *)memchr(head, '\r', headlen);
2185 882 ▶ 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; 653 229 882
2186 882 char *sp1 = (char *)memchr(head, ' ', ll);
2187 882 const char *method = head; STRLEN mlen = ll;
2188 882 const char *uri = "/"; STRLEN ulen = 1;
2189 882 const char *proto = "HTTP/1.0"; STRLEN plen = 8;
2190 /*
2191 # uncoverable branch false class:ignore_covered_err
2192 # uncoverable condition right count:1 class:ignore_covered_err */
2193 882 ▶ if (sp1) {
Branch: 1 branch
BranchTrueFalseTotal
if (sp1) { 882 0 882
2194 882 mlen = (STRLEN)(sp1 - head);
2195 882 char *u = sp1 + 1;
2196 882 char *sp2 = (char *)memchr(u, ' ', ll - (u - head));
2197 /*
2198 # uncoverable branch false
2199 # uncoverable condition right count:1 class:ignore_covered_err */
2200 882 ▶ if (sp2) {
Branch: 1 branch
BranchTrueFalseTotal
if (sp2) { 882 0 882
2201 882 uri = u; ulen = (STRLEN)(sp2 - u);
2202 882 proto = sp2 + 1; plen = (STRLEN)((head + ll) - (sp2 + 1));
2203 0 } else { uri = u; ulen = (STRLEN)((head + ll) - u); } /* # uncoverable statement class:ignore_covered_err */
2204 }
2205 882 const char *qmark = (const char *)memchr(uri, '?', ulen);
2206 882 const char *path = uri; STRLEN path_l = ulen;
2207 882 const char *qs = ""; STRLEN qs_l = 0;
2208 882 ▶ 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; } 14 868 882
2209  
2210 882 hm_env_store(env, HMK_REQUEST_METHOD, newSVpvn(method, mlen));
2211 882 hm_env_store(env, HMK_REQUEST_URI, newSVpvn(uri, ulen));
2212 882 hm_env_store(env, HMK_PATH_INFO, hm_pct_decode(aTHX_ path, path_l));
2213 882 hm_env_store(env, HMK_QUERY_STRING, newSVpvn(qs, qs_l));
2214 882 hm_env_store(env, HMK_SERVER_PROTOCOL, newSVpvn(proto, plen));
2215 882 hm_env_store(env, HMK_SCRIPT_NAME, newSVpvs(""));
2216 882 ▶ 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 846 882
c->is_head = (mlen == 4 && memcmp(method, "HEAD", 4) == 0); 4 32 36
2217 882 ▶ if (!c->sname_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->sname_sv) { 815 67 882
2218 /*
2219 # uncoverable condition right count:1 class:ignore_covered_err
2220 # uncoverable condition right count:2 class:ignore_covered_err */
2221 815 ▶ 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); 815 0 815
c->sname_sv = newSVpv(c->lst && c->lst->host ? c->lst->host : "0.0.0.0", 0); 815 0 815
2222 815 ▶ 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 */ 815 0 815
2223 }
2224 /* Copies, not the cached SVs themselves. `$env->{REMOTE_ADDR} = $ip`
2225 * - which is what a reverse-proxy middleware does - assigns INTO the
2226 * value SV, and a shared one would then carry the forwarded address
2227 * into every later request on this keep-alive connection, before any
2228 * middleware had run on them. newSVsv shares the buffer copy-on-write
2229 * on perls that can, so the copy costs an SV head and no string. */
2230 882 hm_env_store(env, HMK_SERVER_NAME, newSVsv(c->sname_sv));
2231 882 hm_env_store(env, HMK_SERVER_PORT, newSVsv(c->sport_sv));
2232 882 ▶ if (c->peer[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer[0]) { 880 2 882
2233 880 ▶ if (!c->peer_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->peer_sv) { 813 67 880
2234 813 c->peer_sv = newSVpv(c->peer, 0);
2235 813 c->peer_host_sv = newSVpv(c->peer, 0);
2236 }
2237 880 hm_env_store(env, HMK_REMOTE_ADDR, newSVsv(c->peer_sv));
2238 880 hm_env_store(env, HMK_REMOTE_HOST, newSVsv(c->peer_host_sv));
2239 }
2240 882 ▶ if (c->peer_port) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->peer_port) { 880 2 882
2241 880 ▶ 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); 813 67 880
2242 880 hm_env_store(env, HMK_REMOTE_PORT, newSVsv(c->peer_port_sv));
2243 }
2244 /* Per-request copies, not the shared read-only SVs: an assignment into
2245 * the slot writes INTO the SV there, and Plack::Middleware::BufferedStreaming
2246 * does `$env->{'psgi.streaming'} = 1`, which died "Modification of a
2247 * read-only value" and made every request a 500 under it. The version
2248 * copy is a fresh RV onto the one read-only array. */
2249 882 hm_env_store(env, HMK_PSGI_VERSION, newSVsv(hm_env_version));
2250 882 ▶ hm_env_store(env, HMK_PSGI_URL_SCHEME,
Branch: 1 branch
BranchTrueFalseTotal
hm_env_store(env, HMK_PSGI_URL_SCHEME, 47 835 882
2251 c->ssl ? newSVpvs("https") : newSVpvs("http"));
2252 882 hm_env_store(env, HMK_PSGI_MULTITHREAD, newSViv(0));
2253 882 hm_env_store(env, HMK_PSGI_MULTIPROCESS, newSViv(1));
2254 882 hm_env_store(env, HMK_PSGI_RUN_ONCE, newSViv(0));
2255 882 hm_env_store(env, HMK_PSGI_STREAMING, newSViv(1));
2256 882 hm_env_store(env, HMK_PSGI_NONBLOCKING, newSViv(1));
2257 /* A copy: `$env->{'psgi.errors'} = $fh` is an assignment INTO the slot's
2258 * SV, and the shared one is read-only, so an application redirecting
2259 * its errors died with "Modification of a read-only value". */
2260 882 hm_env_store(env, HMK_PSGI_ERRORS, newSVsv(hm_env_errors));
2261 882 ▶ 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 */ 55 827 882
2262 55 (void)hv_stores(env, "psgix.request_start", newSVnv((NV)hm_now_ns() / 1e9));
2263  
2264 /* psgix.loop: this worker's loop, so apps/clients can create loop
2265 * Futures; psgix.io: the client socket, dup'd so an app that
2266 * hijacks it keeps the socket alive after we close our fd. */
2267 882 hm_env_store(env, HMK_PSGIX_LOOP, hm_loop_to_sv(aTHX_ c->loop));
2268 882 ▶ 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); 815 67 882
2269 882 hm_env_store(env, HMK_PSGIX_IO, SvREFCNT_inc(c->io_sv));
2270 /* psgix.hyperman.conn: [fd, generation id] - the ticket an app hands
2271 * back to Hyperman::detach (or the ABI's conn_detach) to take this
2272 * socket over for a protocol upgrade. HTTP/1 only; the generation id
2273 * makes a stale ticket a no-op rather than a wrong-connection hit. */
2274 882 ▶ if (!c->cid_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->cid_sv) { 815 67 882
2275 815 AV *cid = newAV();
2276 815 av_extend(cid, 2);
2277 815 av_store(cid, 0, newSViv(c->fd));
2278 815 av_store(cid, 1, newSVuv(c->id));
2279 /* The third element is the stream id, and -1 is "the whole
2280 * connection is the stream" - which is what HTTP/1.1 is. It rides on
2281 * the same cached arrayref rather than a second one, so
2282 * psgix.hyperman.stream costs a store and not an allocation. */
2283 815 av_store(cid, 2, newSViv(-1));
2284 815 c->cid_sv = newRV_noinc((SV *)cid);
2285 }
2286 882 hm_env_store(env, HMK_PSGIX_HM_CONN, SvREFCNT_inc(c->cid_sv));
2287 882 hm_env_store(env, HMK_PSGIX_HM_STREAM, SvREFCNT_inc(c->cid_sv));
2288 882 ▶ if (c->proxy_addr[0]) /* the address that connected */
Branch: 1 branch
BranchTrueFalseTotal
if (c->proxy_addr[0]) /* the address that connected */ 10 872 882
2289 10 hm_env_store(env, HMK_PSGIX_PROXY_ADDR, newSVpv(c->proxy_addr, 0));
2290 882 ▶ if (c->ssl) hm_tls_env(aTHX_ c, env);
Branch: 1 branch
BranchTrueFalseTotal
if (c->ssl) hm_tls_env(aTHX_ c, env); 47 835 882
2291  
2292 882 ▶ 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 */ 882 0 882
c->keepalive = (plen == 8 && memcmp(proto, "HTTP/1.1", 8) == 0); /* # uncoverable condition right count:1 class:ignore_covered_err */ 366 516 882
2293 882 c->req_11 = c->keepalive; /* before Connection: close can clear it */
2294 /* Per request, not per connection: a keep-alive connection may send a
2295 * different Accept-Encoding on its next request, and the response path
2296 * has no env to read by the time it needs this. One bit, set below. */
2297 882 c->accepts_gzip = 0;
2298 882 c->te_trailers = 0;
2299  
2300 /* header lines, from the framing pass's index (no rescan) */
2301 char keybuf[300];
2302 882 int have_cl = 0;
2303 int li;
2304 1978 ▶ for (li = 0; li < nlines; li++) {
Branch: 1 branch
BranchTrueFalseTotal
for (li = 0; li < nlines; li++) { 1096 882 1978
2305 1096 const char *p = head + idx[li].off;
2306 1096 size_t nk = idx[li].klen;
2307 1096 const char *vp = head + idx[li].voff;
2308 1096 size_t nv = idx[li].vlen;
2309  
2310 /*
2311 # uncoverable branch true
2312 # uncoverable condition left count:1 class:ignore_covered_err */
2313 1096 ▶ 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 1096 1096
2314 we would have stored before
2315 either */
2316 /* Fold to the canonical HTTP_ form first, then every name test below
2317 * is a memcmp on known-case bytes rather than a strncasecmp on the
2318 * wire bytes - three case-blind scans per header gone. The fold maps
2319 * '-' to '_', which would let a literal "Content_Length" alias the
2320 * real thing, so the special names also check the wire byte at the
2321 * hyphen position, exactly as the old raw-name compare required. */
2322 {
2323 size_t i;
2324 1096 int underscore = 0;
2325 1096 memcpy(keybuf, "HTTP_", 5);
2326 8024 ▶ for (i = 0; i < nk; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nk; i++) { 6928 1096 8024
2327 6928 unsigned char ch = (unsigned char)p[i];
2328 6928 ▶ 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 */ 5163 1765 6928
if (ch >= 'a' && ch <= 'z') ch -= 32; /* # uncoverable condition right count:2 class:ignore_covered_err */ 5163 0 5163
2329 1765 ▶ else if (ch == '-') ch = '_';
Branch: 1 branch
BranchTrueFalseTotal
else if (ch == '-') ch = '_'; 266 1499 1765
2330 1499 ▶ else if (ch == '_') underscore = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (ch == '_') underscore = 1; 3 1496 1499
2331 6928 keybuf[5 + i] = (char)ch;
2332 }
2333 /* A wire name with an underscore folds to the same env key as
2334 * the hyphenated name, so "X_Forwarded_For" would land in
2335 * HTTP_X_FORWARDED_FOR beside - or instead of - the header a
2336 * proxy in front vetted. Proxies strip the hyphenated form and
2337 * pass the underscored one untouched, which is the whole
2338 * attack. Dropped, as nginx and Apache do. */
2339 1096 ▶ if (underscore) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (underscore) continue; 2 1094 1096
2340 }
2341 /* Accept-Encoding is answered on this one pass and remembered as a
2342 * bit on the connection: hm_queue_response has no env to consult by
2343 * the time it must decide. Not an arm of the chain below - the
2344 * header is still stored as HTTP_ACCEPT_ENCODING like any other. */
2345 /*
2346 # uncoverable condition right count:2 class:ignore_covered_err
2347 # uncoverable condition right count:3 class:ignore_covered_err
2348 # uncoverable condition right count:4 class:ignore_covered_err */
2349 1094 ▶ if (nk == 15 && p[6] == '-' && c->loop->compress
Branch: 3 branches
BranchTrueFalseTotal
if (nk == 15 && p[6] == '-' && c->loop->compress 17 1077 1094
if (nk == 15 && p[6] == '-' && c->loop->compress 17 0 17
if (nk == 15 && p[6] == '-' && c->loop->compress 17 0 17
2350 17 ▶ && memEQ(keybuf + 5, "ACCEPT_ENCODING", 15))
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(keybuf + 5, "ACCEPT_ENCODING", 15)) 17 0 17
2351 17 c->accepts_gzip = (unsigned char)hz_accepts_gzip(vp, nv);
2352 /* TE is read the same way, into one bit, and still stored as HTTP_TE.
2353 * Several TE lines form one list, so the bit only ever goes on. */
2354 1094 ▶ if (nk == 2 && memEQ(keybuf + 5, "TE", 2) && hm_te_names_trailers(vp, nv))
Branch: 3 branches
BranchTrueFalseTotal
if (nk == 2 && memEQ(keybuf + 5, "TE", 2) && hm_te_names_trailers(vp, nv)) 0 1094 1094
if (nk == 2 && memEQ(keybuf + 5, "TE", 2) && hm_te_names_trailers(vp, nv)) 0 0 0
if (nk == 2 && memEQ(keybuf + 5, "TE", 2) && hm_te_names_trailers(vp, nv)) 0 0 0
2355 0 c->te_trailers = 1;
2356  
2357 1094 ▶ 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 1072 1094
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
2358 22 hm_env_store(env, HMK_CONTENT_LENGTH, newSVpvn(vp, nv));
2359 22 have_cl = 1;
2360 1072 ▶ } 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 1024 1072
} else if (nk == 12 && p[7] == '-' /* # uncoverable condition right count:2 class:ignore_covered_err */ 48 0 48
2361 48 ▶ && memEQ(keybuf + 5, "CONTENT_TYPE", 12)) {
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(keybuf + 5, "CONTENT_TYPE", 12)) { 11 37 48
2362 11 hm_env_store(env, HMK_CONTENT_TYPE, newSVpvn(vp, nv));
2363 /*
2364 # uncoverable condition right count:2 class:ignore_covered_err
2365 # uncoverable condition right count:3 class:ignore_covered_err */
2366 1061 ▶ } else if (nk == 17 && p[8] == '-'
Branch: 2 branches
BranchTrueFalseTotal
} else if (nk == 17 && p[8] == '-' 10 1051 1061
} else if (nk == 17 && p[8] == '-' 10 0 10
2367 10 ▶ && memEQ(keybuf + 5, "TRANSFER_ENCODING", 17)) {
Branch: 1 branch
BranchTrueFalseTotal
&& memEQ(keybuf + 5, "TRANSFER_ENCODING", 17)) { 10 0 10
2368 /* consumed by framing (already dechunked); not exposed to the
2369 * app, whose psgi.input is the decoded body with CONTENT_LENGTH */
2370 } else {
2371 {
2372 /* repeated header: join values (hm_hdr_join_sep) */
2373 1051 SV *ksv = hm_hdrk_lookup(keybuf, nk + 5);
2374 1051 ▶ if (ksv) {
Branch: 1 branch
BranchTrueFalseTotal
if (ksv) { 930 121 1051
2375 /* a common header: the shared key SV carries its hash
2376 * and its HEK, so no hashing and no HEK churn */
2377 930 HE *he = hv_fetch_ent(env, ksv, 0, 0);
2378 930 ▶ if (he) {
Branch: 1 branch
BranchTrueFalseTotal
if (he) { 0 930 930
2379 0 sv_catpvn(HeVAL(he), hm_hdr_join_sep(keybuf, nk + 5), 2);
2380 0 sv_catpvn(HeVAL(he), vp, nv);
2381 } else {
2382 930 (void)hv_store_ent(env, ksv, newSVpvn(vp, nv), 0);
2383 }
2384 } else {
2385 121 SV **old = hv_fetch(env, keybuf, (I32)(nk + 5), 0);
2386 121 ▶ if (old) {
Branch: 1 branch
BranchTrueFalseTotal
if (old) { 1 120 121
2387 1 sv_catpvn(*old, hm_hdr_join_sep(keybuf, nk + 5), 2);
2388 1 sv_catpvn(*old, vp, nv);
2389 } else {
2390 120 hv_store(env, keybuf, (I32)(nk + 5), newSVpvn(vp, nv), 0);
2391 }
2392 }
2393 }
2394 /* the name is already canonical; only the value keeps wire case */
2395 1051 ▶ if (nk == 10 && memEQ(keybuf + 5, "CONNECTION", 10)) {
Branch: 2 branches
BranchTrueFalseTotal
if (nk == 10 && memEQ(keybuf + 5, "CONNECTION", 10)) { 242 809 1051
if (nk == 10 && memEQ(keybuf + 5, "CONNECTION", 10)) { 184 58 242
2396 184 ▶ 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 */ 184 0 184
if (nv >= 5 && hm_strncasecmp(vp, "close", 5) == 0) c->keepalive = 0; /* # uncoverable condition right count:1 class:ignore_covered_err */ 175 9 184
2397 /*
2398 # uncoverable branch true class:ignore_covered_err
2399 # uncoverable condition left count:1 class:ignore_covered_err
2400 # uncoverable condition left count:2 class:ignore_covered_err */
2401 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
2402 }
2403 }
2404 }
2405 /* dechunked request: no Content-Length header, but we know the decoded
2406 * length - present it so apps/middleware see the real body size */
2407 882 ▶ if (!have_cl && clen > 0)
Branch: 2 branches
BranchTrueFalseTotal
if (!have_cl && clen > 0) 860 22 882
if (!have_cl && clen > 0) 10 850 860
2408 10 hm_env_store(env, HMK_CONTENT_LENGTH, newSViv((IV)clen));
2409  
2410 886 ▶ 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 */ 882 0 882
if (c && c->spill_fd >= 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 4 878 882
2411 /* The body was drained to a file as it arrived, so there is no body
2412 * pointer to copy from: the descriptor IS psgi.input. The handle owns
2413 * it from here, and the connection stops tracking it. */
2414 4 SV *in = hm_input_from_fd(aTHX_ c->spill_fd);
2415 4 c->spill_fd = -1;
2416 4 c->spill_got = 0;
2417 4 ▶ hm_env_store(env, HMK_PSGI_INPUT,
Branch: 1 branch
BranchTrueFalseTotal
hm_env_store(env, HMK_PSGI_INPUT, 0 4 4
2418 in ? in : hm_empty_input_sv(aTHX));
2419 }
2420 878 ▶ else if (clen > 0)
Branch: 1 branch
BranchTrueFalseTotal
else if (clen > 0) 27 851 878
2421 27 hm_env_store(env, HMK_PSGI_INPUT, hm_new_input(aTHX_ body, (STRLEN)clen));
2422 else
2423 851 hm_env_store(env, HMK_PSGI_INPUT, hm_empty_input_sv(aTHX));
2424 882 hm_env_store(env, HMK_PSGIX_INPUT_BUFFERED, SvREFCNT_inc(hm_env_one));
2425 /* The flag promises only what the framing can deliver: a streamed body
2426 * is chunked on an HTTP/1.1 keep-alive connection and nowhere else, and
2427 * only a chunked body has room for trailers. An application that then
2428 * supplies its own Content-Length gives that room away again, see
2429 * hm_stream_finish. */
2430 882 ▶ if (c->te_trailers && c->req_11 && c->keepalive)
Branch: 3 branches
BranchTrueFalseTotal
if (c->te_trailers && c->req_11 && c->keepalive) 0 882 882
if (c->te_trailers && c->req_11 && c->keepalive) 0 0 0
if (c->te_trailers && c->req_11 && c->keepalive) 0 0 0
2431 0 hv_stores(env, "psgix.hyperman.trailers", SvREFCNT_inc(hm_env_one));
2432  
2433 882 return env;
2434 }
2435  
2436 /* ---- app invocation ------------------------------------------------------ */
2437  
2438 /* Call the app with an env we keep alive (access_log needs it afterwards). */
2439 164 static SV *hm_call_app(pTHX_ hm_loop *loop, SV *env_rv) {
2440 164 dSP;
2441 164 SV *resp = NULL;
2442 int count;
2443 164 ENTER; SAVETMPS;
2444 164 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 164 164
2445 164 ▶ XPUSHs(sv_2mortal(SvREFCNT_inc(env_rv)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(SvREFCNT_inc(env_rv))); 0 164 164
2446 164 PUTBACK;
2447 164 count = call_sv(loop->app, G_SCALAR | G_EVAL);
2448 164 SPAGAIN;
2449 164 ▶ 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 */ 164 0 164
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 163 1 164
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 163 0 163
2450 163 resp = POPs;
2451 163 SvREFCNT_inc(resp);
2452 /*
2453 # uncoverable branch false class:ignore_covered_err
2454 # uncoverable condition right count:1 class:ignore_covered_err */
2455 1 ▶ } else if (count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (count > 0) { 1 0 1
2456 1 (void)POPs;
2457 }
2458 164 hm_warn_died(aTHX_ "application");
2459 164 PUTBACK;
2460 164 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 164 0 164
2461 164 return resp;
2462 }
2463  
2464 /* No-logger fast path: the env is handed to the call and freed with it. */
2465 716 static SV *hm_call_app0(pTHX_ hm_loop *loop, HV *env) {
2466 716 dSP;
2467 716 SV *resp = NULL;
2468 int count;
2469 716 ENTER; SAVETMPS;
2470 716 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 716 716
2471 716 ▶ XPUSHs(sv_2mortal(newRV_noinc((SV *)env)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newRV_noinc((SV *)env))); 0 716 716
2472 716 PUTBACK;
2473 716 count = call_sv(loop->app, G_SCALAR | G_EVAL);
2474 716 SPAGAIN;
2475 716 ▶ 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 */ 716 0 716
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 714 2 716
if (!SvTRUE(ERRSV) && count > 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 714 0 714
2476 714 resp = POPs;
2477 714 SvREFCNT_inc(resp);
2478 /*
2479 # uncoverable branch false class:ignore_covered_err
2480 # uncoverable condition right count:1 class:ignore_covered_err */
2481 2 ▶ } else if (count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (count > 0) { 2 0 2
2482 2 (void)POPs;
2483 }
2484 716 hm_warn_died(aTHX_ "application");
2485 716 PUTBACK;
2486 716 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 716 0 716
2487 716 return resp;
2488 }
2489  
2490 /* Is any access logging configured for this loop? Guards the (small) cost of
2491 * keeping the env alive past the response purely for the logger. */
2492 #define hm_logging(loop) ((loop)->log_cb || (loop)->log_fd >= 0)
2493  
2494 /* ---- fast default access-log writer (Combined Log Format) ----------------
2495 * When access_log is a path/handle rather than a coderef, log lines are
2496 * formatted and buffered in C and flushed once per loop wakeup - no Perl
2497 * call on the hot path. The fd is shared (inherited) across workers and
2498 * opened O_APPEND, so whole-line writes stay atomic between them. */
2499  
2500 #define HM_LOG_FLUSH_AT (32 * 1024) /* flush the buffer once it grows past */
2501  
2502 75 static void hm_log_flush(hm_loop *loop) {
2503 75 size_t off = 0;
2504 75 ▶ 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 */ 75 0 75
if (loop->log_fd < 0 || loop->log_len == 0) return; /* # uncoverable condition left count:1 class:ignore_covered_err */ 8 67 75
2505 134 ▶ while (off < loop->log_len) {
Branch: 1 branch
BranchTrueFalseTotal
while (off < loop->log_len) { 67 67 134
2506 67 ssize_t n = hm_os_write_file(loop->log_fd, loop->log_buf + off,
2507 loop->log_len - off);
2508 /*
2509 # uncoverable branch false
2510 # uncoverable condition right count:1 class:ignore_covered_err */
2511 67 ▶ if (n > 0) { off += (size_t)n; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { off += (size_t)n; continue; } 67 0 67
2512 /*
2513 # uncoverable statement
2514 # uncoverable branch true
2515 # uncoverable branch false
2516 # uncoverable condition left count:1
2517 # uncoverable condition right count:1
2518 # uncoverable condition left count:2
2519 # uncoverable condition right count:2 */
2520 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
2521 0 break; /* EAGAIN/error: keep the unwritten tail for the next flush */ /* # uncoverable statement */
2522 }
2523 /*
2524 # uncoverable branch true class:ignore_covered_err
2525 # uncoverable condition left count:1 class:ignore_covered_err
2526 # uncoverable condition right count:1 class:ignore_covered_err
2527 # uncoverable condition left count:2 class:ignore_covered_err */
2528 67 ▶ if (off && off < loop->log_len)
Branch: 2 branches
BranchTrueFalseTotal
if (off && off < loop->log_len) 67 0 67
if (off && off < loop->log_len) 0 67 67
2529 0 memmove(loop->log_buf, loop->log_buf + off, loop->log_len - off); /* # uncoverable statement */
2530 67 loop->log_len -= off;
2531 }
2532  
2533 1552 static void hm_log_raw(hm_loop *loop, const char *p, size_t n) {
2534 1552 ▶ if (loop->log_len + n > loop->log_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_len + n > loop->log_cap) { 8 1544 1552
2535 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
2536 /*
2537 # uncoverable branch true class:ignore_covered_err
2538 # uncoverable condition left count:1 class:ignore_covered_err */
2539 8 ▶ while (ncap < loop->log_len + n) ncap *= 2;
Branch: 1 branch
BranchTrueFalseTotal
while (ncap < loop->log_len + n) ncap *= 2; 0 8 8
2540 8 loop->log_buf = (char *)hm_xrealloc(loop->log_buf, ncap);
2541 8 loop->log_cap = ncap;
2542 }
2543 1552 memcpy(loop->log_buf + loop->log_len, p, n);
2544 1552 loop->log_len += n;
2545 1552 }
2546  
2547 /* A plain token: '-' when empty (CLF uses '-' for missing fields). */
2548 /*
2549 # uncoverable statement
2550 # uncoverable subroutine */
2551 0 static void hm_log_tok(hm_loop *loop, const char *p, size_t n) {
2552 /*
2553 # uncoverable statement
2554 # uncoverable branch true
2555 # uncoverable branch false
2556 # uncoverable condition left count:1
2557 # uncoverable condition right count:1
2558 # uncoverable condition left count:2
2559 # uncoverable condition right count:2 */
2560 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
2561 0 hm_log_raw(loop, p, n); /* # uncoverable statement */
2562 }
2563  
2564 /* A value going inside "quotes": escape ", \ and control bytes \xHH so a
2565 * hostile URI or User-Agent cannot forge or split a log line. */
2566 83 static void hm_log_quoted(hm_loop *loop, const char *p, size_t n) {
2567 static const char hex[] = "0123456789abcdef";
2568 83 size_t i, run = 0;
2569 /*
2570 # uncoverable branch true
2571 # uncoverable condition left count:1 class:ignore_covered_err */
2572 83 ▶ if (!p) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return; 0 83 83
2573 720 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 637 83 720
2574 637 unsigned char ch = (unsigned char)p[i];
2575 /*
2576 # uncoverable condition left count:3 class:ignore_covered_err */
2577 642 ▶ if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) {
Branch: 4 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 634 3 637
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 633 1 634
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 633 0 633
if (ch == '"' || ch == '\\' || ch < 0x20 || ch == 0x7f) { 1 632 633
2578 char e[4];
2579 /*
2580 # uncoverable branch false class:ignore_covered_err
2581 # uncoverable condition right count:1 class:ignore_covered_err */
2582 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
2583 5 ▶ if (ch == '"' || ch == '\\') {
Branch: 2 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\') { 2 3 5
if (ch == '"' || ch == '\\') { 1 1 2
2584 4 e[0] = '\\'; e[1] = (char)ch; hm_log_raw(loop, e, 2);
2585 } else {
2586 1 e[0] = '\\'; e[1] = 'x'; e[2] = hex[ch >> 4]; e[3] = hex[ch & 0xf];
2587 1 hm_log_raw(loop, e, 4);
2588 }
2589 } else {
2590 632 run++;
2591 }
2592 }
2593 83 ▶ if (run) hm_log_raw(loop, p + n - run, run);
Branch: 1 branch
BranchTrueFalseTotal
if (run) hm_log_raw(loop, p + n - run, run); 82 1 83
2594 }
2595  
2596 /* The Date header (RFC 9110 6.6.1, IMF-fixdate), recomputed at most once a
2597 * second. Formatted by hand: strftime's %a and %b follow the locale, and
2598 * the wire wants English. 37 bytes, always: "Date: " + 29 + CRLF. */
2599 #define HM_DATE_LEN 37
2600 868 static const char *hm_date_header(hm_loop *loop) {
2601 868 ▶ if (loop->now != loop->date_sec) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->now != loop->date_sec) { 116 752 868
2602 static const char days[] = "SunMonTueWedThuFriSat";
2603 static const char mons[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2604 struct tm tm;
2605 116 time_t t = loop->now;
2606 116 char *d = loop->date_hdr;
2607 /*
2608 # uncoverable branch true
2609 # uncoverable condition left count:1 class:ignore_covered_err */
2610 116 ▶ if (!hm_gmtime_r(&t, &tm)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_gmtime_r(&t, &tm)) return NULL; 0 116 116
2611 116 memcpy(d, "Date: ", 6); d += 6;
2612 116 memcpy(d, days + tm.tm_wday * 3, 3); d += 3;
2613 116 *d++ = ','; *d++ = ' ';
2614 116 *d++ = (char)('0' + tm.tm_mday / 10); *d++ = (char)('0' + tm.tm_mday % 10);
2615 116 *d++ = ' ';
2616 116 memcpy(d, mons + tm.tm_mon * 3, 3); d += 3;
2617 116 *d++ = ' ';
2618 {
2619 116 int y = tm.tm_year + 1900;
2620 116 *d++ = (char)('0' + y / 1000 % 10); *d++ = (char)('0' + y / 100 % 10);
2621 116 *d++ = (char)('0' + y / 10 % 10); *d++ = (char)('0' + y % 10);
2622 }
2623 116 *d++ = ' ';
2624 116 *d++ = (char)('0' + tm.tm_hour / 10); *d++ = (char)('0' + tm.tm_hour % 10);
2625 116 *d++ = ':';
2626 116 *d++ = (char)('0' + tm.tm_min / 10); *d++ = (char)('0' + tm.tm_min % 10);
2627 116 *d++ = ':';
2628 116 *d++ = (char)('0' + tm.tm_sec / 10); *d++ = (char)('0' + tm.tm_sec % 10);
2629 116 memcpy(d, " GMT\r\n", 6);
2630 116 loop->date_sec = loop->now;
2631 }
2632 868 return loop->date_hdr;
2633 }
2634  
2635 /* Does an app-supplied header name or value carry a byte that would end
2636 * the field early? A CR, LF or NUL in either splits the response, so a
2637 * response carrying one is refused as a 500 rather than serialised: the
2638 * server is the last place the bug can be caught. */
2639 1918 static int hm_hdr_bytes_ok(const char *p, STRLEN n) {
2640 /*
2641 # uncoverable condition right count:2 class:ignore_covered_err
2642 # uncoverable condition right count:3 class:ignore_covered_err */
2643 1918 ▶ 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); 1916 2 1918
return !memchr(p, '\r', n) && !memchr(p, '\n', n) && !memchr(p, '\0', n); 1916 0 1916
return !memchr(p, '\r', n) && !memchr(p, '\n', n) && !memchr(p, '\0', n); 1916 0 1916
2644 }
2645 872 static int hm_headers_ok(pTHX_ AV *hav) {
2646 SSize_t i, hn;
2647 /*
2648 # uncoverable branch true
2649 # uncoverable condition left count:1 class:ignore_covered_err */
2650 872 ▶ if (!hav) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!hav) return 1; 0 872 872
2651 872 hn = av_len(hav) + 1;
2652 2790 ▶ for (i = 0; i < hn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hn; i++) { 1920 870 2790
2653 1920 SV **e = av_fetch(hav, i, 0);
2654 STRLEN l;
2655 const char *p;
2656 1920 ▶ 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 */ 1918 2 1920
if (!e || !*e) continue; /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 1918 1918
2657 1918 p = SvPV(*e, l);
2658 1918 ▶ if (!hm_hdr_bytes_ok(p, l)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_hdr_bytes_ok(p, l)) return 0; 2 1916 1918
2659 }
2660 870 return 1;
2661 }
2662  
2663 /* The same escape, for a value inside a JSON string. */
2664 /* The length of a well-formed UTF-8 sequence starting at p (2..4), or 0 for
2665 * a byte that does not start one. Overlongs, surrogates and > U+10FFFF
2666 * are 0 too: the point is that what passes through is valid JSON text. */
2667 19 static size_t hm_utf8_seq(const unsigned char *p, size_t n) {
2668 19 unsigned char c = p[0];
2669 size_t len, i;
2670 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
2671 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
2672 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
2673 11 else return 0;
2674 8 ▶ if (n < len) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n < len) return 0; 1 7 8
2675 /*
2676 # uncoverable branch true class:ignore_covered_err
2677 # uncoverable condition left count:1 class:ignore_covered_err */
2678 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
2679 7 ▶ if (len == 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (len == 3) { 3 4 7
2680 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
2681 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
2682 4 ▶ } else if (len == 4) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (len == 4) { 3 1 4
2683 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
2684 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
2685 }
2686 3 return len;
2687 }
2688  
2689 199 static void hm_log_json_esc(hm_loop *loop, const char *p, size_t n) {
2690 static const char hex[] = "0123456789abcdef";
2691 199 size_t i, run = 0;
2692 /*
2693 # uncoverable branch true
2694 # uncoverable condition left count:1 class:ignore_covered_err */
2695 199 ▶ if (!p) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return; 0 199 199
2696 1586 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 1387 199 1586
2697 1387 unsigned char ch = (unsigned char)p[i];
2698 1387 ▶ if (ch >= 0x80) {
Branch: 1 branch
BranchTrueFalseTotal
if (ch >= 0x80) { 19 1368 1387
2699 /* Valid UTF-8 passes; a stray high byte (a URI or User-Agent
2700 * that is not UTF-8) is escaped, so the line stays valid JSON
2701 * and a strict pipeline does not drop it - which was a way to
2702 * keep one's requests out of the log. */
2703 19 size_t sl = hm_utf8_seq((const unsigned char *)p + i, n - i);
2704 19 ▶ if (sl) { run += sl; i += sl - 1; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (sl) { run += sl; i += sl - 1; continue; } 3 16 19
2705 }
2706 1405 ▶ if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) {
Branch: 4 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 1381 3 1384
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 1380 1 1381
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 1379 1 1380
if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x80) { 16 1363 1379
2707 char e[6];
2708 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
2709 21 ▶ if (ch == '"' || ch == '\\') {
Branch: 2 branches
BranchTrueFalseTotal
if (ch == '"' || ch == '\\') { 18 3 21
if (ch == '"' || ch == '\\') { 1 17 18
2710 4 e[0] = '\\'; e[1] = (char)ch; hm_log_raw(loop, e, 2);
2711 } else {
2712 17 e[0] = '\\'; e[1] = 'u'; e[2] = '0'; e[3] = '0';
2713 17 e[4] = hex[ch >> 4]; e[5] = hex[ch & 0xf];
2714 17 hm_log_raw(loop, e, 6);
2715 }
2716 } else {
2717 1363 run++;
2718 }
2719 }
2720 199 ▶ if (run) hm_log_raw(loop, p + n - run, run);
Branch: 1 branch
BranchTrueFalseTotal
if (run) hm_log_raw(loop, p + n - run, run); 198 1 199
2721 }
2722  
2723 /* A value from $env, escaped the way this log's format wants. */
2724 282 static void hm_log_esc(hm_loop *loop, const char *p, size_t n) {
2725 282 ▶ 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); 199 83 282
2726 83 else hm_log_quoted(loop, p, n);
2727 282 }
2728  
2729 /* Cached apache-style timestamp, recomputed at most once per second. */
2730 14 static const char *hm_log_time(hm_loop *loop) {
2731 14 ▶ if (loop->now != loop->log_ts_sec) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->now != loop->log_ts_sec) { 4 10 14
2732 struct tm tm;
2733 4 time_t t = loop->now;
2734 4 hm_localtime_r(&t, &tm);
2735 4 strftime(loop->log_ts, sizeof(loop->log_ts), "%d/%b/%Y:%H:%M:%S %z", &tm);
2736 4 loop->log_ts_sec = loop->now;
2737 }
2738 14 return loop->log_ts;
2739 }
2740  
2741 /* The ISO 8601 stamp the JSON format carries, cached the same way. */
2742 49 static const char *hm_log_time_iso(hm_loop *loop) {
2743 49 ▶ if (loop->now != loop->log_iso_sec) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->now != loop->log_iso_sec) { 4 45 49
2744 struct tm tm;
2745 4 time_t t = loop->now;
2746 4 hm_localtime_r(&t, &tm);
2747 4 strftime(loop->log_iso, sizeof(loop->log_iso), "%Y-%m-%dT%H:%M:%S%z", &tm);
2748 4 loop->log_iso_sec = loop->now;
2749 }
2750 49 return loop->log_iso;
2751 }
2752  
2753 /* ---- the access-log format compiler ----------------------------------------
2754 * Apache's directives, the ones a PSGI server can honour:
2755 * %h %a REMOTE_ADDR %l "-" %u REMOTE_USER %t [time]
2756 * %r request line %s %>s status %b bytes or "-" %B bytes or 0
2757 * %D microseconds %T seconds %p SERVER_PORT %m METHOD
2758 * %U PATH_INFO %q ?query %H SERVER_PROTOCOL %v SERVER_NAME
2759 * %P pid %{Name}i request header %{Name}e any $env key
2760 * %% a literal percent sign
2761 * Returns 0, or -1 with the offending directive in err. Every value is
2762 * escaped (CLF or JSON), so no directive is a way to forge a line. */
2763 #define HM_LOG_COMBINED "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""
2764  
2765 1624 static void hm_logtok_push(hm_logtok **toks, int *n, int *cap, hm_logtok t) {
2766 1624 ▶ if (*n == *cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (*n == *cap) { 179 1445 1624
2767 179 ▶ *cap = *cap ? *cap * 2 : 16;
Branch: 1 branch
BranchTrueFalseTotal
*cap = *cap ? *cap * 2 : 16; 89 90 179
2768 179 *toks = (hm_logtok *)hm_xrealloc(*toks, (size_t)*cap * sizeof(hm_logtok));
2769 }
2770 1624 (*toks)[(*n)++] = t;
2771 1624 }
2772 906 static void hm_logtok_lit(hm_logtok **toks, int *n, int *cap, const char *p, size_t l) {
2773 hm_logtok t;
2774 907 ▶ if (!l) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!l) return; 92 814 906
2775 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
2776 1 hm_logtok *last = &(*toks)[*n - 1];
2777 1 last->lit = (char *)hm_xrealloc(last->lit, last->litlen + l);
2778 1 memcpy(last->lit + last->litlen, p, l);
2779 1 last->litlen += l;
2780 1 return;
2781 }
2782 813 t.kind = HM_LT_LIT; t.lit = (char *)hm_xmalloc(l); memcpy(t.lit, p, l);
2783 813 t.litlen = l; t.key = NULL;
2784 813 hm_logtok_push(toks, n, cap, t);
2785 }
2786 368 static void hm_logtok_env(pTHX_ hm_logtok **toks, int *n, int *cap,
2787 const char *key, size_t klen) {
2788 hm_logtok t;
2789 368 t.kind = HM_LT_ENV; t.lit = NULL; t.litlen = 0;
2790 368 t.key = newSVpvn_share(key, (I32)klen, 0); /* hash computed once */
2791 368 hm_logtok_push(toks, n, cap, t);
2792 368 }
2793 443 static void hm_logtok_kind(hm_logtok **toks, int *n, int *cap, int kind) {
2794 hm_logtok t;
2795 443 t.kind = kind; t.lit = NULL; t.litlen = 0; t.key = NULL;
2796 443 hm_logtok_push(toks, n, cap, t);
2797 443 }
2798  
2799 90 static int hm_logfmt_compile(pTHX_ const char *fmt, hm_logtok **out, int *nout,
2800 int *wants_t0, char *err, size_t errlen) {
2801 90 hm_logtok *toks = NULL;
2802 90 int n = 0, cap = 0;
2803 90 const char *p = fmt, *lit = fmt;
2804 90 *wants_t0 = 0;
2805 2070 ▶ while (*p) {
Branch: 1 branch
BranchTrueFalseTotal
while (*p) { 1984 86 2070
2806 char d;
2807 1984 ▶ if (*p != '%') { p++; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (*p != '%') { p++; continue; } 1201 783 1984
2808 783 hm_logtok_lit(&toks, &n, &cap, lit, (size_t)(p - lit));
2809 783 p++;
2810 783 ▶ if (*p == '>') p++; /* %>s is %s */
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '>') p++; /* %>s is %s */ 86 697 783
2811 783 ▶ if (*p == '{') {
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '{') { 175 608 783
2812 175 const char *name = p + 1, *end = strchr(name, '}');
2813 char key[300];
2814 size_t nl, i;
2815 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
2816 2 ▶ snprintf(err, errlen, "%%{...}%c", end ? end[1] : '?');
Branch: 1 branch
BranchTrueFalseTotal
snprintf(err, errlen, "%%{...}%c", end ? end[1] : '?'); 1 1 2
2817 3 goto bad;
2818 }
2819 173 nl = (size_t)(end - name);
2820 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
2821 172 ▶ if (end[1] == 'i') {
Branch: 1 branch
BranchTrueFalseTotal
if (end[1] == 'i') { 171 1 172
2822 171 memcpy(key, "HTTP_", 5);
2823 1624 ▶ for (i = 0; i < nl; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nl; i++) { 1453 171 1624
2824 1453 unsigned char ch = (unsigned char)name[i];
2825 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
2826 345 ▶ else if (ch == '-') ch = '_';
Branch: 1 branch
BranchTrueFalseTotal
else if (ch == '-') ch = '_'; 87 258 345
2827 1453 key[5 + i] = (char)ch;
2828 }
2829 171 hm_logtok_env(aTHX_ &toks, &n, &cap, key, nl + 5);
2830 } else {
2831 1 hm_logtok_env(aTHX_ &toks, &n, &cap, name, nl);
2832 }
2833 172 p = end + 2;
2834 172 lit = p;
2835 172 continue;
2836 }
2837 608 d = *p;
2838 /*
2839 # uncoverable branch true count:11 class:ignore_covered_err
2840 # uncoverable branch true count:12 class:ignore_covered_err */
2841 608 switch (d) {
2842 1 case '%': hm_logtok_lit(&toks, &n, &cap, "%", 1); break;
2843 87 case 'h': case 'a': hm_logtok_env(aTHX_ &toks, &n, &cap, "REMOTE_ADDR", 11); break;
2844 84 case 'l': hm_logtok_kind(&toks, &n, &cap, HM_LT_DASH); break;
2845 84 case 'u': hm_logtok_env(aTHX_ &toks, &n, &cap, "REMOTE_USER", 11); break;
2846 84 case 't': hm_logtok_kind(&toks, &n, &cap, HM_LT_TIME); break;
2847 84 case 'r': hm_logtok_kind(&toks, &n, &cap, HM_LT_REQLINE); break;
2848 86 case 's': hm_logtok_kind(&toks, &n, &cap, HM_LT_STATUS); break;
2849 86 case 'b': hm_logtok_kind(&toks, &n, &cap, HM_LT_BYTES); break;
2850 1 case 'B': hm_logtok_kind(&toks, &n, &cap, HM_LT_BYTES0); break;
2851 2 case 'D': hm_logtok_kind(&toks, &n, &cap, HM_LT_DUR_US); *wants_t0 = 1; break;
2852 1 case 'T': hm_logtok_kind(&toks, &n, &cap, HM_LT_DUR_S); *wants_t0 = 1; break;
2853 0 case 'p': hm_logtok_env(aTHX_ &toks, &n, &cap, "SERVER_PORT", 11); break; /* # uncoverable statement */
2854 1 case 'm': hm_logtok_env(aTHX_ &toks, &n, &cap, "REQUEST_METHOD", 14); break;
2855 1 case 'U': hm_logtok_env(aTHX_ &toks, &n, &cap, "PATH_INFO", 9); break;
2856 1 case 'q': hm_logtok_kind(&toks, &n, &cap, HM_LT_QUERY); break;
2857 1 case 'H': hm_logtok_env(aTHX_ &toks, &n, &cap, "SERVER_PROTOCOL", 15); break;
2858 1 case 'v': hm_logtok_env(aTHX_ &toks, &n, &cap, "SERVER_NAME", 11); break;
2859 2 case 'P': hm_logtok_kind(&toks, &n, &cap, HM_LT_PID); break;
2860 1 default:
2861 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
2862 1 goto bad;
2863 }
2864 607 p++;
2865 607 lit = p;
2866 }
2867 86 hm_logtok_lit(&toks, &n, &cap, lit, (size_t)(p - lit));
2868 86 *out = toks; *nout = n;
2869 86 return 0;
2870 4 bad:
2871 {
2872 int i;
2873 6 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 2 4 6
2874 2 ▶ if (toks[i].lit) free(toks[i].lit);
Branch: 1 branch
BranchTrueFalseTotal
if (toks[i].lit) free(toks[i].lit); 1 1 2
2875 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
2876 }
2877 4 ▶ if (toks) free(toks);
Branch: 1 branch
BranchTrueFalseTotal
if (toks) free(toks); 1 3 4
2878 }
2879 4 return -1;
2880 }
2881  
2882 /* The JSON shape: one object per line, fixed keys, numbers unquoted. */
2883 3 static void hm_logfmt_json(pTHX_ hm_logtok **out, int *nout) {
2884 3 hm_logtok *toks = NULL;
2885 3 int n = 0, cap = 0;
2886 #define HM_JL(s) hm_logtok_lit(&toks, &n, &cap, s, sizeof(s) - 1)
2887 #define HM_JE(k) hm_logtok_env(aTHX_ &toks, &n, &cap, k, sizeof(k) - 1)
2888 3 HM_JL("{\"time\":\""); hm_logtok_kind(&toks, &n, &cap, HM_LT_TIME_ISO);
2889 3 HM_JL("\",\"remote_addr\":\""); HM_JE("REMOTE_ADDR");
2890 3 HM_JL("\",\"user\":\""); HM_JE("REMOTE_USER");
2891 3 HM_JL("\",\"method\":\""); HM_JE("REQUEST_METHOD");
2892 3 HM_JL("\",\"uri\":\""); HM_JE("REQUEST_URI");
2893 3 HM_JL("\",\"protocol\":\""); HM_JE("SERVER_PROTOCOL");
2894 3 HM_JL("\",\"status\":"); hm_logtok_kind(&toks, &n, &cap, HM_LT_STATUS);
2895 3 HM_JL(",\"bytes\":"); hm_logtok_kind(&toks, &n, &cap, HM_LT_BYTES);
2896 3 HM_JL(",\"referer\":\""); HM_JE("HTTP_REFERER");
2897 3 HM_JL("\",\"user_agent\":\""); HM_JE("HTTP_USER_AGENT");
2898 3 HM_JL("\",\"duration_us\":"); hm_logtok_kind(&toks, &n, &cap, HM_LT_DUR_US);
2899 3 HM_JL("}");
2900 #undef HM_JL
2901 #undef HM_JE
2902 3 *out = toks; *nout = n;
2903 3 }
2904  
2905 48 static const char *hm_env_str(pTHX_ HV *env, const char *key, I32 klen, STRLEN *lenp) {
2906 48 SV **s = hv_fetch(env, key, klen, 0);
2907 /*
2908 # uncoverable branch false class:ignore_covered_err
2909 # uncoverable condition right count:1 class:ignore_covered_err
2910 # uncoverable condition right count:2 class:ignore_covered_err
2911 # uncoverable condition right count:3 class:ignore_covered_err */
2912 96 ▶ if (s && *s && SvOK(*s)) return SvPV(*s, *lenp);
Branch: 3 branches
BranchTrueFalseTotal
if (s && *s && SvOK(*s)) return SvPV(*s, *lenp); 48 0 48
if (s && *s && SvOK(*s)) return SvPV(*s, *lenp); 48 0 48
if (s && *s && SvOK(*s)) return SvPV(*s, *lenp); 48 0 48
2913 0 *lenp = 0; /* # uncoverable statement */
2914 0 return NULL; /* # uncoverable statement */
2915 }
2916  
2917 /* One $env value into the line, escaped; the "absent" spelling differs
2918 * between the two shapes ("-" in CLF, an empty string in JSON). */
2919 429 static void hm_log_env_val(pTHX_ hm_loop *loop, HV *env, const hm_logtok *t) {
2920 429 HE *he = hv_fetch_ent(env, t->key, 0, 0);
2921 429 ▶ SV *v = he ? HeVAL(he) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *v = he ? HeVAL(he) : NULL; 239 190 429
2922 429 ▶ 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 */ 239 190 429
if (v && SvOK(v)) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 239 0 239
2923 STRLEN n;
2924 239 const char *s = SvPV(v, n);
2925 /*
2926 # uncoverable branch false
2927 # uncoverable condition right count:1 class:ignore_covered_err */
2928 239 ▶ if (n) { hm_log_esc(loop, s, n); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (n) { hm_log_esc(loop, s, n); return; } 239 0 239
2929 }
2930 190 ▶ if (!loop->log_json) hm_log_raw(loop, "-", 1);
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->log_json) hm_log_raw(loop, "-", 1); 46 144 190
2931 }
2932  
2933 /* Build one access-log line into the loop's log buffer by walking the
2934 * compiled format. The default compiles to Combined:
2935 * host - user [time] "METHOD URI PROTO" status bytes "referer" "ua" */
2936 69 static void hm_log_line(pTHX_ hm_loop *loop, SV *env_rv, int status, ssize_t blen) {
2937 HV *env;
2938 char num[32];
2939 int ln, i;
2940  
2941 /*
2942 # uncoverable branch true class:ignore_covered_err
2943 # uncoverable condition left count:1 class:ignore_covered_err
2944 # uncoverable condition left count:2 class:ignore_covered_err
2945 # uncoverable condition left count:3 class:ignore_covered_err */
2946 69 ▶ 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; 69 0 69
if (!(env_rv && SvROK(env_rv) && SvTYPE(SvRV(env_rv)) == SVt_PVHV)) return; 69 0 69
if (!(env_rv && SvROK(env_rv) && SvTYPE(SvRV(env_rv)) == SVt_PVHV)) return; 0 69 69
2947 69 env = (HV *)SvRV(env_rv);
2948  
2949 1572 ▶ for (i = 0; i < loop->nlogtok; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlogtok; i++) { 1503 69 1572
2950 1503 const hm_logtok *t = &loop->logtok[i];
2951 1503 switch (t->kind) { /* # uncoverable branch true count:13 class:ignore_covered_err */
2952 774 case HM_LT_LIT: hm_log_raw(loop, t->lit, t->litlen); break;
2953 429 case HM_LT_ENV: hm_log_env_val(aTHX_ loop, env, t); break;
2954 14 case HM_LT_DASH: hm_log_raw(loop, "-", 1); break;
2955 69 case HM_LT_STATUS:
2956 69 ln = (int)hm_itoa(num, (long)status); hm_log_raw(loop, num, (size_t)ln);
2957 69 break;
2958 69 case HM_LT_BYTES:
2959 69 ▶ 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); 57 12 69
2960 57 hm_log_raw(loop, num, (size_t)ln); }
2961 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
2962 5 else hm_log_raw(loop, "-", 1);
2963 69 break;
2964 4 case HM_LT_BYTES0:
2965 4 ln = (int)hm_utoa(num, blen >= 0 ? (unsigned long)blen : 0UL);
2966 4 hm_log_raw(loop, num, (size_t)ln);
2967 4 break;
2968 14 case HM_LT_TIME: {
2969 14 const char *ts = hm_log_time(loop);
2970 14 hm_log_raw(loop, "[", 1); hm_log_raw(loop, ts, strlen(ts)); hm_log_raw(loop, "]", 1);
2971 14 break;
2972 }
2973 49 case HM_LT_TIME_ISO: {
2974 49 const char *ts = hm_log_time_iso(loop);
2975 49 hm_log_raw(loop, ts, strlen(ts));
2976 49 break;
2977 }
2978 14 case HM_LT_REQLINE: {
2979 const char *s; STRLEN n;
2980 14 s = hm_env_str(aTHX_ env, "REQUEST_METHOD", 14, &n);
2981 /*
2982 # uncoverable condition right count:1 class:ignore_covered_err
2983 # uncoverable condition right count:2 class:ignore_covered_err */
2984 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
2985 14 hm_log_raw(loop, " ", 1);
2986 14 s = hm_env_str(aTHX_ env, "REQUEST_URI", 11, &n);
2987 /*
2988 # uncoverable condition right count:1 class:ignore_covered_err
2989 # uncoverable condition right count:2 class:ignore_covered_err */
2990 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
2991 14 hm_log_raw(loop, " ", 1);
2992 14 s = hm_env_str(aTHX_ env, "SERVER_PROTOCOL", 15, &n);
2993 /*
2994 # uncoverable condition right count:1 class:ignore_covered_err
2995 # uncoverable condition right count:2 class:ignore_covered_err */
2996 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
2997 14 break;
2998 }
2999 2 case HM_LT_QUERY: {
3000 const char *s; STRLEN n;
3001 2 s = hm_env_str(aTHX_ env, "QUERY_STRING", 12, &n);
3002 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
3003 2 break;
3004 }
3005 6 case HM_LT_PID:
3006 6 ln = (int)hm_itoa(num, (long)hm_os_getpid()); hm_log_raw(loop, num, (size_t)ln);
3007 6 break;
3008 59 case HM_LT_DUR_US:
3009 case HM_LT_DUR_S: {
3010 59 SV **t0 = hv_fetch(env, "psgix.request_start", 19, 0);
3011 /*
3012 # uncoverable branch false class:ignore_covered_err
3013 # uncoverable condition right count:1 class:ignore_covered_err
3014 # uncoverable condition right count:2 class:ignore_covered_err
3015 # uncoverable condition right count:3 class:ignore_covered_err */
3016 118 ▶ if (t0 && *t0 && SvOK(*t0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (t0 && *t0 && SvOK(*t0)) { 59 0 59
if (t0 && *t0 && SvOK(*t0)) { 59 0 59
if (t0 && *t0 && SvOK(*t0)) { 59 0 59
3017 59 double el = (double)hm_now_ns() / 1e9 - SvNV(*t0);
3018 59 unsigned long v = el < 0 ? 0UL
3019 59 ▶ : (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 59 59
: (unsigned long)(t->kind == HM_LT_DUR_US ? el * 1e6 : el); /* # uncoverable condition left count:1 class:ignore_covered_err */ 55 4 59
3020 59 ln = (int)hm_utoa(num, v); hm_log_raw(loop, num, (size_t)ln);
3021 }
3022 /*
3023 # uncoverable statement
3024 # uncoverable branch true
3025 # uncoverable branch false
3026 # uncoverable condition left count:1
3027 # uncoverable condition right count:1 */
3028 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
3029 0 else hm_log_raw(loop, "-", 1); /* # uncoverable statement */
3030 59 break;
3031 }
3032 }
3033 }
3034 69 hm_log_raw(loop, "\n", 1);
3035  
3036 /*
3037 # uncoverable branch true class:ignore_covered_err
3038 # uncoverable condition left count:1 class:ignore_covered_err */
3039 69 ▶ 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 69 69
3040 }
3041  
3042 /* Record one response. Fast path: format in C to the access-log fd. Else, if
3043 * a coderef was given, call $cb->($env, $status, $bytes); errors in the logger
3044 * are swallowed so they cannot take the loop down. */
3045 164 static void hm_access_log(pTHX_ hm_loop *loop, SV *env_rv, int status, ssize_t blen) {
3046 164 dSP;
3047 164 ▶ 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; } 69 95 164
3048 /*
3049 # uncoverable branch true
3050 # uncoverable condition left count:1 class:ignore_covered_err */
3051 95 ▶ if (!loop->log_cb) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->log_cb) return; 0 95 95
3052 95 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 95 95
3053 95 ▶ XPUSHs(env_rv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(env_rv); 0 95 95
3054 95 ▶ XPUSHs(sv_2mortal(newSViv(status)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSViv(status))); 0 95 95
3055 /*
3056 # uncoverable condition left count:1 class:ignore_covered_err
3057 # uncoverable condition right count:2 class:ignore_covered_err */
3058 95 ▶ 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 95 95
XPUSHs(blen >= 0 ? sv_2mortal(newSViv((IV)blen)) : &PL_sv_undef); 95 0 95
3059 95 PUTBACK;
3060 95 call_sv(loop->log_cb, G_DISCARD | G_EVAL);
3061 95 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 95 0 95
3062 }
3063  
3064 /* ---- response serialization ---------------------------------------------- */
3065  
3066 /* Reusable per-connection write buffer: keep capacity across requests so the
3067 * steady-state response path does no malloc/free. */
3068 10077 static void hm_wb_reserve(hm_conn *c, size_t need) {
3069 10077 ▶ if (c->wlen + need > c->wcap) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->wlen + need > c->wcap) { 143 9934 10077
3070 143 ▶ size_t ncap = c->wcap ? c->wcap : 4096;
Branch: 1 branch
BranchTrueFalseTotal
size_t ncap = c->wcap ? c->wcap : 4096; 19 124 143
3071 208 ▶ while (ncap < c->wlen + need) ncap *= 2;
Branch: 1 branch
BranchTrueFalseTotal
while (ncap < c->wlen + need) ncap *= 2; 65 143 208
3072 143 c->wbuf = (char *)hm_xrealloc(c->wbuf, ncap);
3073 143 c->wcap = ncap;
3074 }
3075 10077 }
3076 10076 static void hm_wb_put(hm_conn *c, const char *p, size_t n) {
3077 10076 hm_wb_reserve(c, n);
3078 10076 memcpy(c->wbuf + c->wlen, p, n);
3079 10076 c->wlen += n;
3080 10076 }
3081  
3082 static const char HM_ERR500[] =
3083 "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n"
3084 "Content-Length: 21\r\nConnection: close\r\n\r\nInternal Server Error";
3085  
3086 /* Serialize $resp: headers into c->wbuf, then try an immediate writev of
3087 * header + body chunks (zero-copy body). Whatever the kernel doesn't take
3088 * is buffered; a write watcher resumes it (backpressure). Falls back to
3089 * copy-into-buffer when bytes are already queued (pipelining) or the body
3090 * is a filehandle. Returns 0, or -1 if the connection was closed. */
3091 832 static int hm_queue_response(pTHX_ hm_conn *c, SV *resp) {
3092 832 hm_loop *loop = c->loop;
3093 832 AV *rav, *hav = NULL;
3094 SV **s0, **s1, **s2;
3095 832 SV *fh_body = NULL;
3096 832 AV *bav = NULL;
3097 832 int status = 500, has_len = 0, has_conn = 0, has_date = 0;
3098 832 int gz_out = 0;
3099 832 size_t blen = 0;
3100 832 size_t hdr_start = c->wlen;
3101 832 SSize_t bn = 0;
3102 char line[64];
3103 int ln;
3104  
3105 /*
3106 # uncoverable branch true class:ignore_covered_err
3107 # uncoverable condition left count:1 class:ignore_covered_err */
3108 832 ▶ if (loop->stopping) c->keepalive = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stopping) c->keepalive = 0; 0 832 832
3109  
3110 /*
3111 # uncoverable condition left count:2 class:ignore_covered_err
3112 # uncoverable condition left count:3 class:ignore_covered_err */
3113 832 ▶ if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) {
Branch: 3 branches
BranchTrueFalseTotal
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) { 829 3 832
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) { 829 0 829
if (!(resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) { 0 829 829
3114 3 hm_wb_put(c, HM_ERR500, sizeof(HM_ERR500) - 1);
3115 3 c->keepalive = 0;
3116 3 c->last_status = 500;
3117 3 c->last_blen = 21;
3118 3 return 0;
3119 }
3120 829 rav = (AV *)SvRV(resp);
3121 829 s0 = av_fetch(rav, 0, 0);
3122 829 s1 = av_fetch(rav, 1, 0);
3123 829 s2 = av_fetch(rav, 2, 0);
3124 /*
3125 # uncoverable branch false class:ignore_covered_err
3126 # uncoverable condition right count:1 class:ignore_covered_err
3127 # uncoverable condition right count:2 class:ignore_covered_err */
3128 829 ▶ if (s0 && *s0) status = (int)SvIV(*s0);
Branch: 2 branches
BranchTrueFalseTotal
if (s0 && *s0) status = (int)SvIV(*s0); 829 0 829
if (s0 && *s0) status = (int)SvIV(*s0); 829 0 829
3129 /*
3130 # uncoverable branch false class:ignore_covered_err
3131 # uncoverable condition right count:1 class:ignore_covered_err
3132 # uncoverable condition right count:2 class:ignore_covered_err
3133 # uncoverable condition right count:3 class:ignore_covered_err
3134 # uncoverable condition right count:4 class:ignore_covered_err */
3135 829 ▶ 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); 829 0 829
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 829 0 829
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 829 0 829
if (s1 && *s1 && SvROK(*s1) && SvTYPE(SvRV(*s1)) == SVt_PVAV) hav = (AV *)SvRV(*s1); 829 0 829
3136 829 ▶ if (!hm_headers_ok(aTHX_ hav)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_headers_ok(aTHX_ hav)) { 1 828 829
3137 1 hm_errlog("Hyperman: response header carries CR, LF or NUL; refused\n");
3138 1 hm_wb_put(c, HM_ERR500, sizeof(HM_ERR500) - 1);
3139 1 c->keepalive = 0;
3140 1 c->last_status = 500;
3141 1 c->last_blen = 21;
3142 1 return 0;
3143 }
3144 /*
3145 # uncoverable branch true class:ignore_covered_err
3146 # uncoverable condition left count:1 class:ignore_covered_err
3147 # uncoverable condition right count:1 class:ignore_covered_err
3148 # uncoverable condition left count:2 class:ignore_covered_err */
3149 828 ▶ if (s2 && !*s2) s2 = NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (s2 && !*s2) s2 = NULL; 828 0 828
if (s2 && !*s2) s2 = NULL; 0 828 828
3150  
3151 /* body length (first pass, no copy) */
3152 /*
3153 # uncoverable condition right count:1 class:ignore_covered_err
3154 # uncoverable condition right count:2 class:ignore_covered_err */
3155 1638 ▶ if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) {
Branch: 3 branches
BranchTrueFalseTotal
if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) { 828 0 828
if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) { 828 0 828
if (s2 && SvROK(*s2) && SvTYPE(SvRV(*s2)) == SVt_PVAV) { 810 18 828
3156 SSize_t i;
3157 810 bav = (AV *)SvRV(*s2);
3158 810 bn = av_len(bav) + 1;
3159 1614 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 804 810 1614
3160 804 SV **e = av_fetch(bav, i, 0);
3161 /*
3162 # uncoverable branch false class:ignore_covered_err
3163 # uncoverable condition right count:1 class:ignore_covered_err */
3164 1608 ▶ if (e) { STRLEN l; (void)SvPV(*e, l); blen += l; }
Branch: 1 branch
BranchTrueFalseTotal
if (e) { STRLEN l; (void)SvPV(*e, l); blen += l; } 804 0 804
3165 }
3166 /*
3167 # uncoverable branch false class:ignore_covered_err
3168 # uncoverable condition right count:1 class:ignore_covered_err
3169 # uncoverable condition right count:2 class:ignore_covered_err */
3170 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
3171 /* filehandle or IO::Handle-like body: stream it when it lifts to
3172 * a byte-countable source, else slurp exactly as before */
3173 18 UV clv = 0;
3174 18 int cl_seen = hm_hav_clen(aTHX_ hav, &clv);
3175 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
3176 14 blen = (size_t)c->bsrc.remaining;
3177 else {
3178 4 fh_body = hm_slurp_body(aTHX_ *s2);
3179 4 { STRLEN l; (void)SvPV(fh_body, l); blen = l; }
3180 }
3181 }
3182  
3183 /* ---- compression decision, before a byte of the response is written --
3184 * Cheapest test first, and the whole block is skipped on a server that
3185 * did not ask for it. The rules, in order:
3186 * 1. enabled, and this request accepted gzip
3187 * 2. the response carries NO Content-Encoding. This one rule covers
3188 * every hands-off case at once - a framework's precompressed file
3189 * already says `gzip`, an opted-out route says `identity` (which
3190 * we strip below), and anything else was encoded deliberately.
3191 * 3. a plain in-memory body, not a glob/reader/streamed source:
3192 * compressing those would undo the 0.20 sendfile and drip paths.
3193 * 4. big enough to be worth a gzip member's header and trailer
3194 * 5. a status that carries an entity, and never 206 (a range
3195 * describes offsets into the UNCOMPRESSED representation)
3196 * 6. a compressible media type, from an allowlist */
3197 /*
3198 # uncoverable condition right count:3 class:ignore_covered_err
3199 # uncoverable condition right count:4 class:ignore_covered_err
3200 # uncoverable condition right count:5 class:ignore_covered_err
3201 # uncoverable condition left count:8 class:ignore_covered_err */
3202 828 ▶ 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 79 749 828
if (loop->compress && c->accepts_gzip && bav && !c->bsrc.kind && !fh_body 15 64 79
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
3203 15 ▶ && blen >= loop->compress_min
Branch: 1 branch
BranchTrueFalseTotal
&& blen >= loop->compress_min 13 2 15
3204 13 ▶ && (status == 200 || status == 203)) {
Branch: 2 branches
BranchTrueFalseTotal
&& (status == 200 || status == 203)) { 1 12 13
&& (status == 200 || status == 203)) { 0 1 1
3205 12 const char *ct = NULL;
3206 12 STRLEN ctl = 0;
3207 12 int enc_seen = 0;
3208 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
3209 30 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 22 8 30
3210 22 SV **k = av_fetch(hav, i, 0);
3211 STRLEN kl;
3212 const char *ks;
3213 /*
3214 # uncoverable condition left count:1 class:ignore_covered_err
3215 # uncoverable condition left count:2 class:ignore_covered_err */
3216 26 ▶ if (!k || !*k) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!k || !*k) continue; 22 0 22
if (!k || !*k) continue; 0 22 22
3217 22 ks = SvPV(*k, kl);
3218 /* A response that sets a cookie is one a BREACH-style attacker
3219 * would want compressed beside a reflected input; left alone,
3220 * as the no-transform contract for a Set-Cookie response. */
3221 /*
3222 # uncoverable condition right count:2 class:ignore_covered_err
3223 # uncoverable condition right count:3 class:ignore_covered_err */
3224 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
3225 1 ▶ && hm_strncasecmp(ks, "Set-Cookie", 10) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Set-Cookie", 10) == 0) { 1 0 1
3226 1 enc_seen = 1;
3227 4 break;
3228 }
3229 21 ▶ if ((ks[0] | 32) != 'c') continue;
Branch: 1 branch
BranchTrueFalseTotal
if ((ks[0] | 32) != 'c') continue; 4 17 21
3230 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
3231 3 enc_seen = 1;
3232 3 break;
3233 }
3234 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
3235 12 SV **v = av_fetch(hav, i + 1, 0);
3236 /*
3237 # uncoverable branch false class:ignore_covered_err
3238 # uncoverable condition right count:1 class:ignore_covered_err
3239 # uncoverable condition right count:2 class:ignore_covered_err */
3240 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
3241 }
3242 }
3243 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
3244 /* one contiguous copy of the body, then one deflate */
3245 7 char *flat, *gz = NULL;
3246 7 size_t gzl = 0, off = 0;
3247 SSize_t j;
3248 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
3249 14 ▶ for (j = 0; j < bn; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < bn; j++) { 7 7 14
3250 7 SV **e = av_fetch(bav, j, 0);
3251 /*
3252 # uncoverable branch false class:ignore_covered_err
3253 # uncoverable condition right count:1 class:ignore_covered_err */
3254 7 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 7 0 7
3255 STRLEN l;
3256 7 const char *p = SvPV(*e, l);
3257 /* Bounded by the length the first pass measured: an
3258 * overloaded or tied element whose stringification grew
3259 * between the two calls would otherwise run past flat. */
3260 /*
3261 # uncoverable branch true class:ignore_covered_err
3262 # uncoverable condition left count:1 class:ignore_covered_err */
3263 7 ▶ if (l > blen - off) l = blen - off;
Branch: 1 branch
BranchTrueFalseTotal
if (l > blen - off) l = blen - off; 0 7 7
3264 /*
3265 # uncoverable branch false class:ignore_covered_err
3266 # uncoverable condition right count:1 class:ignore_covered_err */
3267 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
3268 }
3269 }
3270 /*
3271 # uncoverable branch false class:ignore_covered_err
3272 # uncoverable condition right count:1 class:ignore_covered_err */
3273 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
3274 /* route it down the fh_body path: one SV, one copy into the
3275 * write buffer. A response that just paid a deflate is not
3276 * the one to spend the writev fast path on. */
3277 7 fh_body = newSVpvn(gz, gzl);
3278 7 Safefree(gz);
3279 7 bav = NULL; bn = 0;
3280 7 blen = gzl;
3281 7 c->last_blen = blen;
3282 7 gz_out = 1;
3283 }
3284 7 Safefree(flat);
3285 }
3286 }
3287  
3288 /* status line + headers */
3289 828 c->last_status = status;
3290 828 c->last_blen = blen;
3291 {
3292 size_t sll;
3293 828 const char *sl = hm_status_line(status, &sll, line);
3294 828 hm_wb_put(c, sl, sll);
3295 }
3296 /*
3297 # uncoverable branch false class:ignore_covered_err
3298 # uncoverable condition right count:1 class:ignore_covered_err */
3299 828 ▶ if (hav) {
Branch: 1 branch
BranchTrueFalseTotal
if (hav) { 828 0 828
3300 828 SSize_t i, hn = av_len(hav) + 1;
3301 1733 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 905 828 1733
3302 905 SV **k = av_fetch(hav, i, 0);
3303 905 SV **v = av_fetch(hav, i + 1, 0);
3304 STRLEN kl, vl;
3305 const char *ks, *vs;
3306 /*
3307 # uncoverable condition left count:2 class:ignore_covered_err
3308 # uncoverable condition left count:3 class:ignore_covered_err
3309 # uncoverable condition left count:4 class:ignore_covered_err */
3310 912 ▶ 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 */ 904 1 905
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 904 0 904
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 904 0 904
if (!k || !*k || !v || !*v) continue; /* a hole in the array */ 0 904 904
3311 904 ks = SvPV(*k, kl);
3312 904 ▶ vs = SvPV(*v, vl);
Branch: 1 branch
BranchTrueFalseTotal
vs = SvPV(*v, vl); 635 269 904
3313 904 ▶ 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 898 904
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
3314 1 has_date = 1;
3315 /* both interesting names start with 'c', so one folded-byte test
3316 * skips the case-blind scans for every other header */
3317 904 ▶ if ((ks[0] | 32) == 'c') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ks[0] | 32) == 'c') { 889 15 904
3318 889 ▶ 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 */ 268 621 889
if (kl == 14 && hm_strncasecmp(ks, "Content-Length", 14) == 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 268 0 268
3319 268 has_len = 1;
3320 /* the app's length describes the bytes we just replaced */
3321 268 ▶ if (gz_out) { has_len = 0; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (gz_out) { has_len = 0; continue; } 2 266 268
3322 }
3323 887 ▶ 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 886 887
if (kl == 10 && hm_strncasecmp(ks, "Connection", 10) == 0) has_conn = 1; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
3324 /* `identity` is the documented way for anything above to opt
3325 * a response out (see hm_compress.h). It has done its job by
3326 * now; sending it on would be noise. */
3327 /*
3328 # uncoverable condition right count:3 class:ignore_covered_err
3329 # uncoverable condition right count:4 class:ignore_covered_err
3330 # uncoverable condition right count:5 class:ignore_covered_err */
3331 887 ▶ if (kl == 16 && vl == 8 && loop->compress
Branch: 3 branches
BranchTrueFalseTotal
if (kl == 16 && vl == 8 && loop->compress 3 884 887
if (kl == 16 && vl == 8 && loop->compress 2 1 3
if (kl == 16 && vl == 8 && loop->compress 2 0 2
3332 2 ▶ && hm_strncasecmp(ks, "Content-Encoding", 16) == 0
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Content-Encoding", 16) == 0 2 0 2
3333 2 ▶ && hm_strncasecmp(vs, "identity", 8) == 0)
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(vs, "identity", 8) == 0) 2 0 2
3334 2 continue;
3335 }
3336 /* The layer that compressed must be the layer that fixes the
3337 * validator, or a cache serves these bytes to a client that
3338 * asked for none. nginx does the same; it is in the POD because
3339 * an app author will otherwise find it by debugging. */
3340 900 ▶ 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 890 900
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
3341 3 hm_wb_put(c, ks, kl);
3342 3 hm_wb_put(c, ": ", 2);
3343 /*
3344 # uncoverable condition right count:1 class:ignore_covered_err */
3345 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
3346 2 hm_wb_put(c, vs, vl - 1);
3347 2 hm_wb_put(c, "-gzip\"", 6);
3348 } else {
3349 1 hm_wb_put(c, vs, vl);
3350 1 hm_wb_put(c, "-gzip", 5);
3351 }
3352 3 hm_wb_put(c, "\r\n", 2);
3353 3 continue;
3354 }
3355 897 hm_wb_put(c, ks, kl);
3356 897 hm_wb_put(c, ": ", 2);
3357 897 hm_wb_put(c, vs, vl);
3358 897 hm_wb_put(c, "\r\n", 2);
3359 }
3360 }
3361 828 ▶ if (gz_out) {
Branch: 1 branch
BranchTrueFalseTotal
if (gz_out) { 7 821 828
3362 7 hm_wb_put(c, "Content-Encoding: gzip\r\n", 24);
3363 7 hm_wb_put(c, "Vary: Accept-Encoding\r\n", 23);
3364 }
3365 /* Alt-Svc: how a client finds out this origin also speaks HTTP/3. It is
3366 * advertised on the HTTP/1.1 and HTTP/2 responses and never on an h3 one,
3367 * where it would be telling a client what it is already using. The value
3368 * is precomputed per listener in hm_worker_listeners - never built from a
3369 * client-supplied Host, which would let a request choose the header. */
3370 /*
3371 # uncoverable branch true class:ignore_covered_err
3372 # uncoverable condition left count:1 class:ignore_covered_err
3373 # uncoverable condition right count:1 class:ignore_covered_err
3374 # uncoverable condition left count:2 class:ignore_covered_err */
3375 828 ▶ if (c->lst && c->lst->altsvc) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->lst && c->lst->altsvc) { 828 0 828
if (c->lst && c->lst->altsvc) { 0 828 828
3376 0 hm_wb_put(c, "Alt-Svc: ", 9); /* # uncoverable statement class:ignore_covered_err */
3377 0 hm_wb_put(c, c->lst->altsvc, strlen(c->lst->altsvc)); /* # uncoverable statement class:ignore_covered_err */
3378 0 hm_wb_put(c, "\r\n", 2); /* # uncoverable statement class:ignore_covered_err */
3379 }
3380 /* 1xx/204/304 carry no entity: no Content-Length, no body (RFC 7230) */
3381 {
3382 828 ▶ int no_entity = (status < 200 || status == 204 || status == 304);
Branch: 3 branches
BranchTrueFalseTotal
int no_entity = (status < 200 || status == 204 || status == 304); 825 3 828
int no_entity = (status < 200 || status == 204 || status == 304); 822 3 825
int no_entity = (status < 200 || status == 204 || status == 304); 3 819 822
3383 828 ▶ if (no_entity) {
Branch: 1 branch
BranchTrueFalseTotal
if (no_entity) { 9 819 828
3384 /*
3385 # uncoverable branch true class:ignore_covered_err
3386 # uncoverable condition left count:1 class:ignore_covered_err */
3387 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
3388 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
3389 9 bav = NULL; bn = 0; blen = 0;
3390 819 ▶ } else if (!has_len) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!has_len) { 553 266 819
3391 553 memcpy(line, "Content-Length: ", 16);
3392 553 ln = 16 + (int)hm_utoa(line + 16, (unsigned long)blen);
3393 553 line[ln++] = '\r'; line[ln++] = '\n';
3394 553 hm_wb_put(c, line, (size_t)ln);
3395 }
3396 /* HEAD: the headers of the GET, including its Content-Length, and
3397 * not one body byte - which the app, like most apps, produced
3398 * anyway. Sending it would be read as the start of the next
3399 * response on this connection. */
3400 828 ▶ if (!no_entity && c->is_head) {
Branch: 2 branches
BranchTrueFalseTotal
if (!no_entity && c->is_head) { 819 9 828
if (!no_entity && c->is_head) { 3 816 819
3401 /*
3402 # uncoverable branch true class:ignore_covered_err
3403 # uncoverable condition left count:1 class:ignore_covered_err */
3404 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
3405 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
3406 3 bav = NULL; bn = 0; blen = 0;
3407 3 c->last_blen = 0;
3408 }
3409 }
3410 828 ▶ if (!has_date) {
Branch: 1 branch
BranchTrueFalseTotal
if (!has_date) { 827 1 828
3411 827 const char *dh = hm_date_header(loop);
3412 /*
3413 # uncoverable branch false class:ignore_covered_err
3414 # uncoverable condition right count:1 class:ignore_covered_err */
3415 827 ▶ if (dh) hm_wb_put(c, dh, HM_DATE_LEN);
Branch: 1 branch
BranchTrueFalseTotal
if (dh) hm_wb_put(c, dh, HM_DATE_LEN); 827 0 827
3416 }
3417 828 ▶ if (!has_conn)
Branch: 1 branch
BranchTrueFalseTotal
if (!has_conn) 827 1 828
3418 827 ▶ 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 667 827
3419 827 ▶ c->keepalive ? 24 : 19);
Branch: 1 branch
BranchTrueFalseTotal
c->keepalive ? 24 : 19); 160 667 827
3420 828 hm_wb_put(c, "\r\n", 2);
3421  
3422 828 loop->bytes_out += (c->wlen - hdr_start) + blen;
3423  
3424 /* fast path: nothing queued before this response -> writev header+body
3425 * straight from the response SVs, no body copy */
3426 /*
3427 # uncoverable condition right count:2 class:ignore_covered_err
3428 # uncoverable condition right count:3 class:ignore_covered_err
3429 # uncoverable condition left count:6 class:ignore_covered_err
3430 # uncoverable condition right count:9 class:ignore_covered_err
3431 # uncoverable condition right count:10 class:ignore_covered_err */
3432 828 ▶ 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 827 1 828
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 827 0 827
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 827 0 827
if (hdr_start == 0 && c->woff == 0 && !c->writing && !fh_body 816 11 827
3433 816 ▶ && (!c->ssl || hm_ktls_tx(c))
Branch: 2 branches
BranchTrueFalseTotal
&& (!c->ssl || hm_ktls_tx(c)) 43 773 816
&& (!c->ssl || hm_ktls_tx(c)) 43 0 43
3434 816 ▶ && !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) {
Branch: 4 branches
BranchTrueFalseTotal
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 804 12 816
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 792 12 804
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 792 0 792
&& !c->bsrc.kind && bav && bn >= 0 && bn < HM_IOV_MAX) { 792 0 792
3435 hm_iovec iov[HM_IOV_MAX];
3436 792 size_t total = c->wlen;
3437 792 int niov = 1;
3438 SSize_t i;
3439 ssize_t n;
3440 792 HM_IOV_SET(iov, 0, c->wbuf, c->wlen);
3441 1582 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 790 792 1582
3442 790 SV **e = av_fetch(bav, i, 0);
3443 /*
3444 # uncoverable branch false class:ignore_covered_err
3445 # uncoverable condition right count:1 class:ignore_covered_err */
3446 790 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 790 0 790
3447 790 STRLEN l; const char *p = SvPV(*e, l);
3448 /*
3449 # uncoverable branch false class:ignore_covered_err
3450 # uncoverable condition right count:1 class:ignore_covered_err */
3451 790 ▶ if (l) {
Branch: 1 branch
BranchTrueFalseTotal
if (l) { 790 0 790
3452 790 HM_IOV_SET(iov, niov, p, l);
3453 790 niov++;
3454 790 total += l;
3455 }
3456 }
3457 }
3458 792 n = hm_os_writev(c->fd, iov, niov);
3459 /*
3460 # uncoverable branch true class:ignore_covered_err
3461 # uncoverable condition left count:1 class:ignore_covered_err */
3462 792 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 0 792 792
3463 /*
3464 # uncoverable statement
3465 # uncoverable branch true
3466 # uncoverable branch false
3467 # uncoverable condition left count:1
3468 # uncoverable condition right count:1
3469 # uncoverable condition left count:2
3470 # uncoverable condition right count:2 */
3471 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
3472 0 n = 0; /* # uncoverable statement */
3473 }
3474 /*
3475 # uncoverable branch false class:ignore_covered_err
3476 # uncoverable condition right count:1 class:ignore_covered_err */
3477 792 ▶ 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 */ 789 3 792
3478 /* partial: keep the unwritten remainder in wbuf */
3479 {
3480 3 size_t skip = (size_t)n; /* # uncoverable statement class:ignore_covered_err */
3481 3 size_t hdrlen = c->wlen; /* # uncoverable statement class:ignore_covered_err */
3482 /*
3483 # uncoverable branch true class:ignore_covered_err
3484 # uncoverable statement class:ignore_covered_err
3485 # uncoverable branch false class:ignore_covered_err
3486 # uncoverable condition left count:1 class:ignore_covered_err
3487 # uncoverable condition right count:1 class:ignore_covered_err */
3488 3 ▶ if (skip < hdrlen) {
Branch: 1 branch
BranchTrueFalseTotal
if (skip < hdrlen) { 0 3 3
3489 0 memmove(c->wbuf, c->wbuf + skip, hdrlen - skip); /* # uncoverable statement */
3490 0 c->wlen = hdrlen - skip; /* # uncoverable statement */
3491 0 skip = 0; /* # uncoverable statement */
3492 } else {
3493 3 skip -= hdrlen; /* # uncoverable statement class:ignore_covered_err */
3494 3 c->wlen = 0; /* # uncoverable statement class:ignore_covered_err */
3495 }
3496 /*
3497 # uncoverable statement class:ignore_covered_err
3498 # uncoverable branch true class:ignore_covered_err
3499 # uncoverable branch false class:ignore_covered_err
3500 # uncoverable condition left count:1 class:ignore_covered_err
3501 # uncoverable condition right count:1 class:ignore_covered_err */
3502 6 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 3 3 6
3503 3 SV **e = av_fetch(bav, i, 0); /* # uncoverable statement class:ignore_covered_err */
3504 /*
3505 # uncoverable statement class:ignore_covered_err
3506 # uncoverable branch true class:ignore_covered_err
3507 # uncoverable branch false class:ignore_covered_err
3508 # uncoverable condition left count:1 class:ignore_covered_err
3509 # uncoverable condition right count:1 class:ignore_covered_err */
3510 3 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 3 0 3
3511 3 STRLEN l; const char *p = SvPV(*e, l); /* # uncoverable statement class:ignore_covered_err */
3512 /*
3513 # uncoverable branch true class:ignore_covered_err
3514 # uncoverable statement class:ignore_covered_err
3515 # uncoverable branch false class:ignore_covered_err
3516 # uncoverable condition left count:1 class:ignore_covered_err
3517 # uncoverable condition right count:1 class:ignore_covered_err */
3518 3 ▶ if (skip >= l) { skip -= l; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (skip >= l) { skip -= l; continue; } 0 3 3
3519 3 hm_wb_put(c, p + skip, l - skip); /* # uncoverable statement class:ignore_covered_err */
3520 3 skip = 0; /* # uncoverable statement class:ignore_covered_err */
3521 }
3522 }
3523 }
3524 3 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0); /* # uncoverable statement class:ignore_covered_err */
3525 3 c->writing = 1; /* # uncoverable statement class:ignore_covered_err */
3526 3 return 0; /* # uncoverable statement class:ignore_covered_err */
3527 }
3528  
3529 /* slow path: copy the body into the write buffer */
3530 36 ▶ if (fh_body) {
Branch: 1 branch
BranchTrueFalseTotal
if (fh_body) { 11 25 36
3531 11 STRLEN l; const char *p = SvPV(fh_body, l);
3532 11 hm_wb_put(c, p, l);
3533 11 SvREFCNT_dec(fh_body);
3534 25 ▶ } else if (bav) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (bav) { 1 24 25
3535 SSize_t i;
3536 2 ▶ for (i = 0; i < bn; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bn; i++) { 1 1 2
3537 1 SV **e = av_fetch(bav, i, 0);
3538 /*
3539 # uncoverable branch false class:ignore_covered_err
3540 # uncoverable condition right count:1 class:ignore_covered_err */
3541 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
3542 }
3543 }
3544 36 return 0;
3545 }
3546  
3547 /* Flush c->wbuf; on EAGAIN arm a write watcher. Returns 0 to keep the
3548 * connection, -1 if it was closed. A streaming body source (c->bsrc) is
3549 * drained here: buffer empties, source refills it a chunk at a time - or
3550 * skips the buffer entirely via sendfile(2) on a plaintext socket - so a
3551 * large file response never holds more than one chunk in memory. */
3552 3163 static int hm_flush(pTHX_ hm_conn *c) {
3553 3163 hm_loop *loop = c->loop;
3554 3163 int src_done = 0;
3555 3163 ▶ if (c->wlen == 0 && !c->bsrc.kind) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->wlen == 0 && !c->bsrc.kind) { 2241 922 3163
if (c->wlen == 0 && !c->bsrc.kind) { 7 915 922
3556 915 ▶ 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; } 692 223 915
if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; } 673 19 692
3557 242 ▶ if (c->stream_done) { /* a streamed body ended
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_done) { /* a streamed body ended 1 241 242
3558 * with nothing to flush */
3559 1 c->stream_done = 0;
3560 /*
3561 # uncoverable branch false class:ignore_covered_err
3562 # uncoverable condition right count:1 class:ignore_covered_err
3563 # uncoverable condition left count:2 class:ignore_covered_err
3564 # uncoverable condition right count:2 class:ignore_covered_err */
3565 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
3566 }
3567 242 return 0;
3568 }
3569 for (;;) {
3570 4258 ▶ while (c->woff < c->wlen) {
Branch: 1 branch
BranchTrueFalseTotal
while (c->woff < c->wlen) { 3267 991 4258
3571 3267 ssize_t n = hm_cwrite(c, c->wbuf + c->woff, c->wlen - c->woff);
3572 3267 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 1945 1322 3267
3573 1945 c->woff += (size_t)n;
3574 /*
3575 # uncoverable condition right count:1 class:ignore_covered_err
3576 # uncoverable condition left count:3 class:ignore_covered_err */
3577 1322 ▶ } else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
Branch: 3 branches
BranchTrueFalseTotal
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { 1322 0 1322
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { 2 1320 1322
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { 0 2 2
3578 /* arm a write watcher, unless the TLS engine is blocked
3579 * wanting a read (the always-armed read watcher re-drives
3580 * us then) */
3581 1320 ▶ 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 */ 6 1314 1320
if (!c->writing && !c->tls_w_wants_r) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 6 0 6
3582 6 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0);
3583 6 c->writing = 1;
3584 }
3585 1320 return 0;
3586 } else {
3587 2 hm_close(aTHX_ loop, c);
3588 2 return -1;
3589 }
3590 }
3591 /* buffer drained; keep the capacity for the next round */
3592 991 c->wlen = c->woff = 0;
3593 991 ▶ if (!c->bsrc.kind) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->bsrc.kind) break; 908 83 991
3594  
3595 #if defined(HM_HAVE_SENDFILE_LINUX) || defined(HM_HAVE_SENDFILE_FREEBSD) \
3596 || defined(HM_HAVE_SENDFILE_MACOS)
3597 /* file straight to a plaintext socket, no copy through userspace */
3598 /*
3599 # uncoverable condition left count:3 class:ignore_covered_err
3600 # uncoverable condition right count:4 class:ignore_covered_err */
3601 83 ▶ 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) { 39 44 83
if (c->bsrc.kind == 1 && (!c->ssl || hm_ktls_tx(c)) && !c->bsrc.nosf) { 1 38 39
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) { 39 0 39
3602 39 size_t want = c->bsrc.remaining < HM_SENDFILE_MAX
3603 ? (size_t)c->bsrc.remaining : HM_SENDFILE_MAX;
3604 39 ssize_t sent = -1;
3605 39 int again = 0;
3606 #if defined(HM_HAVE_SENDFILE_LINUX)
3607 39 off_t off = c->bsrc.off;
3608 39 sent = sendfile(c->fd, c->bsrc.fd, &off, want);
3609 /*
3610 # uncoverable condition right count:2 class:ignore_covered_err
3611 # uncoverable condition left count:3 class:ignore_covered_err
3612 # uncoverable condition right count:3 class:ignore_covered_err */
3613 39 ▶ again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
Branch: 3 branches
BranchTrueFalseTotal
again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)); 8 31 39
again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)); 1 7 8
again = (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)); 0 1 1
3614 #elif defined(HM_HAVE_SENDFILE_FREEBSD)
3615 off_t sbytes = 0;
3616 int r = sendfile(c->bsrc.fd, c->fd, c->bsrc.off, want,
3617 NULL, &sbytes, 0);
3618 if (r == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
3619 sent = (ssize_t)sbytes;
3620 again = (r != 0);
3621 }
3622 #elif defined(HM_HAVE_SENDFILE_MACOS)
3623 off_t len = (off_t)want;
3624 int r = sendfile(c->bsrc.fd, c->fd, c->bsrc.off, &len, NULL, 0);
3625 if (r == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
3626 sent = (ssize_t)len;
3627 again = (r != 0);
3628 }
3629 #endif
3630 39 ▶ if (sent > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (sent > 0) { 31 8 39
3631 31 c->bsrc.off += sent;
3632 31 c->bsrc.remaining -= (UV)sent;
3633 }
3634 39 ▶ if (c->bsrc.remaining == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->bsrc.remaining == 0) { 10 29 39
3635 10 hm_bsrc_release(aTHX_ &c->bsrc);
3636 10 src_done = 1;
3637 10 break;
3638 }
3639 /*
3640 # uncoverable branch false class:ignore_covered_err
3641 # uncoverable condition right count:1 class:ignore_covered_err
3642 # uncoverable condition right count:2 class:ignore_covered_err */
3643 29 ▶ if (again || sent > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (again || sent > 0) { 22 7 29
if (again || sent > 0) { 21 1 22
3644 28 ▶ if (again) {
Branch: 1 branch
BranchTrueFalseTotal
if (again) { 7 21 28
3645 7 ▶ if (!c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->writing) { 1 6 7
3646 1 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0);
3647 1 c->writing = 1;
3648 }
3649 7 return 0;
3650 }
3651 21 continue; /* kernel took it all; try more */
3652 }
3653 /* sendfile refused this pairing (filesystem, socket state):
3654 * fall back to the read path for the rest of this body */
3655 1 c->bsrc.nosf = 1; /* # uncoverable statement class:ignore_covered_err */
3656 }
3657 #endif
3658 {
3659 45 ssize_t n = hm_bsrc_fill(aTHX_ c);
3660 45 ▶ if (n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { 1 44 45
3661 /* spent (0), or ended early (-1, keepalive already off) */
3662 1 hm_bsrc_release(aTHX_ &c->bsrc);
3663 1 src_done = 1;
3664 /*
3665 # uncoverable branch true
3666 # uncoverable condition left count:1 class:ignore_covered_err */
3667 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
3668 1 break;
3669 }
3670 }
3671 }
3672 /* fully written; keep the buffer + capacity for the next response */
3673 919 c->wlen = c->woff = 0;
3674 919 ▶ if (c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->writing) { 9 910 919
3675 9 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE);
3676 9 c->writing = 0;
3677 }
3678 /* A stream handle that was told to stop producing can start again. The
3679 * callback may write, and writing calls back in here, so re-read the
3680 * connection afterwards rather than deciding on what was true before. */
3681 919 ▶ if (hm_stream_paused_n) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_stream_paused_n) { 1 918 919
3682 1 int fd = c->fd;
3683 1 hm_stream_drained(aTHX_ c);
3684 /*
3685 # uncoverable branch true
3686 # uncoverable condition left count:1 class:ignore_covered_err */
3687 1 ▶ if (loop->conns[fd] != c) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return -1; 0 1 1
3688 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
3689 }
3690 /* hm_process stopped on a full write buffer with requests still in the
3691 * read buffer: the client has now read, so serve the next of them. */
3692 918 ▶ 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); } 0 918 918
3693 918 ▶ 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; } 858 60 918
if (!c->keepalive && !c->awaiting) { hm_close(aTHX_ loop, c); return -1; } 54 804 858
3694 /* requests that pipelined in behind the stream were parked; pick them
3695 * up on the next loop turn */
3696 /* Pipelined requests behind the stream are picked up next turn - and in
3697 * completion mode the SAME push is what re-arms the read, which is why
3698 * an empty buffer is scheduled too. Without that a connection that
3699 * streamed a body would never be read from again. */
3700 864 ▶ 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 856 864
3701 864 ▶ 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 846 864
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
3702 864 return 0;
3703 }
3704  
3705 /* ---- async delivery (Future + streaming) --------------------------------- */
3706  
3707 /* Deliver an async response to a parked connection. No-op if the
3708 * connection is gone or the fd was reused. */
3709 12 static void hm_deliver(pTHX_ int fd, UV id, SV *resp) {
3710 12 hm_loop *loop = hm_cur_loop;
3711 /*
3712 # uncoverable condition right count:1 class:ignore_covered_err
3713 # uncoverable condition right count:2 class:ignore_covered_err
3714 # uncoverable condition right count:3 class:ignore_covered_err */
3715 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
3716 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
3717 /* Only a parked connection is owed a response. A responder called a
3718 * second time, or the 500 for a streaming handler that died AFTER it
3719 * had already answered, would otherwise be serialised onto a live
3720 * keep-alive connection as the reply to its next request. */
3721 10 ▶ if (!c->awaiting) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->awaiting) return; 1 9 10
3722 /* A streamed response is open on this connection: a stream handle
3723 * opened after the handler parked (the documented pattern), whose
3724 * Future has now resolved with a value that is not a response, or a
3725 * second response for one request. Serialising it here put a status
3726 * line inside a chunked body. The handle owns the response; this one
3727 * is dropped. (A handler that DIED with a writer alive is the other
3728 * case, and hm_delayed closes the connection for that.) */
3729 /*
3730 # uncoverable branch true
3731 # uncoverable condition left count:1 class:ignore_covered_err */
3732 9 ▶ if (c->stream_open) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_open) { 0 9 9
3733 /*
3734 # uncoverable statement
3735 # uncoverable branch true
3736 # uncoverable branch false
3737 # uncoverable condition left count:1
3738 # uncoverable condition right count:1 */
3739 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
3740 0 return; /* # uncoverable statement */
3741 }
3742 /* detached from inside a Future continuation (async work before an
3743 * upgrade): the app owns the socket, so drop the response it resolved
3744 * with and forget the connection */
3745 /*
3746 # uncoverable branch true
3747 # uncoverable condition left count:1 class:ignore_covered_err */
3748 9 ▶ if (c->detached) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->detached) { 0 9 9
3749 0 c->awaiting = 0; /* # uncoverable statement */
3750 /*
3751 # uncoverable statement
3752 # uncoverable branch true
3753 # uncoverable branch false
3754 # uncoverable condition left count:1
3755 # uncoverable condition right count:1 */
3756 0 ▶ if (c->env_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { 0 0 0
3757 0 hm_access_log(aTHX_ loop, c->env_sv, 101, -1); /* # uncoverable statement */
3758 0 SvREFCNT_dec(c->env_sv); /* # uncoverable statement */
3759 0 c->env_sv = NULL; /* # uncoverable statement */
3760 }
3761 0 hm_conn_release(aTHX_ loop, c); /* # uncoverable statement */
3762 0 return; /* # uncoverable statement */
3763 }
3764 9 c->awaiting = 0;
3765 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
3766 9 ▶ if (c->env_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { 2 7 9
3767 2 SV *env_rv = c->env_sv;
3768 2 c->env_sv = NULL;
3769 /*
3770 # uncoverable branch false class:ignore_covered_err
3771 # uncoverable condition right count:1 class:ignore_covered_err
3772 # uncoverable condition right count:2 class:ignore_covered_err */
3773 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
3774 2 hm_access_log(aTHX_ loop, env_rv, c->last_status,
3775 2 (ssize_t)c->last_blen);
3776 2 SvREFCNT_dec(env_rv);
3777 /*
3778 # uncoverable condition left count:1 class:ignore_covered_err
3779 # uncoverable condition left count:2 class:ignore_covered_err
3780 # uncoverable condition right count:2 class:ignore_covered_err */
3781 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
3782 0 hm_process(aTHX_ c); /* # uncoverable statement */
3783 /*
3784 # uncoverable statement
3785 # uncoverable branch true
3786 # uncoverable branch false
3787 # uncoverable condition left count:1
3788 # uncoverable condition right count:1 */
3789 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
3790 }
3791 } else {
3792 0 SvREFCNT_dec(env_rv); /* # uncoverable statement */
3793 }
3794 /* Parked connections have no read outstanding - the completion
3795 * handler skipped arming one while the response was being made - so
3796 * the re-arm is scheduled here, for the top of the next turn. */
3797 /*
3798 # uncoverable branch true class:ignore_covered_err
3799 # uncoverable condition left count:1 class:ignore_covered_err
3800 # uncoverable condition left count:2 class:ignore_covered_err
3801 # uncoverable condition right count:2 class:ignore_covered_err
3802 # uncoverable condition left count:3 class:ignore_covered_err
3803 # uncoverable condition right count:3 class:ignore_covered_err */
3804 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
3805 0 hm_again_push(loop, c); /* # uncoverable statement */
3806 2 return;
3807 }
3808 /*
3809 # uncoverable branch false class:ignore_covered_err
3810 # uncoverable condition right count:1 class:ignore_covered_err
3811 # uncoverable condition right count:2 class:ignore_covered_err
3812 # uncoverable condition right count:3 class:ignore_covered_err
3813 # uncoverable condition right count:4 class:ignore_covered_err */
3814 7 ▶ if (hm_queue_response(aTHX_ c, resp) == 0
Branch: 1 branch
BranchTrueFalseTotal
if (hm_queue_response(aTHX_ c, resp) == 0 7 0 7
3815 7 ▶ && loop->conns[fd] == c
Branch: 1 branch
BranchTrueFalseTotal
&& loop->conns[fd] == c 7 0 7
3816 7 ▶ && hm_flush(aTHX_ c) == 0
Branch: 1 branch
BranchTrueFalseTotal
&& hm_flush(aTHX_ c) == 0 7 0 7
3817 7 ▶ && loop->conns[fd] == c) {
Branch: 1 branch
BranchTrueFalseTotal
&& loop->conns[fd] == c) { 7 0 7
3818 7 hm_process(aTHX_ c);
3819 /*
3820 # uncoverable branch false class:ignore_covered_err
3821 # uncoverable condition right count:1 class:ignore_covered_err */
3822 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
3823 }
3824 /*
3825 # uncoverable condition right count:2 class:ignore_covered_err
3826 # uncoverable condition right count:3 class:ignore_covered_err */
3827 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
3828 5 hm_again_push(loop, c);
3829 }
3830  
3831 /* How a streamed HTTP/1.1 body is framed, decided once in hm_start_stream:
3832 * EOF - Connection: close, the body ends when the connection does. The
3833 * only framing there was before 0.57, and still the one for
3834 * HTTP/1.0, a request that asked to close, a 101 tunnel, an app
3835 * that wrote its own Transfer-Encoding, and a draining server.
3836 * CHUNKED - Transfer-Encoding: chunked, keep-alive kept. Every write is one
3837 * chunk, close sends the last one, and the pipeline resumes.
3838 * LENGTH - the app gave Content-Length: bytes are counted; an overrun or
3839 * a short body breaks the framing, so the connection closes.
3840 * NOBODY - 1xx, 204, 304: headers only, keep-alive kept. */
3841 #define HM_SM_EOF 0
3842 #define HM_SM_CHUNKED 1
3843 #define HM_SM_LENGTH 2
3844 #define HM_SM_NOBODY 3
3845  
3846 /* Send status+headers for a streaming response; body follows via
3847 * hm_stream_write/hm_stream_close. */
3848 /* 1 when the response was begun; 0 when it was refused because this
3849 * connection is not parked on a response, or one has already begun; -1
3850 * when the headers were refused (a 500 went out instead). Only a PARKED
3851 * connection with no response begun: a second responder call, or a stale
3852 * responder kept from an earlier request on this keep-alive connection,
3853 * otherwise wrote a status line and headers into the body being streamed,
3854 * or into the next request's response. */
3855 45 static int hm_start_stream(pTHX_ int fd, UV id, int status, SV *headers) {
3856 45 hm_loop *loop = hm_cur_loop;
3857 /*
3858 # uncoverable condition right count:1 class:ignore_covered_err
3859 # uncoverable condition right count:2 class:ignore_covered_err
3860 # uncoverable condition right count:3 class:ignore_covered_err */
3861 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
3862 char line[64];
3863 45 AV *hav = NULL;
3864 45 int has_date = 0, has_conn = 0, conn_close = 0, has_te = 0, has_len = 0;
3865 45 UV clen = 0;
3866 /*
3867 # uncoverable branch true class:ignore_covered_err
3868 # uncoverable condition left count:1 class:ignore_covered_err
3869 # uncoverable condition left count:2 class:ignore_covered_err */
3870 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
3871 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
3872 43 c->stream_open = 1;
3873 43 c->stream_serial++;
3874 43 c->stream_mode = HM_SM_EOF;
3875 43 c->stream_left = 0;
3876 43 c->stream_done = 0;
3877 43 ▶ if (c->env_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->env_sv) { 11 32 43
3878 11 hm_access_log(aTHX_ loop, c->env_sv, status, -1);
3879 11 SvREFCNT_dec(c->env_sv);
3880 11 c->env_sv = NULL;
3881 }
3882 /*
3883 # uncoverable branch false class:ignore_covered_err
3884 # uncoverable condition right count:1 class:ignore_covered_err
3885 # uncoverable condition right count:2 class:ignore_covered_err
3886 # uncoverable condition right count:3 class:ignore_covered_err */
3887 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
3888 43 hav = (AV *)SvRV(headers);
3889 43 ▶ if (!hm_headers_ok(aTHX_ hav)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_headers_ok(aTHX_ hav)) { 1 42 43
3890 1 hm_errlog("Hyperman: response header carries CR, LF or NUL; refused\n");
3891 1 hm_wb_put(c, HM_ERR500, sizeof(HM_ERR500) - 1);
3892 1 c->last_status = 500;
3893 1 c->last_blen = 21;
3894 1 c->awaiting = 0; /* nothing more is owed on this connection */
3895 1 c->stream_open = 0;
3896 1 hm_flush(aTHX_ c);
3897 1 return -1;
3898 }
3899 {
3900 size_t sll;
3901 42 const char *sl = hm_status_line(status, &sll, line);
3902 42 hm_wb_put(c, sl, sll);
3903 }
3904 /*
3905 # uncoverable branch false class:ignore_covered_err
3906 # uncoverable condition right count:1 class:ignore_covered_err */
3907 42 ▶ if (hav) {
Branch: 1 branch
BranchTrueFalseTotal
if (hav) { 42 0 42
3908 42 SSize_t i, hn = av_len(hav) + 1;
3909 94 ▶ for (i = 0; i + 1 < hn; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < hn; i += 2) { 52 42 94
3910 52 SV **k = av_fetch(hav, i, 0);
3911 52 SV **v = av_fetch(hav, i + 1, 0);
3912 STRLEN kl, vl;
3913 const char *ks, *vs;
3914 /*
3915 # uncoverable branch true class:ignore_covered_err
3916 # uncoverable condition left count:1 class:ignore_covered_err
3917 # uncoverable condition left count:2 class:ignore_covered_err
3918 # uncoverable condition left count:3 class:ignore_covered_err
3919 # uncoverable condition left count:4 class:ignore_covered_err */
3920 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
3921 52 ks = SvPV(*k, kl);
3922 52 ▶ vs = SvPV(*v, vl);
Branch: 1 branch
BranchTrueFalseTotal
vs = SvPV(*v, vl); 50 2 52
3923 /*
3924 # uncoverable condition right count:2 class:ignore_covered_err
3925 # uncoverable condition right count:3 class:ignore_covered_err */
3926 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
3927 1 has_date = 1;
3928 /*
3929 # uncoverable condition right count:2 class:ignore_covered_err
3930 # uncoverable condition right count:3 class:ignore_covered_err */
3931 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
3932 9 ▶ && hm_strncasecmp(ks, "Connection", 10) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Connection", 10) == 0) { 9 0 9
3933 9 has_conn = 1;
3934 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
3935 }
3936 /*
3937 # uncoverable condition right count:2 class:ignore_covered_err
3938 # uncoverable condition right count:3 class:ignore_covered_err */
3939 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
3940 3 ▶ && hm_strncasecmp(ks, "Content-Length", 14) == 0)
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Content-Length", 14) == 0) 3 0 3
3941 3 has_len = 1;
3942 /*
3943 # uncoverable condition right count:2 class:ignore_covered_err
3944 # uncoverable condition right count:3 class:ignore_covered_err */
3945 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
3946 1 ▶ && hm_strncasecmp(ks, "Transfer-Encoding", 17) == 0)
Branch: 1 branch
BranchTrueFalseTotal
&& hm_strncasecmp(ks, "Transfer-Encoding", 17) == 0) 1 0 1
3947 1 has_te = 1;
3948 52 hm_wb_put(c, ks, kl);
3949 52 hm_wb_put(c, ": ", 2);
3950 52 hm_wb_put(c, vs, vl);
3951 52 hm_wb_put(c, "\r\n", 2);
3952 }
3953 }
3954 42 ▶ if (!has_date) {
Branch: 1 branch
BranchTrueFalseTotal
if (!has_date) { 41 1 42
3955 41 const char *dh = hm_date_header(loop);
3956 /*
3957 # uncoverable branch false class:ignore_covered_err
3958 # uncoverable condition right count:1 class:ignore_covered_err */
3959 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
3960 }
3961 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
3962 {
3963 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
3964 /*
3965 # uncoverable condition left count:2 class:ignore_covered_err
3966 # uncoverable condition left count:5 class:ignore_covered_err
3967 # uncoverable condition left count:6 class:ignore_covered_err */
3968 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
3969 13 ▶ || conn_close || has_te) {
Branch: 2 branches
BranchTrueFalseTotal
|| conn_close || has_te) { 13 0 13
|| conn_close || has_te) { 0 13 13
3970 29 c->stream_mode = HM_SM_EOF;
3971 29 c->keepalive = 0;
3972 /*
3973 # uncoverable branch true
3974 # uncoverable condition left count:1 class:ignore_covered_err */
3975 13 ▶ } else if (no_entity) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (no_entity) { 0 13 13
3976 0 c->stream_mode = HM_SM_NOBODY; /* # uncoverable statement */
3977 13 ▶ } else if (has_len) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (has_len) { 2 11 13
3978 2 c->stream_mode = HM_SM_LENGTH;
3979 2 c->stream_left = clen;
3980 } else {
3981 11 c->stream_mode = HM_SM_CHUNKED;
3982 11 hm_wb_put(c, "Transfer-Encoding: chunked\r\n", 28);
3983 }
3984 }
3985 /* A 101 is an upgrade: the caller's own Upgrade and Connection headers
3986 * are the response, and "close" would contradict them. The connection
3987 * still ends when the handle closes - keepalive is off above. */
3988 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
3989 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
3990 else {
3991 /*
3992 # uncoverable branch false class:ignore_covered_err
3993 # uncoverable condition right count:1 class:ignore_covered_err */
3994 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
3995 13 hm_wb_put(c, "\r\n", 2);
3996 }
3997 42 hm_flush(aTHX_ c);
3998 42 return 1;
3999 }
4000  
4001 /* `serial` names the streamed response a Writer was handed out for; 0 skips
4002 * the check (the ABI stream handle has a registry of its own for that). A
4003 * writer kept past its response, or closed twice, must not touch the
4004 * response that followed on the same keep-alive connection. */
4005 /* Queue body bytes on a streamed HTTP/1.1 response, framed as the mode says.
4006 * Shared by the Writer (hm_stream_write) and the ABI stream handle
4007 * (hm_stream.h), so the two cannot disagree about the framing. Returns the
4008 * octets queued: 0 when nothing was (HEAD, no body, past the end), and the
4009 * caller then has nothing to flush. */
4010 2111 static STRLEN hm_stream_body_put(pTHX_ hm_conn *c, const char *p, STRLEN l) {
4011 /*
4012 # uncoverable branch true class:ignore_covered_err
4013 # uncoverable condition left count:1 class:ignore_covered_err
4014 # uncoverable condition left count:2 class:ignore_covered_err
4015 # uncoverable condition right count:2 class:ignore_covered_err */
4016 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
4017 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
4018 /*
4019 # uncoverable branch true
4020 # uncoverable condition left count:1 class:ignore_covered_err */
4021 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
4022 2107 ▶ if (c->stream_mode == HM_SM_LENGTH) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_mode == HM_SM_LENGTH) { 3 2104 2107
4023 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
4024 * broken, end the conn */
4025 1 l = (STRLEN)c->stream_left;
4026 1 c->keepalive = 0;
4027 }
4028 3 c->stream_left -= l;
4029 }
4030 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
4031 2104 ▶ if (c->stream_mode == HM_SM_CHUNKED) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->stream_mode == HM_SM_CHUNKED) { 17 2087 2104
4032 char sz[24];
4033 17 int n = snprintf(sz, sizeof(sz), "%" UVxf "\r\n", (UV)l);
4034 17 hm_wb_put(c, sz, (size_t)n);
4035 17 hm_wb_put(c, p, l);
4036 17 hm_wb_put(c, "\r\n", 2);
4037 } else {
4038 2087 hm_wb_put(c, p, l);
4039 }
4040 2104 c->loop->bytes_out += l;
4041 2104 return l;
4042 }
4043  
4044 /* 1: queued, and the connection holds less than HM_WB_HIWAT unwritten.
4045 * 0: queued, but the connection is holding more than that - the producer
4046 * should wait for a later write to answer 1 again before writing more
4047 * (the Perl Writer's ->write hands this back; before 0.62 it returned
4048 * nothing, and a producer feeding a slow reader grew the buffer without
4049 * bound).
4050 * -1: not written: the writer is stale (closed, or from an earlier
4051 * request on this connection). */
4052 43 static int hm_stream_write(pTHX_ int fd, UV id, UV serial, SV *data) {
4053 43 hm_loop *loop = hm_cur_loop;
4054 /*
4055 # uncoverable condition right count:2 class:ignore_covered_err
4056 # uncoverable condition right count:3 class:ignore_covered_err */
4057 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
4058 STRLEN l;
4059 const char *p;
4060 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
4061 /*
4062 # uncoverable branch true class:ignore_covered_err
4063 # uncoverable condition left count:1 class:ignore_covered_err
4064 # uncoverable condition left count:2 class:ignore_covered_err */
4065 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
4066 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
4067 37 p = SvPV(data, l);
4068 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
4069 /*
4070 # uncoverable branch true
4071 # uncoverable condition left count:1 class:ignore_covered_err */
4072 37 ▶ if (loop->conns[fd] != c) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return -1; 0 37 37
4073 37 return (c->wlen - c->woff) > HM_WB_HIWAT ? 0 : 1;
4074 }
4075  
4076 /* End a streamed HTTP/1.1 body. `trailers` is a list from hm_trailers_build
4077 * or NULL, borrowed for the duration of the call.
4078 *
4079 * Trailer fields have exactly one home in HTTP/1.1: between the last chunk
4080 * and the blank line that ends a chunked body (RFC 9112 7.1.2). So they go
4081 * out when the body is chunked, the request was not a HEAD, and the client's
4082 * TE asked for them. Otherwise the body ends as it would have with no list,
4083 * since a counted or EOF-delimited body has no place for them and a client
4084 * that did not ask may not parse them. Every name and value was checked by
4085 * hm_trailers_build, so nothing here can put a bare CR or LF on the wire. */
4086 63 static void hm_stream_finish(pTHX_ int fd, UV id, UV serial, AV *trailers) {
4087 63 hm_loop *loop = hm_cur_loop;
4088 /*
4089 # uncoverable condition right count:1 class:ignore_covered_err
4090 # uncoverable condition right count:2 class:ignore_covered_err
4091 # uncoverable condition right count:3 class:ignore_covered_err */
4092 63 ▶ 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 1 63
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
4093 63 ▶ if (!(c && c->id == id)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!(c && c->id == id)) return; 47 16 63
if (!(c && c->id == id)) return; 2 45 47
4094 /*
4095 # uncoverable branch true class:ignore_covered_err
4096 # uncoverable condition left count:1 class:ignore_covered_err
4097 # uncoverable condition left count:2 class:ignore_covered_err */
4098 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
4099 45 ▶ if (!c->awaiting) return; /* closed already */
Branch: 1 branch
BranchTrueFalseTotal
if (!c->awaiting) return; /* closed already */ 8 37 45
4100 37 c->stream_open = 0;
4101 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
4102 8 ▶ if (trailers && c->te_trailers) {
Branch: 2 branches
BranchTrueFalseTotal
if (trailers && c->te_trailers) { 0 8 8
if (trailers && c->te_trailers) { 0 0 0
4103 0 SV **field = AvARRAY(trailers);
4104 0 SSize_t i, n = av_len(trailers) + 1;
4105 0 hm_wb_put(c, "0\r\n", 3);
4106 0 ▶ for (i = 0; i < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i += 2) { 0 0 0
4107 0 hm_wb_put(c, SvPVX_const(field[i]), SvCUR(field[i]));
4108 0 hm_wb_put(c, ": ", 2);
4109 0 hm_wb_put(c, SvPVX_const(field[i + 1]), SvCUR(field[i + 1]));
4110 0 hm_wb_put(c, "\r\n", 2);
4111 }
4112 0 hm_wb_put(c, "\r\n", 2);
4113 }
4114 8 else hm_wb_put(c, "0\r\n\r\n", 5);
4115 }
4116 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
4117 1 c->keepalive = 0; /* short body: cannot keep
4118 * the connection in frame */
4119 37 c->stream_mode = HM_SM_EOF;
4120 37 c->stream_left = 0;
4121 37 c->awaiting = 0;
4122 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
4123 * pipeline when drained */
4124 37 hm_flush(aTHX_ c); /* closes when drained if keepalive is off */
4125 }
4126  
4127 25 static void hm_stream_close(pTHX_ int fd, UV id, UV serial) {
4128 25 hm_stream_finish(aTHX_ fd, id, serial, NULL);
4129 25 }
4130  
4131 /* The parked-Future continuation: when the response Future resolves,
4132 * deliver its result (or a 500 on failure, logged to psgi.errors). */
4133 XS_INTERNAL(hm_xs_park_cb);
4134 7 XS_INTERNAL(hm_xs_park_cb) {
4135 7 dXSARGS;
4136 7 hm_clos *cl = hm_clos_of(aTHX_ cv);
4137 7 SV *f, *resp = NULL;
4138 IV st;
4139 int fd;
4140 UV id;
4141 /*
4142 # uncoverable branch true class:ignore_covered_err
4143 # uncoverable condition left count:1 class:ignore_covered_err
4144 # uncoverable condition left count:2 class:ignore_covered_err */
4145 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
4146 7 f = ST(0);
4147 7 fd = (int)cl->i;
4148 7 id = cl->u;
4149 7 st = hm_any_state(aTHX_ f);
4150 7 ▶ if (st == HMF_DONE) {
Branch: 1 branch
BranchTrueFalseTotal
if (st == HMF_DONE) { 5 2 7
4151 5 ▶ if (hmf_is_future(aTHX_ f)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hmf_is_future(aTHX_ f)) { 5 0 5
4152 5 AV *vals = hmf_values_av(aTHX_ f);
4153 /*
4154 # uncoverable condition right count:1 class:ignore_covered_err
4155 # uncoverable condition right count:2 class:ignore_covered_err */
4156 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
4157 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
4158 } else {
4159 0 dSP;
4160 0 SV *got = NULL;
4161 int n;
4162 0 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 0 0
4163 0 ▶ XPUSHs(f);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(f); 0 0 0
4164 0 PUTBACK;
4165 0 n = call_method("get", G_SCALAR | G_EVAL);
4166 0 SPAGAIN;
4167 /*
4168 # uncoverable branch false class:ignore_covered_err
4169 # uncoverable condition right count:1 class:ignore_covered_err
4170 # uncoverable condition right count:2 class:ignore_covered_err */
4171 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
4172 /*
4173 # uncoverable statement
4174 # uncoverable branch true
4175 # uncoverable branch false
4176 # uncoverable condition left count:1
4177 # uncoverable condition right count:1 */
4178 0 ▶ else if (n) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
else if (n) (void)POPs; 0 0 0
4179 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
4180 /*
4181 # uncoverable branch false class:ignore_covered_err
4182 # uncoverable condition right count:1 class:ignore_covered_err */
4183 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
4184 }
4185 2 ▶ } else if (st == HMF_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (st == HMF_FAILED) { 1 1 2
4186 1 AV *errs = newAV();
4187 SV **e;
4188 STRLEN l;
4189 1 const char *msg = "unknown error";
4190 1 hm_any_values(aTHX_ f, st, errs);
4191 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
4192 /*
4193 # uncoverable branch false class:ignore_covered_err
4194 # uncoverable condition right count:1 class:ignore_covered_err
4195 # uncoverable condition right count:2 class:ignore_covered_err */
4196 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
4197 1 hm_errlog("Hyperman: async response failed: %s%s",
4198 /*
4199 # uncoverable condition right count:1 class:ignore_covered_err
4200 # uncoverable condition right count:2 class:ignore_covered_err */
4201 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
4202 1 SvREFCNT_dec((SV *)errs);
4203 }
4204 /*
4205 # uncoverable condition left count:2 class:ignore_covered_err
4206 # uncoverable condition left count:3 class:ignore_covered_err */
4207 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
4208 2 ▶ resp = hm_500_resp(aTHX_ st == HMF_DONE
Branch: 1 branch
BranchTrueFalseTotal
resp = hm_500_resp(aTHX_ st == HMF_DONE 0 2 2
4209 ? "Bad async response" : "Internal Server Error");
4210 7 hm_deliver(aTHX_ fd, id, resp);
4211 7 XSRETURN_EMPTY;
4212 }
4213  
4214 /* Park a connection awaiting a pending Future. */
4215 8 static void hm_park(pTHX_ hm_conn *c, SV *future) {
4216 8 SV *cb = hm_closure(aTHX_ hm_xs_park_cb, NULL, NULL, NULL, NULL,
4217 8 (IV)c->fd, c->id);
4218 8 hm_any_on_ready(aTHX_ future, cb);
4219 8 SvREFCNT_dec(cb);
4220 8 }
4221  
4222 /* psgi.streaming responder: [$s,$h,$b] delivers now; [$s,$h] starts a
4223 * stream and returns a Hyperman::Writer. */
4224 XS_INTERNAL(hm_xs_responder);
4225 30 XS_INTERNAL(hm_xs_responder) {
4226 30 dXSARGS;
4227 30 hm_clos *cl = hm_clos_of(aTHX_ cv);
4228 SV *r;
4229 AV *rav;
4230 SSize_t n;
4231 int fd;
4232 UV id;
4233 /*
4234 # uncoverable branch true class:ignore_covered_err
4235 # uncoverable condition left count:1 class:ignore_covered_err */
4236 30 ▶ if (!cl) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!cl) XSRETURN_EMPTY; 0 30 30
4237 30 fd = (int)cl->i;
4238 30 id = cl->u;
4239 /*
4240 # uncoverable condition left count:1 class:ignore_covered_err
4241 # uncoverable condition left count:3 class:ignore_covered_err */
4242 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
4243 1 croak("Hyperman responder expects an array reference");
4244 29 r = ST(0);
4245 29 rav = (AV *)SvRV(r);
4246 29 n = av_len(rav) + 1;
4247 29 ▶ if (n >= 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (n >= 3) { 2 27 29
4248 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
4249 4 ▶ ? hm_cur_loop->conns[fd] : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? hm_cur_loop->conns[fd] : NULL; 2 0 2
4250 /*
4251 # uncoverable condition right count:1 class:ignore_covered_err
4252 # uncoverable condition right count:2 class:ignore_covered_err */
4253 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
4254 1 croak("Hyperman responder: a response has already been started "
4255 "on this connection");
4256 1 hm_deliver(aTHX_ fd, id, r);
4257 1 XSRETURN_EMPTY;
4258 }
4259 27 ▶ if (n == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 2) { 26 1 27
4260 26 SV **s0 = av_fetch(rav, 0, 0);
4261 26 SV **s1 = av_fetch(rav, 1, 0);
4262 26 AV *w = newAV();
4263 SV *wrv;
4264 /*
4265 # uncoverable condition right count:1 class:ignore_covered_err
4266 # uncoverable condition right count:2 class:ignore_covered_err */
4267 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
4268 s1 ? *s1 : NULL);
4269 26 ▶ if (began == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (began == 0) { 2 24 26
4270 2 SvREFCNT_dec((SV *)w);
4271 2 croak("Hyperman responder: a response has already been started "
4272 "on this connection");
4273 }
4274 24 ▶ if (began < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (began < 0) { 1 23 24
4275 1 SvREFCNT_dec((SV *)w);
4276 1 croak("Hyperman responder: a response header carries CR, LF or NUL");
4277 }
4278 23 av_push(w, newSViv(fd));
4279 23 av_push(w, newSVuv(id));
4280 /* the serial of the response just begun, read back from the conn
4281 * (hm_start_stream is a no-op on a stale ticket, so 0 then) */
4282 {
4283 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
4284 46 ▶ ? hm_cur_loop->conns[fd] : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? hm_cur_loop->conns[fd] : NULL; 23 0 23
4285 /*
4286 # uncoverable condition right count:1 class:ignore_covered_err
4287 # uncoverable condition right count:2 class:ignore_covered_err */
4288 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
4289 }
4290 23 av_push(w, newSVpvs("h1"));
4291 23 wrv = newRV_noinc((SV *)w);
4292 23 sv_bless(wrv, gv_stashpv("Hyperman::Writer", GV_ADD));
4293 23 ST(0) = sv_2mortal(wrv);
4294 23 XSRETURN(1);
4295 }
4296 1 croak("Hyperman responder expects [status, headers, body] or [status, headers]");
4297 }
4298  
4299 /* psgi.streaming: run the app's coderef with a responder. */
4300 40 static void hm_delayed(pTHX_ hm_conn *c, SV *code) {
4301 40 SV *responder = hm_closure(aTHX_ hm_xs_responder, NULL, NULL, NULL, NULL,
4302 40 (IV)c->fd, c->id);
4303 40 int fd = c->fd;
4304 40 UV id = c->id;
4305 40 dSP;
4306 40 ENTER; SAVETMPS;
4307 40 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 40 40
4308 40 ▶ XPUSHs(responder);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(responder); 0 40 40
4309 40 PUTBACK;
4310 40 call_sv(code, G_DISCARD | G_EVAL);
4311 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
4312 6 hm_loop *loop = hm_cur_loop;
4313 /*
4314 # uncoverable condition right count:1 class:ignore_covered_err
4315 # uncoverable condition right count:2 class:ignore_covered_err
4316 # uncoverable condition right count:3 class:ignore_covered_err */
4317 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
4318 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
4319 /* It answered through the responder, kept the writer alive, and
4320 * died with the body part written. A 500 cannot follow a status
4321 * line already sent, and ending the body as if complete would
4322 * hand the client a cut body it may cache: the connection ends
4323 * once what was written has drained, WITHOUT the terminating
4324 * chunk. (A writer that was a lexical has already been
4325 * destroyed by the unwind and ended the body itself, the
4326 * promise a dropped writer keeps.) */
4327 2 hm_warn_died(aTHX_ "streaming handler");
4328 2 c->stream_open = 0;
4329 2 c->stream_mode = HM_SM_EOF;
4330 2 c->stream_done = 0;
4331 2 c->keepalive = 0;
4332 2 c->awaiting = 0;
4333 /*
4334 # uncoverable branch true class:ignore_covered_err
4335 # uncoverable condition left count:1 class:ignore_covered_err */
4336 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
4337 2 hm_flush(aTHX_ c);
4338 } else {
4339 4 hm_deliver(aTHX_ fd, id, hm_500_resp(aTHX_ "Internal Server Error"));
4340 }
4341 }
4342 40 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 4 36 40
4343 40 SvREFCNT_dec(responder);
4344 40 }
4345  
4346 /* ---- trailer fields: checked once, for both transports and both doors --- */
4347  
4348 #include "hm_trailers.h"
4349  
4350 /* ---- HTTP/2 (h2c via nghttp2), reusing the helpers above ----------------- */
4351  
4352 #include "hm_http2.h"
4353  
4354 /* ---- ABI v6 stream handles, over both halves above ---------------------- */
4355  
4356 #include "hm_stream.h"
4357  
4358 /* ---- HTTP/3 over QUIC: the transport, then the semantics ---------------- */
4359  
4360 #include "hm_quic.h"
4361 #include "hm_http3.h"
4362  
4363 /* ---- request processing -------------------------------------------------- */
4364  
4365 11 static void hm_again_push(hm_loop *loop, hm_conn *c) {
4366 11 ▶ if (loop->again_n == loop->again_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->again_n == loop->again_cap) { 7 4 11
4367 7 ▶ 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 7 7
4368 7 loop->again = (hm_again *)hm_xrealloc(loop->again,
4369 7 loop->again_cap * sizeof(hm_again));
4370 }
4371 11 loop->again[loop->again_n].fd = c->fd;
4372 11 loop->again[loop->again_n].id = c->id;
4373 11 loop->again_n++;
4374 11 c->again_queued = 1;
4375 11 }
4376  
4377 /* Built-in https redirect: synthesize a 301 to the same host and target on
4378 * the https port, so a plain :80 listener can bounce browsers to :443 without
4379 * ever touching the app. Host comes from the request (its :port is stripped);
4380 * the target port is omitted when it is the standard 443. */
4381 2 static SV *hm_redirect_response(pTHX_ HV *env, int https_port) {
4382 const char *host, *uri;
4383 STRLEN hlen, ulen;
4384 SV *loc;
4385 AV *rav, *hav, *bav;
4386 2 host = hm_env_str(aTHX_ env, "HTTP_HOST", 9, &hlen);
4387 2 uri = hm_env_str(aTHX_ env, "REQUEST_URI", 11, &ulen);
4388 /*
4389 # uncoverable branch true class:ignore_covered_err
4390 # uncoverable condition left count:1 class:ignore_covered_err */
4391 2 ▶ if (!uri) { uri = "/"; ulen = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (!uri) { uri = "/"; ulen = 1; } 0 2 2
4392 2 loc = newSVpvs("https://");
4393 /* Host and request-target are reflected into a response header, so stop at
4394 * the first control or space byte: a header value is only \r-delimited, so
4395 * a bare LF could otherwise smuggle a CRLF and inject/split the response.
4396 * A valid host[:port] / request-target contains no CTL or SP anyway. */
4397 /*
4398 # uncoverable branch false class:ignore_covered_err
4399 # uncoverable condition right count:1 class:ignore_covered_err */
4400 2 ▶ if (host) {
Branch: 1 branch
BranchTrueFalseTotal
if (host) { 2 0 2
4401 2 STRLEN i = 0; /* host, up to :port */
4402 2 ▶ 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 */ 2 0 2
if (hlen && host[0] == '[') { /* [v6]:port: whole */ /* # uncoverable condition right count:1 class:ignore_covered_err */ 1 1 2
4403 /*
4404 # uncoverable condition right count:1 class:ignore_covered_err
4405 # uncoverable condition right count:2 class:ignore_covered_err */
4406 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
4407 /*
4408 # uncoverable branch false class:ignore_covered_err
4409 # uncoverable condition right count:1 class:ignore_covered_err
4410 # uncoverable condition right count:2 class:ignore_covered_err */
4411 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
4412 } else {
4413 /*
4414 # uncoverable condition right count:1 class:ignore_covered_err
4415 # uncoverable condition right count:2 class:ignore_covered_err */
4416 11 ▶ while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++;
Branch: 3 branches
BranchTrueFalseTotal
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++; 11 0 11
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++; 11 0 11
while (i < hlen && (unsigned char)host[i] > ' ' && host[i] != ':') i++; 10 1 11
4417 }
4418 2 sv_catpvn(loc, host, i);
4419 }
4420 /*
4421 # uncoverable branch false class:ignore_covered_err
4422 # uncoverable condition right count:1 class:ignore_covered_err */
4423 2 ▶ if (https_port != 443) sv_catpvf(loc, ":%d", https_port);
Branch: 1 branch
BranchTrueFalseTotal
if (https_port != 443) sv_catpvf(loc, ":%d", https_port); 2 0 2
4424 {
4425 2 STRLEN i = 0; /* request-target */
4426 14 ▶ 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 */ 12 2 14
while (i < ulen && (unsigned char)uri[i] > ' ') i++; /* # uncoverable condition right count:2 class:ignore_covered_err */ 12 0 12
4427 2 sv_catpvn(loc, uri, i);
4428 }
4429  
4430 2 hav = newAV();
4431 2 av_push(hav, newSVpvs("Location")); av_push(hav, loc);
4432 2 av_push(hav, newSVpvs("Content-Length")); av_push(hav, newSVpvs("0"));
4433 2 bav = newAV();
4434 2 rav = newAV();
4435 2 av_push(rav, newSViv(301));
4436 2 av_push(rav, newRV_noinc((SV *)hav));
4437 2 av_push(rav, newRV_noinc((SV *)bav));
4438 2 return newRV_noinc((SV *)rav);
4439 }
4440  
4441 /* Process complete requests buffered in c->rbuf, capped per wakeup so one
4442 * pipelined connection can't starve the others (fairness). */
4443 969 static void hm_process(pTHX_ hm_conn *c) {
4444 969 hm_loop *loop = c->loop;
4445 969 int served = 0;
4446  
4447 /* HTTP/2: once a connection is in h2 mode, all bytes go to nghttp2.
4448 * On a fresh connection with http2 enabled, sniff the h2 preface. */
4449 969 ▶ if (c->h2) { hm_h2_input(aTHX_ c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) { hm_h2_input(aTHX_ c); return; } 0 969 969
4450 969 ▶ 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 969 969
if (c->lst && c->lst->http2 && c->nreqs == 0 && c->rlen > 0) { /* # uncoverable condition right count:1 class:ignore_covered_err */ 969 0 969
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
4451 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
4452 }
4453  
4454 153 for (;;) {
4455 /*
4456 # uncoverable branch true
4457 # uncoverable condition left count:1 class:ignore_covered_err */
4458 1122 ▶ if (c->awaiting) break; /* parked; resumes via hm_deliver */
Branch: 1 branch
BranchTrueFalseTotal
if (c->awaiting) break; /* parked; resumes via hm_deliver */ 0 1122 1122
4459 1122 ▶ 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 1111 1122
4460 flush that finishes it re-queues us */
4461 /* Responses the client has not read yet. A pipeline that never
4462 * reads would otherwise have every request in the read buffer
4463 * answered into a write buffer that only grows: hold the rest until
4464 * the drain re-queues this connection (hm_flush, backlogged). */
4465 /*
4466 # uncoverable branch true class:ignore_covered_err
4467 # uncoverable condition left count:1 class:ignore_covered_err */
4468 1111 ▶ 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; } 0 1111 1111
4469  
4470 /* RFC 9112 2.2: at least one empty line before the request line is
4471 * ignored. Stripped here so the request line is the first line and
4472 * not an empty one with the real request line read as a header. */
4473 1111 ▶ 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 */ 965 146 1111
if (c->rlen >= 2 && c->rbuf[0] == '\r' && c->rbuf[1] == '\n') { /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 964 965
if (c->rlen >= 2 && c->rbuf[0] == '\r' && c->rbuf[1] == '\n') { /* # uncoverable condition right count:3 class:ignore_covered_err */ 1 0 1
4474 1 size_t k = 0;
4475 /*
4476 # uncoverable condition right count:1 class:ignore_covered_err
4477 # uncoverable condition right count:3 class:ignore_covered_err */
4478 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
4479 1 memmove(c->rbuf, c->rbuf + k, c->rlen - k);
4480 1 c->rlen -= k;
4481 /*
4482 # uncoverable branch true
4483 # uncoverable condition left count:1 class:ignore_covered_err */
4484 1 ▶ if (c->rlen == 0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen == 0) break; 0 1 1
4485 }
4486  
4487 1111 char *end = (char *)hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4);
4488 1111 ▶ if (!end) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!end) break; 155 956 1111
4489  
4490 956 ▶ if (served >= loop->max_pipeline) { /* yield to other conns */
Branch: 1 branch
BranchTrueFalseTotal
if (served >= loop->max_pipeline) { /* yield to other conns */ 2 954 956
4491 2 hm_again_push(loop, c);
4492 2 break;
4493 }
4494  
4495 954 size_t headlen = (size_t)(end - c->rbuf);
4496 954 size_t bodystart = headlen + 4;
4497  
4498 /* one pass: framing decision + header-line index for the env build */
4499 hm_hline hidx_stack[HM_HIDX_STACK];
4500 954 const hm_hline *hidx = hidx_stack;
4501 954 int nhl = 0;
4502 954 long clen = 0;
4503 954 int frame = hm_parse_index(c->rbuf, headlen, &clen,
4504 hidx_stack, HM_HIDX_STACK, &nhl);
4505 954 ▶ if (frame == -2) { /* > HM_HIDX_STACK header lines: rescan
Branch: 1 branch
BranchTrueFalseTotal
if (frame == -2) { /* > HM_HIDX_STACK header lines: rescan 1 953 954
4506 into the loop's growable index */
4507 /*
4508 # uncoverable branch false class:ignore_covered_err
4509 # uncoverable condition right count:1 class:ignore_covered_err */
4510 1 ▶ if (nhl > loop->hidx_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (nhl > loop->hidx_cap) { 1 0 1
4511 2 loop->hidx = (hm_hline *)hm_xrealloc(loop->hidx,
4512 1 (size_t)nhl * sizeof(hm_hline));
4513 1 loop->hidx_cap = nhl;
4514 }
4515 1 frame = hm_parse_index(c->rbuf, headlen, &clen,
4516 loop->hidx, loop->hidx_cap, &nhl);
4517 1 hidx = loop->hidx;
4518 }
4519 954 ▶ if (frame) { /* smuggling/framing: reject + close */
Branch: 1 branch
BranchTrueFalseTotal
if (frame) { /* smuggling/framing: reject + close */ 9 945 954
4520 9 ▶ if (frame == 501) {
Branch: 1 branch
BranchTrueFalseTotal
if (frame == 501) { 1 8 9
4521 static const char e501[] =
4522 "HTTP/1.1 501 Not Implemented\r\nContent-Length: 0\r\n"
4523 "Connection: close\r\n\r\n";
4524 1 hm_wb_put(c, e501, sizeof(e501) - 1);
4525 } else {
4526 static const char e400[] =
4527 "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n"
4528 "Connection: close\r\n\r\n";
4529 8 hm_wb_put(c, e400, sizeof(e400) - 1);
4530 }
4531 9 c->keepalive = 0;
4532 9 break;
4533 }
4534  
4535 /* An expectation this server cannot meet is refused now, on the
4536 * headers alone - which is the answer the client asked for. */
4537 945 int expect = hm_expectation(c->rbuf, headlen);
4538 945 ▶ if (expect == HM_EXPECT_OTHER) {
Branch: 1 branch
BranchTrueFalseTotal
if (expect == HM_EXPECT_OTHER) { 2 943 945
4539 static const char e417[] =
4540 "HTTP/1.1 417 Expectation Failed\r\nContent-Length: 0\r\n"
4541 "Connection: close\r\n\r\n";
4542 2 hm_wb_put(c, e417, sizeof(e417) - 1);
4543 2 c->keepalive = 0;
4544 2 c->last_status = 417;
4545 2 break;
4546 }
4547  
4548 size_t body_consumed; /* wire octets after the headers this request uses */
4549 943 ▶ if (clen < 0) { /* chunked: validate, then decode in place */
Branch: 1 branch
BranchTrueFalseTotal
if (clen < 0) { /* chunked: validate, then decode in place */ 22 921 943
4550 22 size_t enc = 0, dec = 0;
4551 22 int r = hm_chunked_scan_from(c->rbuf + bodystart, c->rlen - bodystart,
4552 &enc, &dec, loop->max_read,
4553 &c->chunk_pos, &c->chunk_dec);
4554 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
4555 static const char e413[] =
4556 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4557 "Connection: close\r\n\r\n";
4558 2 hm_wb_put(c, e413, sizeof(e413) - 1);
4559 2 c->keepalive = 0;
4560 2 c->last_status = 413;
4561 12 break;
4562 }
4563 20 ▶ if (r < 0) { /* malformed chunked */
Branch: 1 branch
BranchTrueFalseTotal
if (r < 0) { /* malformed chunked */ 4 16 20
4564 static const char e400[] =
4565 "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n"
4566 "Connection: close\r\n\r\n";
4567 4 hm_wb_put(c, e400, sizeof(e400) - 1);
4568 4 c->keepalive = 0;
4569 4 break;
4570 }
4571 16 ▶ if (r == 0) { /* need more bytes */
Branch: 1 branch
BranchTrueFalseTotal
if (r == 0) { /* need more bytes */ 6 10 16
4572 6 c->body_phase = 1;
4573 6 c->body_t0 = loop->now;
4574 6 c->body_rx = 0;
4575 /*
4576 # uncoverable branch true
4577 # uncoverable condition left count:1 class:ignore_covered_err */
4578 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
4579 static const char e413[] =
4580 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4581 "Connection: close\r\n\r\n";
4582 0 hm_wb_put(c, e413, sizeof(e413) - 1); /* # uncoverable statement */
4583 0 c->keepalive = 0; /* # uncoverable statement */
4584 }
4585 6 else hm_send_continue(c, expect);
4586 6 break;
4587 }
4588 10 hm_chunked_compact(c->rbuf + bodystart); /* -> dec octets @ bodystart */
4589 10 clen = (long)dec;
4590 10 body_consumed = enc;
4591 } else {
4592 921 ▶ 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 914 921
4593 static const char e413[] =
4594 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4595 "Connection: close\r\n\r\n";
4596 7 hm_wb_put(c, e413, sizeof(e413) - 1);
4597 7 c->keepalive = 0;
4598 7 break;
4599 }
4600 /* A large body is drained to a temp file as it arrives rather
4601 * than accumulated here. rbuf keeps the headers and whatever
4602 * arrived after the body; the file gets the body.
4603 *
4604 * Identity framing only. A chunked body has no Content-Length to
4605 * divert on and its decoder wants the octets contiguous, so those
4606 * still accumulate - documented rather than hidden.
4607 *
4608 * Nothing about the loop changes: this still `break`s to wait for
4609 * more, and is re-driven when the socket is readable again. What
4610 * changes is that the waiting no longer costs the body. */
4611 914 ▶ if ((long)clen > HM_SPILL_BODY) {
Branch: 1 branch
BranchTrueFalseTotal
if ((long)clen > HM_SPILL_BODY) { 22 892 914
4612 22 size_t have = c->rlen - bodystart;
4613 /*
4614 # uncoverable branch true class:ignore_covered_err
4615 # uncoverable condition left count:1 class:ignore_covered_err
4616 # uncoverable condition left count:2 class:ignore_covered_err */
4617 22 ▶ 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 17 22
if (c->spill_fd < 0 && (c->spill_fd = hm_body_tmpfile()) < 0) 0 5 5
4618 0 goto hm_no_spill; /* cannot: behave as before */ /* # uncoverable statement */
4619 /*
4620 # uncoverable branch false class:ignore_covered_err
4621 # uncoverable condition right count:1 class:ignore_covered_err */
4622 22 ▶ if (have) {
Branch: 1 branch
BranchTrueFalseTotal
if (have) { 19 3 22
4623 19 size_t want = have;
4624 19 size_t room = (size_t)(clen - c->spill_got);
4625 /*
4626 # uncoverable branch true class:ignore_covered_err
4627 # uncoverable condition left count:1 class:ignore_covered_err */
4628 19 ▶ 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 18 19
4629 * request, not this body */
4630 /*
4631 # uncoverable branch false class:ignore_covered_err
4632 # uncoverable condition right count:1 class:ignore_covered_err */
4633 19 ▶ if (want) {
Branch: 1 branch
BranchTrueFalseTotal
if (want) { 19 0 19
4634 19 ssize_t w = write(c->spill_fd, c->rbuf + bodystart, want);
4635 /*
4636 # uncoverable branch true class:ignore_covered_err
4637 # uncoverable condition left count:1 class:ignore_covered_err */
4638 53 ▶ if (w <= 0) { hm_close(aTHX_ loop, c); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (w <= 0) { hm_close(aTHX_ loop, c); return; } 0 19 19
4639 19 c->spill_got += w;
4640 19 memmove(c->rbuf + bodystart, c->rbuf + bodystart + w,
4641 19 c->rlen - bodystart - w);
4642 19 c->rlen -= (size_t)w;
4643 }
4644 }
4645 22 ▶ if (c->spill_got < (long)clen) { /* await more */
Branch: 1 branch
BranchTrueFalseTotal
if (c->spill_got < (long)clen) { /* await more */ 18 4 22
4646 18 c->body_phase = 1;
4647 18 c->body_t0 = loop->now;
4648 18 c->body_rx = 0;
4649 18 hm_send_continue(c, expect);
4650 18 break;
4651 }
4652 /*
4653 # uncoverable branch true
4654 # uncoverable condition left count:1 class:ignore_covered_err */
4655 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
4656 0 hm_close(aTHX_ loop, c); return; /* # uncoverable statement */
4657 }
4658 4 body_consumed = 0; /* none of it is in rbuf */
4659 4 goto hm_have_body;
4660 }
4661 892 hm_no_spill:
4662 892 ▶ if (c->rlen - bodystart < (size_t)clen) { /* await full body */
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen - bodystart < (size_t)clen) { /* await full body */ 24 868 892
4663 24 c->body_phase = 1;
4664 24 c->body_t0 = loop->now;
4665 24 c->body_rx = 0;
4666 24 hm_send_continue(c, expect);
4667 24 break;
4668 }
4669 868 body_consumed = (size_t)clen;
4670 872 hm_have_body: ;
4671 }
4672  
4673 #ifdef HM_HAVE_NGHTTP2
4674 /* HTTP/1.1 Upgrade: h2c (cleartext, first request only). h2c-over-TLS
4675 * is forbidden by RFC 7540; the TLS path uses ALPN. */
4676 /*
4677 # uncoverable condition right count:1 class:ignore_covered_err
4678 # uncoverable condition right count:4 class:ignore_covered_err */
4679 if (c->lst && c->lst->http2 && !c->ssl && !c->h2 && c->nreqs == 0) {
4680 size_t ul = 0, sl = 0;
4681 const char *up = hm_find_header(c->rbuf, headlen, "upgrade", 7, &ul);
4682 const char *se = hm_find_header(c->rbuf, headlen, "http2-settings", 14, &sl);
4683 if (up && se && hm_ci_contains(up, ul, "h2c")) { /* # uncoverable condition right count:3 class:ignore_covered_err */
4684 static const char resp101[] =
4685 "HTTP/1.1 101 Switching Protocols\r\n"
4686 "Connection: Upgrade\r\nUpgrade: h2c\r\n\r\n";
4687 /*
4688 # uncoverable condition left count:1 class:ignore_covered_err
4689 # uncoverable condition right count:1 class:ignore_covered_err
4690 # uncoverable condition left count:2 class:ignore_covered_err */
4691 int is_head = (headlen >= 5 && hm_strncasecmp(c->rbuf, "HEAD ", 5) == 0);
4692 HV *env = hm_build_env(aTHX_ c->rbuf, headlen,
4693 c->rbuf + bodystart, clen, c, hidx, nhl);
4694 (void)hv_stores(env, "SERVER_PROTOCOL", newSVpvs("HTTP/2"));
4695 hm_wb_put(c, resp101, sizeof(resp101) - 1);
4696 {
4697 size_t consumed = bodystart + body_consumed;
4698 memmove(c->rbuf, c->rbuf + consumed, c->rlen - consumed);
4699 c->rlen -= consumed;
4700 c->nreqs++;
4701 loop->requests++;
4702 /* The request is consumed: the header and body clocks
4703 * stop here, as they do for an ordinary request below.
4704 * An h2 session never passes that point again, so one
4705 * whose upgrade arrived in two reads was closed by the
4706 * sweep as a slow request header_timeout later. */
4707 c->req_start = 0;
4708 c->body_phase = 0;
4709 c->chunk_pos = c->chunk_dec = 0;
4710 }
4711 {
4712 int rc;
4713 c->in_app = 1; /* the upgrade dispatches stream 1 */
4714 rc = hm_h2_start_upgrade(aTHX_ c, se, sl, env, is_head);
4715 c->in_app = 0;
4716 if (rc < 0 || c->close_deferred) { /* # uncoverable condition left count:2 class:ignore_covered_err */
4717 c->close_deferred = 0;
4718 hm_close(aTHX_ loop, c);
4719 return;
4720 }
4721 hm_read_resume(loop, c);
4722 }
4723 hm_h2_input(aTHX_ c); /* client's h2 preface + frames, + flush */
4724 return;
4725 }
4726 }
4727 #endif
4728  
4729 882 HV *env = hm_build_env(aTHX_ c->rbuf, headlen, c->rbuf + bodystart,
4730 clen, c, hidx, nhl);
4731 882 SV *env_rv = NULL;
4732 SV *resp;
4733 882 c->in_app = 1; /* see hm_close: a close meanwhile is deferred */
4734 882 ▶ 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 */ 882 0 882
if (c->lst && c->lst->redirect_https) { /* built-in :80 -> :443 bounce */ /* # uncoverable condition right count:1 class:ignore_covered_err */ 2 880 882
4735 2 resp = hm_redirect_response(aTHX_ env, c->lst->redirect_https);
4736 2 ▶ 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 */ 2 0 2
if (hm_logging(loop)) env_rv = newRV_noinc((SV *)env); /* # uncoverable branch true class:ignore_covered_err */ 0 2 2
4737 2 else SvREFCNT_dec((SV *)env);
4738 880 ▶ } else if (hm_logging(loop)) { /* env survives for access_log */
Branch: 2 branches
BranchTrueFalseTotal
} else if (hm_logging(loop)) { /* env survives for access_log */ 785 95 880
} else if (hm_logging(loop)) { /* env survives for access_log */ 69 716 785
4739 164 env_rv = newRV_noinc((SV *)env);
4740 164 resp = hm_call_app(aTHX_ loop, env_rv);
4741 } else {
4742 716 resp = hm_call_app0(aTHX_ loop, env);
4743 }
4744 882 c->in_app = 0;
4745 882 ▶ if (c->close_deferred) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->close_deferred) { 1 881 882
4746 /* The peer left, or the sweep gave up on it, while the handler
4747 * ran. Nothing it returned has anywhere to go. */
4748 1 c->close_deferred = 0;
4749 /*
4750 # uncoverable branch true class:ignore_covered_err
4751 # uncoverable condition left count:1 class:ignore_covered_err */
4752 1 ▶ if (env_rv) SvREFCNT_dec(env_rv);
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) SvREFCNT_dec(env_rv); 0 1 1
4753 /*
4754 # uncoverable branch false class:ignore_covered_err
4755 # uncoverable condition right count:1 class:ignore_covered_err */
4756 1 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 1 0 1
4757 1 hm_close(aTHX_ loop, c);
4758 1 return;
4759 }
4760 881 hm_read_resume(loop, c);
4761  
4762 /* The app called detach: the socket is its own now. Drop whatever it
4763 * returned (the sentinel), forget the connection, and do not touch c
4764 * again. Any bytes past this request are dropped with it - RFC 6455
4765 * forbids the client sending before the 101, so they are a protocol
4766 * violation, not data we owe anyone. */
4767 881 ▶ if (c->detached) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->detached) { 4 877 881
4768 4 ▶ if (env_rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) { 1 3 4
4769 1 hm_access_log(aTHX_ loop, env_rv, 101, -1);
4770 1 SvREFCNT_dec(env_rv);
4771 }
4772 /*
4773 # uncoverable branch false class:ignore_covered_err
4774 # uncoverable condition right count:1 class:ignore_covered_err */
4775 4 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 4 0 4
4776 4 c->nreqs++;
4777 4 loop->requests++;
4778 4 hm_conn_release(aTHX_ loop, c);
4779 4 return;
4780 }
4781  
4782 /* The app opened a 101 stream handle from inside the handler
4783 * (hm_stream_open): the connection is a tunnel now, its bytes
4784 * belong to the handle both ways, and the triplet the handler
4785 * returned is the same sentinel a detach leaves behind. Parked for
4786 * the life of the handle - stream_close unparks it, and the close
4787 * that follows (keepalive is off) ends the tunnel. Bytes that came
4788 * in with the request are the handle's too, so they are handed
4789 * over rather than parsed as a request that will never come. */
4790 877 ▶ if (c->tunnel == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->tunnel == 2) { 6 871 877
4791 6 size_t consumed = bodystart + body_consumed;
4792 6 c->tunnel = 1;
4793 /*
4794 # uncoverable branch true class:ignore_covered_err
4795 # uncoverable condition left count:1 class:ignore_covered_err */
4796 6 ▶ if (env_rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) { 0 6 6
4797 0 hm_access_log(aTHX_ loop, env_rv, 101, -1); /* # uncoverable statement */
4798 0 SvREFCNT_dec(env_rv); /* # uncoverable statement */
4799 }
4800 /*
4801 # uncoverable branch false class:ignore_covered_err
4802 # uncoverable condition right count:1 class:ignore_covered_err */
4803 6 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 6 0 6
4804 6 memmove(c->rbuf, c->rbuf + consumed, c->rlen - consumed);
4805 6 c->rlen -= consumed;
4806 6 c->req_start = 0;
4807 6 c->nreqs++;
4808 6 loop->requests++;
4809 6 ▶ if (c->rlen) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen) { 5 1 6
4810 5 size_t n = c->rlen;
4811 5 c->rlen = 0;
4812 /*
4813 # uncoverable branch true class:ignore_covered_err
4814 # uncoverable condition left count:1 class:ignore_covered_err
4815 # uncoverable condition left count:2 class:ignore_covered_err
4816 # uncoverable condition right count:2 class:ignore_covered_err */
4817 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
4818 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
4819 0 c->rlen = n; /* no read half yet: kept for it */ /* # uncoverable statement */
4820 }
4821 6 return;
4822 }
4823  
4824 871 size_t consumed = bodystart + body_consumed;
4825 871 memmove(c->rbuf, c->rbuf + consumed, c->rlen - consumed);
4826 871 c->rlen -= consumed;
4827 871 c->req_start = 0;
4828 871 c->body_phase = 0;
4829 871 c->chunk_pos = c->chunk_dec = 0;
4830 871 c->cont_sent = 0; /* the next request on this connection asks
4831 * for itself */
4832 871 served++;
4833 871 c->nreqs++;
4834 871 hm_count_request(loop);
4835  
4836 /* async: handler returned a Future -> park and wait; hold the
4837 * future so a client disconnect can cancel it */
4838 871 ▶ if (resp && hm_is_awaitable(aTHX_ resp)) {
Branch: 2 branches
BranchTrueFalseTotal
if (resp && hm_is_awaitable(aTHX_ resp)) { 868 3 871
if (resp && hm_is_awaitable(aTHX_ resp)) { 8 860 868
4839 8 c->awaiting = 1;
4840 8 c->resp_f = SvREFCNT_inc(resp);
4841 8 c->env_sv = env_rv; /* logged at delivery */
4842 8 hm_park(aTHX_ c, resp);
4843 8 SvREFCNT_dec(resp);
4844 /*
4845 # uncoverable branch true
4846 # uncoverable condition left count:1 class:ignore_covered_err */
4847 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
4848 8 break;
4849 }
4850  
4851 /* psgi.streaming: coderef response -> park, hand it a responder */
4852 863 ▶ 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 */ 860 3 863
if (resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVCV) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 860 0 860
if (resp && SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVCV) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 40 820 860
4853 40 c->awaiting = 1;
4854 40 c->env_sv = env_rv; /* logged at respond time */
4855 40 hm_delayed(aTHX_ c, resp);
4856 40 SvREFCNT_dec(resp);
4857 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
4858 17 break;
4859 }
4860  
4861 {
4862 823 int rc = hm_queue_response(aTHX_ c, resp);
4863 823 ▶ if (resp) SvREFCNT_dec(resp);
Branch: 1 branch
BranchTrueFalseTotal
if (resp) SvREFCNT_dec(resp); 820 3 823
4864 /*
4865 # uncoverable branch true
4866 # uncoverable condition left count:1 class:ignore_covered_err
4867 # uncoverable condition left count:2 class:ignore_covered_err
4868 # uncoverable condition right count:2 class:ignore_covered_err */
4869 823 ▶ 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 823 823
if (rc < 0) { if (env_rv) SvREFCNT_dec(env_rv); return; } 0 0 0
4870 }
4871 823 ▶ if (env_rv) {
Branch: 1 branch
BranchTrueFalseTotal
if (env_rv) { 150 673 823
4872 150 hm_access_log(aTHX_ loop, env_rv, c->last_status, (ssize_t)c->last_blen);
4873 150 SvREFCNT_dec(env_rv);
4874 }
4875 823 ▶ if (!c->keepalive) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->keepalive) break; 670 153 823
4876 }
4877 935 ▶ 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 */ 935 0 935
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 89 846 935
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 87 2 89
if (loop->conns[c->fd] == c && c->rlen > 0 && !c->awaiting && !c->req_start) /* # uncoverable condition right count:1 class:ignore_covered_err */ 53 34 87
4878 53 c->req_start = loop->now;
4879 }
4880  
4881 /* A tunnel's bytes belong to its handle, not the request parser: hand over
4882 * whatever the read left in rbuf, or keep it when no read half is registered
4883 * yet. ONE function for both ways a read completes - readiness (hm_readable)
4884 * and completion (HM_EV_RECV) - because the completion path once had no
4885 * tunnel branch at all and fed the bytes to hm_process, where they sat as
4886 * the start of a request that never came. Every Linux box with liburing
4887 * takes that path by default, and macOS never does, so the six smokers that
4888 * failed t/41 were the first time it ran. Returns 0 when the callback closed
4889 * the connection. */
4890 7 static int hm_tunnel_bytes(pTHX_ hm_conn *c) {
4891 7 hm_loop *loop = c->loop;
4892 7 size_t have = c->rlen;
4893 7 c->rlen = 0;
4894 /*
4895 # uncoverable branch true class:ignore_covered_err
4896 # uncoverable condition left count:1 class:ignore_covered_err */
4897 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
4898 /*
4899 # uncoverable statement
4900 # uncoverable branch true
4901 # uncoverable branch false
4902 # uncoverable condition left count:1
4903 # uncoverable condition right count:1 */
4904 0 ▶ if (loop->conns[c->fd] != c) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return 0; 0 0 0
4905 0 c->rlen = have; /* no read half yet: kept for it */ /* # uncoverable statement */
4906 }
4907 7 return loop->conns[c->fd] == c;
4908 }
4909  
4910 /* Stop and restart reading a connection whose buffer is full while a frame
4911 * on the stack still holds pointers into it (hm_readable, below). The
4912 * watcher is persistent and level-triggered, so leaving the bytes in the
4913 * socket without this would wake the loop every turn until the frame
4914 * returned. Readiness mode only: a completion-mode read is armed from the
4915 * top of a loop turn (hm_run_again), never from under a frame. */
4916 37 static void hm_read_pause(hm_loop *loop, hm_conn *c) {
4917 /*
4918 # uncoverable branch true
4919 # uncoverable condition left count:1 class:ignore_covered_err */
4920 37 ▶ if (c->read_paused) return;
Branch: 1 branch
BranchTrueFalseTotal
if (c->read_paused) return; 0 37 37
4921 37 c->read_paused = 1;
4922 37 loop->be->remove_io(loop->be, c->fd, HM_EV_READ);
4923 }
4924 918 static void hm_read_resume(hm_loop *loop, hm_conn *c) {
4925 918 ▶ if (!c->read_paused) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!c->read_paused) return; 881 37 918
4926 37 c->read_paused = 0;
4927 37 loop->be->add_io(loop->be, c->fd, HM_EV_READ, 0);
4928 }
4929  
4930 1085 static void hm_readable(pTHX_ hm_conn *c) {
4931 1085 hm_loop *loop = c->loop;
4932 98 for (;;) {
4933 1183 ▶ if (c->rlen == c->rcap) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->rlen == c->rcap) { 42 1141 1183
4934 /* A synchronous handler on the stack (in_app) may be nghttp2
4935 * reading frames out of this very buffer, or hm_process holding
4936 * offsets into it: growing it here would move it from under
4937 * them. Leave the rest in the socket until that frame returns. */
4938 /*
4939 # uncoverable branch true class:ignore_covered_err
4940 # uncoverable condition left count:1 class:ignore_covered_err
4941 # uncoverable condition left count:2 class:ignore_covered_err
4942 # uncoverable condition right count:2 class:ignore_covered_err */
4943 42 ▶ if (c->in_app && !hm_h2_reentrant(c)) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->in_app && !hm_h2_reentrant(c)) { 0 42 42
if (c->in_app && !hm_h2_reentrant(c)) { 0 0 0
4944 0 hm_read_pause(loop, c); /* # uncoverable statement */
4945 0 break; /* # uncoverable statement */
4946 }
4947 /* HTTP/2: the buffer holds frames, not a request, and nghttp2
4948 * parses them incrementally - a frame larger than the buffer is
4949 * consumed across reads. Hand over what is here and let the
4950 * level-triggered watcher bring the rest. The request ceiling
4951 * is per stream there (hm_h2_cb_data_chunk); applied to this
4952 * buffer it closed every upload over 16KB on a server whose
4953 * max_body was below that. */
4954 42 ▶ if (c->h2) break;
Branch: 1 branch
BranchTrueFalseTotal
if (c->h2) break; 0 42 42
4955 /* The same, one read earlier: the preface is in the buffer but
4956 * hm_process has not run to detect it. Let it. */
4957 42 ▶ if (hm_h2_preface_pending(c)) break;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_h2_preface_pending(c)) break; 0 42 42
4958 /* grow for large bodies; unbounded headers are rejected */
4959 /*
4960 # uncoverable condition left count:2 class:ignore_covered_err
4961 # uncoverable condition left count:3 class:ignore_covered_err */
4962 42 ▶ if (c->rcap >= loop->max_read
Branch: 1 branch
BranchTrueFalseTotal
if (c->rcap >= loop->max_read 41 1 42
4963 41 ▶ || (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 14 41
|| (c->rlen >= 65536 && !hm_memmem(c->rbuf, c->rlen, "\r\n\r\n", 4))) { 0 27 27
4964 /* The buffer is full and may not grow. Until max_body was
4965 * configurable this only happened to a genuinely enormous
4966 * request and a bare close was defensible; now that an
4967 * operator can set the ceiling BELOW the initial buffer
4968 * (HM_RBUF, 16KB), it is the ordinary way an oversize
4969 * request ends - and dropping the connection with no
4970 * response at all would leave every such client staring at
4971 * a timeout rather than a 413. Answer, then close.
4972 *
4973 * Only for a request that at least has a complete header
4974 * block: without one this is a client streaming garbage,
4975 * which has earned nothing but the close it used to get. */
4976 /*
4977 # uncoverable branch false class:ignore_covered_err
4978 # uncoverable condition right count:1 class:ignore_covered_err
4979 # uncoverable condition right count:2 class:ignore_covered_err */
4980 1 ▶ if (c->rcap >= loop->max_read
Branch: 1 branch
BranchTrueFalseTotal
if (c->rcap >= loop->max_read 1 0 1
4981 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
4982 static const char e413[] =
4983 "HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\n"
4984 "Connection: close\r\n\r\n";
4985 1 hm_wb_put(c, e413, sizeof(e413) - 1);
4986 1 c->keepalive = 0;
4987 1 c->last_status = 413;
4988 1 c->last_blen = 0;
4989 1 (void)hm_flush(aTHX_ c);
4990 /*
4991 # uncoverable branch false
4992 # uncoverable condition right count:1 class:ignore_covered_err */
4993 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
4994 }
4995 0 hm_close(aTHX_ loop, c); /* # uncoverable statement */
4996 0 return; /* # uncoverable statement */
4997 }
4998 {
4999 41 size_t ncap = c->rcap * 2; /* # uncoverable statement class:ignore_covered_err */
5000 /*
5001 # uncoverable statement class:ignore_covered_err
5002 # uncoverable branch true
5003 # uncoverable condition left count:1 */
5004 41 ▶ if (ncap > loop->max_read) ncap = loop->max_read;
Branch: 1 branch
BranchTrueFalseTotal
if (ncap > loop->max_read) ncap = loop->max_read; 0 41 41
5005 41 c->rbuf = (char *)hm_xrealloc(c->rbuf, ncap);
5006 41 c->rcap = ncap;
5007 }
5008 }
5009 1182 size_t want = c->rcap - c->rlen;
5010 1182 ssize_t n = hm_cread(c, c->rbuf + c->rlen, want);
5011 1182 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 1009 173 1182
5012 1009 c->rlen += (size_t)n;
5013 1009 c->last_rx = loop->now;
5014 1009 c->body_rx += (UV)n;
5015 /* A tunnel (a 101 stream handle): the bytes are the handle's,
5016 * not a request. Handed up read by read, so the buffer never
5017 * grows toward the ceiling that ends an oversize request. The
5018 * callback may close the stream and with it the connection.
5019 * Only once SETTLED (1): at 2 the request line is still in
5020 * rbuf and the hm_process frame that opened the tunnel owns the
5021 * buffer, so the bytes wait for it (it hands them over itself). */
5022 /*
5023 # uncoverable branch true class:ignore_covered_err
5024 # uncoverable condition left count:1 class:ignore_covered_err
5025 # uncoverable condition left count:2 class:ignore_covered_err */
5026 1009 ▶ 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 1002 1009
if (c->tunnel == 1 && !hm_tunnel_bytes(aTHX_ c)) return; 0 7 7
5027 /* A SHORT read means the socket buffer is drained: the kernel
5028 * handed over everything it had, so the confirming read that
5029 * would follow can only return EAGAIN. Stopping here removes ONE
5030 * SYSCALL FROM EVERY REQUEST - measured, an ordinary keep-alive
5031 * request cost three (two reads and a writev) and the second read
5032 * was always the empty one.
5033 *
5034 * Safe because the backends are LEVEL-triggered - no EV_CLEAR, no
5035 * EPOLLET. Draining to EAGAIN is an edge-triggered obligation,
5036 * and under level triggering anything that arrived between the
5037 * read and this line simply reports the fd readable again on the
5038 * next turn of the loop. Nothing is lost, and nothing stalls.
5039 *
5040 * NOT for TLS: a short SSL_read says nothing about the socket,
5041 * because the engine may hold more plaintext than it just
5042 * returned, and stopping on it would leave that sitting in the
5043 * engine until the peer happened to send again. */
5044 1009 ▶ if (!c->ssl && (size_t)n < want) {
Branch: 2 branches
BranchTrueFalseTotal
if (!c->ssl && (size_t)n < want) { 953 56 1009
if (!c->ssl && (size_t)n < want) { 911 42 953
5045 /* The disarm the EAGAIN branch below would have done. A write
5046 * watcher left armed over an empty write buffer re-fires
5047 * every turn and spins the worker at 100% CPU. */
5048 /*
5049 # uncoverable branch true class:ignore_covered_err
5050 # uncoverable condition left count:1 class:ignore_covered_err
5051 # uncoverable condition left count:2 class:ignore_covered_err */
5052 911 ▶ if (c->writing && c->woff == c->wlen) {
Branch: 2 branches
BranchTrueFalseTotal
if (c->writing && c->woff == c->wlen) { 0 911 911
if (c->writing && c->woff == c->wlen) { 0 0 0
5053 0 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE); /* # uncoverable statement */
5054 0 c->writing = 0; /* # uncoverable statement */
5055 }
5056 911 break;
5057 }
5058 173 ▶ } else if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (n == 0) { 122 51 173
5059 /* The peer half-closed a tunnel: the same thing a zero read
5060 * means to a socket owner, told to the handle as fin before
5061 * the connection goes and the abort callback says the rest. */
5062 /*
5063 # uncoverable branch true class:ignore_covered_err
5064 # uncoverable condition left count:1 class:ignore_covered_err */
5065 122 ▶ if (c->tunnel) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->tunnel) { 0 122 122
5066 0 (void)hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, 0, 1); /* # uncoverable statement */
5067 /*
5068 # uncoverable statement
5069 # uncoverable branch true
5070 # uncoverable branch false
5071 # uncoverable condition left count:1
5072 # uncoverable condition right count:1 */
5073 0 ▶ if (loop->conns[c->fd] != c) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] != c) return; 0 0 0
5074 }
5075 122 hm_close(aTHX_ loop, c);
5076 122 return;
5077 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
5078 /* TLS read blocked wanting writable: arm a write watcher so a
5079 * write-readiness event re-drives us. Once it unblocks, drop that
5080 * watcher again unless there is queued output still waiting on
5081 * it. The backends are level-triggered, so a watcher left armed
5082 * over an empty write buffer is not merely untidy - it re-fires
5083 * every turn of the loop and spins the worker at 100% CPU. */
5084 /*
5085 # uncoverable branch true
5086 # uncoverable condition left count:1 class:ignore_covered_err */
5087 51 ▶ if (c->tls_r_wants_w) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->tls_r_wants_w) { 0 51 51
5088 /*
5089 # uncoverable statement
5090 # uncoverable branch true
5091 # uncoverable branch false
5092 # uncoverable condition left count:1
5093 # uncoverable condition right count:1 */
5094 0 ▶ if (!c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->writing) { 0 0 0
5095 0 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0); /* # uncoverable statement */
5096 0 c->writing = 1; /* # uncoverable statement */
5097 }
5098 /*
5099 # uncoverable branch true class:ignore_covered_err
5100 # uncoverable condition left count:1 class:ignore_covered_err
5101 # uncoverable condition left count:2 class:ignore_covered_err
5102 # uncoverable condition right count:2 class:ignore_covered_err */
5103 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
5104 0 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE); /* # uncoverable statement */
5105 0 c->writing = 0; /* # uncoverable statement */
5106 }
5107 51 break;
5108 } else {
5109 0 hm_close(aTHX_ loop, c);
5110 0 return;
5111 }
5112 }
5113 962 hm_lru_touch(loop, c);
5114 /* A tunnel carries no requests. A connection whose synchronous handler
5115 * is on the stack (its ->get pumped this loop) keeps the new bytes in
5116 * rbuf for the hm_process frame already running on it: a second frame
5117 * would consume the pipeline from under the first one's offsets. */
5118 /* HTTP/2 is the exception once nghttp2 has returned: a handler waiting
5119 * for its body to drain is waiting for the window updates in these very
5120 * bytes, and hm_h2_input takes them without starting another request. */
5121 962 ▶ 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); 953 9 962
if (!c->tunnel && (!c->in_app || hm_h2_reentrant(c))) hm_process(aTHX_ c); 2 951 953
if (!c->tunnel && (!c->in_app || hm_h2_reentrant(c))) hm_process(aTHX_ c); 0 2 2
5122 962 ▶ if (loop->conns[c->fd] == c) hm_flush(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] == c) hm_flush(aTHX_ c); 934 28 962
5123 }
5124  
5125 static hm_tw *hm_add_timer_watch_c(hm_loop *loop, double secs,
5126 hm_abi_timer_cb cb, void *ud);
5127 static void hm_tls_handshake(pTHX_ hm_conn *c);
5128  
5129 /* The first bytes on a proxy_protocol listener. PEEK, so the header can be
5130 * parsed without taking anything behind it off the socket: a ClientHello or
5131 * an h2 preface in the same segment stays in the kernel for hm_tls_wrap and
5132 * hm_h2_detect, which then run exactly as on a listener without a proxy.
5133 * Only a complete header is consumed, by a read of exactly its length. A
5134 * partial one is re-peeked when the level-triggered watcher fires again;
5135 * one that never completes is closed by hm_sweep after header_timeout. */
5136 /* A partial PROXY header: the bytes stay in the socket (peeked, not read)
5137 * and the watcher is level-triggered, so returning to the loop would wake
5138 * it again at once - a peer that sent "PROXY TCP4 1" and stopped had the
5139 * worker re-peeking at 100% CPU until header_timeout. Reading is paused
5140 * and resumed by this timer; the sweep still closes a header that never
5141 * completes. */
5142 typedef struct { hm_loop *loop; int fd; UV id; } hm_pp_retry;
5143 37 static void hm_proxy_retry(pTHX_ void *ud) {
5144 37 hm_pp_retry *r = (hm_pp_retry *)ud;
5145 /*
5146 # uncoverable condition right count:1 class:ignore_covered_err
5147 # uncoverable condition right count:2 class:ignore_covered_err */
5148 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
5149 PERL_UNUSED_CONTEXT;
5150 /*
5151 # uncoverable branch false class:ignore_covered_err
5152 # uncoverable condition right count:1 class:ignore_covered_err
5153 # uncoverable condition right count:2 class:ignore_covered_err
5154 # uncoverable condition right count:3 class:ignore_covered_err */
5155 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
5156 37 free(r);
5157 37 }
5158  
5159 50 static void hm_proxy_readable(pTHX_ hm_conn *c) {
5160 50 hm_loop *loop = c->loop;
5161 unsigned char buf[HM_PP_MAX];
5162 hm_pp_result r;
5163 ssize_t n;
5164 long len;
5165 50 n = hm_os_recv_peek(c->fd, buf, sizeof(buf));
5166 /*
5167 # uncoverable branch true class:ignore_covered_err
5168 # uncoverable condition left count:1 class:ignore_covered_err */
5169 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
5170 /*
5171 # uncoverable branch true
5172 # uncoverable condition left count:1 class:ignore_covered_err */
5173 50 ▶ if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n < 0) { 0 50 50
5174 /*
5175 # uncoverable statement
5176 # uncoverable branch true
5177 # uncoverable branch false
5178 # uncoverable condition left count:1
5179 # uncoverable condition right count:1
5180 # uncoverable condition left count:2
5181 # uncoverable condition right count:2
5182 # uncoverable condition left count:3
5183 # uncoverable condition right count:3 */
5184 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
5185 0 hm_close(aTHX_ loop, c); return; /* # uncoverable statement */
5186 }
5187 50 len = hm_pp_parse(buf, (size_t)n, &r);
5188 50 ▶ if (len == 0) { /* more to come */
Branch: 1 branch
BranchTrueFalseTotal
if (len == 0) { /* more to come */ 37 13 50
5189 hm_pp_retry *rt;
5190 /*
5191 # uncoverable branch true
5192 # uncoverable condition left count:1 class:ignore_covered_err */
5193 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
5194 37 rt = (hm_pp_retry *)hm_xmalloc(sizeof(*rt));
5195 37 rt->loop = loop; rt->fd = c->fd; rt->id = c->id;
5196 37 hm_read_pause(loop, c);
5197 /*
5198 # uncoverable branch true class:ignore_covered_err
5199 # uncoverable condition left count:1 class:ignore_covered_err */
5200 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
5201 0 free(rt); /* no timer: level-triggered it is */ /* # uncoverable statement */
5202 0 hm_read_resume(loop, c); /* # uncoverable statement */
5203 }
5204 37 return;
5205 }
5206 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
5207 /* take exactly the header; what follows is the client's first bytes */
5208 {
5209 11 ssize_t got = hm_os_recv(c->fd, buf, (size_t)len);
5210 /*
5211 # uncoverable branch true
5212 # uncoverable condition left count:1 class:ignore_covered_err */
5213 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
5214 }
5215 11 c->pp_wait = 0;
5216 11 c->req_start = 0;
5217 /* The proxy's own address is kept for $env; the client's replaces the
5218 * peer, so REMOTE_ADDR, the access log, the rate limiter and the
5219 * denylist all see the client from here on. */
5220 11 memcpy(c->proxy_addr, c->peer, sizeof(c->proxy_addr));
5221 11 c->proxy_port = c->peer_port;
5222 11 ▶ if (r.family) {
Branch: 1 branch
BranchTrueFalseTotal
if (r.family) { 9 2 11
5223 static const unsigned char v4map[12] =
5224 { 0,0,0,0, 0,0,0,0, 0,0,0xff,0xff };
5225 9 c->peer[0] = '\0';
5226 /* ::ffff:a.b.c.d is the IPv4 client it names (see hm_fmt_peer) */
5227 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
5228 1 (void)inet_ntop(AF_INET, (const unsigned char *)r.src + 12,
5229 1 c->peer, (socklen_t)sizeof(c->peer));
5230 else
5231 8 (void)inet_ntop(r.family, r.src, c->peer, (socklen_t)sizeof(c->peer));
5232 9 c->peer_port = r.src_port;
5233 /* the denylist, again, now for the real client; the accept-time
5234 * check saw the proxy */
5235 9 ▶ if (hm_sa_deny_check(c->peer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_deny_check(c->peer)) { 1 8 9
5236 1 loop->denied++;
5237 1 hm_close(aTHX_ loop, c);
5238 1 return;
5239 }
5240 }
5241 /* distinct clients counts clients, not proxies, so the accept path
5242 * skipped it on this listener */
5243 /*
5244 # uncoverable branch true class:ignore_covered_err
5245 # uncoverable condition left count:1 class:ignore_covered_err
5246 # uncoverable condition left count:2 class:ignore_covered_err
5247 # uncoverable condition right count:2 class:ignore_covered_err */
5248 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
5249 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
5250 1 hm_tls_wrap(c, c->lst->tls_ctx);
5251 1 hm_tls_handshake(aTHX_ c);
5252 } else {
5253 9 hm_readable(aTHX_ c);
5254 }
5255 }
5256  
5257 /* accept(2) failed for want of a descriptor. The listener is level-readable
5258 * and stays so, so simply returning would wake the loop again at once and
5259 * spin the worker at 100% CPU until the table had room. Reclaim an idle
5260 * keep-alive connection when there is one; otherwise stop listening for a
5261 * tenth of a second and come back. */
5262 /* Listeners whose starvation timer could not be armed (hm_accept_starved):
5263 * re-added from the top of a loop turn. */
5264 /*
5265 # uncoverable statement class:ignore_covered_err
5266 # uncoverable subroutine class:ignore_covered_err */
5267 28888 static void hm_accept_unstarve(hm_loop *loop) {
5268 int i;
5269 28888 loop->starved_retry = 0; /* # uncoverable statement class:ignore_covered_err */
5270 /*
5271 # uncoverable statement class:ignore_covered_err
5272 # uncoverable branch true class:ignore_covered_err
5273 # uncoverable branch false class:ignore_covered_err */
5274 57776 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 28888 28888 57776
5275 28888 hm_listener *l = &loop->listeners[i]; /* # uncoverable statement class:ignore_covered_err */
5276 /*
5277 # uncoverable statement class:ignore_covered_err
5278 # uncoverable branch true class:ignore_covered_err
5279 # uncoverable branch false class:ignore_covered_err
5280 # uncoverable condition left count:1 */
5281 28888 ▶ if (l->starved != 2) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (l->starved != 2) continue; 0 28888 28888
5282 28888 l->starved = 0; /* # uncoverable statement class:ignore_covered_err */
5283 /*
5284 # uncoverable statement class:ignore_covered_err
5285 # uncoverable branch false
5286 # uncoverable condition right count:1
5287 # uncoverable condition right count:2 */
5288 28888 ▶ if (!loop->stopping && l->fd >= 0)
Branch: 2 branches
BranchTrueFalseTotal
if (!loop->stopping && l->fd >= 0) 28888 0 28888
if (!loop->stopping && l->fd >= 0) 28888 0 28888
5289 28888 loop->be->add_io(loop->be, l->fd, HM_EV_READ, 0); /* # uncoverable statement class:ignore_covered_err */
5290 }
5291 28888 }
5292  
5293 typedef struct { hm_loop *loop; hm_listener *lst; } hm_starve;
5294 /*
5295 # uncoverable statement class:ignore_covered_err
5296 # uncoverable subroutine class:ignore_covered_err */
5297 0 static void hm_accept_rearm(pTHX_ void *ud) {
5298 0 hm_starve *s = (hm_starve *)ud; /* # uncoverable statement class:ignore_covered_err */
5299 0 s->lst->starved = 0; /* # uncoverable statement class:ignore_covered_err */
5300 /*
5301 # uncoverable statement class:ignore_covered_err
5302 # uncoverable branch true class:ignore_covered_err
5303 # uncoverable branch false class:ignore_covered_err
5304 # uncoverable condition left count:1 class:ignore_covered_err
5305 # uncoverable condition right count:1 class:ignore_covered_err
5306 # uncoverable condition left count:2 class:ignore_covered_err
5307 # uncoverable condition right count:2 class:ignore_covered_err */
5308 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
5309 0 s->loop->be->add_io(s->loop->be, s->lst->fd, HM_EV_READ, 0); /* # uncoverable statement class:ignore_covered_err */
5310 0 free(s); /* # uncoverable statement class:ignore_covered_err */
5311 0 }
5312 28948 static void hm_accept_starved(pTHX_ hm_loop *loop, hm_listener *lst) {
5313 28948 hm_conn *c = loop->lru_head; /* oldest activity first */
5314 924476 ▶ while (c) {
Branch: 1 branch
BranchTrueFalseTotal
while (c) { 895588 28888 924476
5315 /*
5316 # uncoverable condition right count:1 class:ignore_covered_err
5317 # uncoverable condition right count:2 class:ignore_covered_err
5318 # uncoverable condition right count:3 class:ignore_covered_err
5319 # uncoverable condition right count:4 class:ignore_covered_err
5320 # uncoverable condition right count:5 class:ignore_covered_err
5321 # uncoverable condition right count:6 class:ignore_covered_err
5322 # uncoverable condition right count:7 class:ignore_covered_err
5323 # uncoverable condition right count:8 class:ignore_covered_err */
5324 895588 ▶ 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 895588 0 895588
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 895588 0 895588
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 895588 0 895588
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 895588 0 895588
if (!c->awaiting && !c->in_app && !c->h2 && !c->tunnel && !c->tls_hs 895588 0 895588
5325 895588 ▶ && c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind
Branch: 3 branches
BranchTrueFalseTotal
&& c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind 895588 0 895588
&& c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind 895588 0 895588
&& c->rlen == 0 && c->wlen == c->woff && !c->bsrc.kind 895588 0 895588
5326 895588 ▶ && c->nreqs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& c->nreqs > 0) { 60 895528 895588
5327 60 hm_close(aTHX_ loop, c);
5328 60 return;
5329 }
5330 895528 c = c->lru_next;
5331 }
5332 /*
5333 # uncoverable branch true
5334 # uncoverable condition left count:1 class:ignore_covered_err */
5335 28888 ▶ if (lst->starved) return;
Branch: 1 branch
BranchTrueFalseTotal
if (lst->starved) return; 0 28888 28888
5336 {
5337 28888 hm_starve *s = (hm_starve *)hm_xmalloc(sizeof(*s));
5338 28888 s->loop = loop;
5339 28888 s->lst = lst;
5340 28888 lst->starved = 1;
5341 28888 loop->be->remove_io(loop->be, lst->fd, HM_EV_READ);
5342 /*
5343 # uncoverable branch false class:ignore_covered_err
5344 # uncoverable condition right count:1 class:ignore_covered_err */
5345 28888 ▶ 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)) { 28888 0 28888
5346 /* No timer to be had: on epoll a timer IS a descriptor, and
5347 * this is the descriptor famine. Re-added from the top of a
5348 * later loop turn instead (hm_accept_unstarve) - the next close
5349 * wakes the loop, and the interval sweep does within five
5350 * seconds regardless. Before this the listener stayed removed
5351 * and the worker never accepted again. */
5352 28888 free(s); /* # uncoverable statement class:ignore_covered_err */
5353 28888 lst->starved = 2; /* # uncoverable statement class:ignore_covered_err */
5354 28888 loop->starved_retry = 1; /* # uncoverable statement class:ignore_covered_err */
5355 }
5356 }
5357 }
5358  
5359 30011 static void hm_accept(pTHX_ hm_loop *loop, hm_listener *lst) {
5360 30011 int batch = 0;
5361 /*
5362 # uncoverable branch true class:ignore_covered_err
5363 # uncoverable condition left count:1 class:ignore_covered_err */
5364 30011 ▶ if (loop->stopping) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stopping) return; 0 30011 30011
5365 936 for (;;) {
5366 struct sockaddr_storage ss;
5367 30947 socklen_t slen = sizeof(ss);
5368 hm_conn *c;
5369 char peer[INET6_ADDRSTRLEN];
5370 int peer_port;
5371 #ifdef HM_HAVE_ACCEPT4
5372 /* Non-blocking and close-on-exec in the accept itself: two fewer
5373 * syscalls per connection, and no window in which a fork from a
5374 * handler inherits a client socket. */
5375 30947 int fd = accept4(lst->fd, (struct sockaddr *)&ss, &slen,
5376 SOCK_NONBLOCK | SOCK_CLOEXEC);
5377 #else
5378 int fd = hm_os_accept(lst->fd, (struct sockaddr *)&ss, &slen);
5379 #endif
5380 30947 ▶ if (fd < 0) { /* EAGAIN: drained */
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { /* EAGAIN: drained */ 30011 936 30947
5381 30011 ▶ 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 */ 1063 28948 30011
if (errno == EMFILE || errno == ENFILE) /* # uncoverable condition left count:2 class:ignore_covered_err */ 0 1063 1063
5382 28948 hm_accept_starved(aTHX_ loop, lst);
5383 30011 break;
5384 }
5385 /*
5386 # uncoverable branch true class:ignore_covered_err
5387 # uncoverable condition left count:1 class:ignore_covered_err */
5388 937 ▶ if (fd >= HM_MAXFD) { hm_os_close(fd); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= HM_MAXFD) { hm_os_close(fd); continue; } 0 936 936
5389 #if !defined(HM_HAVE_ACCEPT4) && !defined(_WIN32)
5390 /* Not into anything the application execs: a child that kept a
5391 * client socket open held the client past the response, and could
5392 * write onto it (onto a TLS socket, raw). hm_new_conn sets
5393 * non-blocking. */
5394 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
5395 #endif
5396 /* Denylist: format the peer and drop a blocked IP HERE, before a
5397 * connection object is allocated or a byte is read - the cheapest
5398 * possible rejection. Fails open (no arena -> deny_check is 0). */
5399 936 hm_fmt_peer(peer, sizeof(peer), &peer_port, (struct sockaddr *)&ss);
5400 936 ▶ 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 935 936
5401 /* Distinct clients, opt-in: with the sketch off this is one load of
5402 * a NULL, with it on a hash and a CAS-max on the peer string. */
5403 /*
5404 # uncoverable condition right count:2 class:ignore_covered_err
5405 # uncoverable condition right count:3 class:ignore_covered_err */
5406 935 ▶ 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 723 935
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
5407 935 c = hm_new_conn(loop, fd, lst);
5408 935 memcpy(c->peer, peer, sizeof(c->peer));
5409 935 c->peer_port = peer_port;
5410 935 loop->accepts++;
5411 /*
5412 # uncoverable branch true
5413 # uncoverable condition left count:1 class:ignore_covered_err */
5414 935 ▶ 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 935 935
5415 /* fairness: don't grab the whole queue in one wakeup; the listener
5416 * stays level-readable, so the next iteration resumes */
5417 /*
5418 # uncoverable branch true
5419 # uncoverable condition left count:1 class:ignore_covered_err */
5420 935 ▶ if (++batch >= 64) break;
Branch: 1 branch
BranchTrueFalseTotal
if (++batch >= 64) break; 0 935 935
5421 }
5422 }
5423  
5424 /* Drive the TLS handshake for a connection still in SSL_accept. On success,
5425 * switch to HTTP/2 if ALPN negotiated h2, then start serving. WANT_READ waits
5426 * on the always-armed read watcher; WANT_WRITE arms a write watcher. */
5427 117 static void hm_tls_handshake(pTHX_ hm_conn *c) {
5428 #ifdef HM_HAVE_OPENSSL
5429 117 hm_loop *loop = c->loop;
5430 117 SSL *ssl = (SSL *)c->ssl;
5431 int r;
5432 117 ERR_clear_error();
5433 117 r = SSL_accept(ssl);
5434 117 ▶ if (r == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (r == 1) { 54 63 117
5435 54 c->tls_hs = 0;
5436 54 hm_tls_capture_peer(c); /* protocol/cipher + any client cert */
5437 /* What the kernel took, for stats and tests. The write paths do NOT
5438 * read this - they ask OpenSSL again each time, because the answer
5439 * can change under them (see hm_ktls_tx). */
5440 54 c->ktls_tx = hm_ktls_tx(c) ? 1 : 0;
5441 /*
5442 # uncoverable branch true class:ignore_covered_err
5443 # uncoverable condition left count:1 class:ignore_covered_err */
5444 54 ▶ if (c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (c->writing) { 0 54 54
5445 0 loop->be->remove_io(loop->be, c->fd, HM_EV_WRITE); /* # uncoverable statement */
5446 0 c->writing = 0; /* # uncoverable statement */
5447 }
5448 #ifdef HM_HAVE_NGHTTP2
5449 if (c->lst && c->lst->http2) { /* # uncoverable condition right count:1 class:ignore_covered_err */
5450 const unsigned char *proto = NULL;
5451 unsigned int plen = 0;
5452 SSL_get0_alpn_selected(ssl, &proto, &plen);
5453 /*
5454 # uncoverable branch true class:ignore_covered_err
5455 # uncoverable condition left count:1 class:ignore_covered_err
5456 # uncoverable condition left count:2 class:ignore_covered_err
5457 # uncoverable condition right count:2 class:ignore_covered_err
5458 # uncoverable condition left count:3 class:ignore_covered_err */
5459 if (plen == 2 && memcmp(proto, "h2", 2) == 0
5460 && hm_h2_start(aTHX_ c) < 0) {
5461 hm_close(aTHX_ loop, c); /* # uncoverable statement */
5462 return; /* # uncoverable statement */
5463 }
5464 }
5465 #endif
5466 54 hm_readable(aTHX_ c); /* any early app data is already buffered */
5467 54 return;
5468 }
5469 {
5470 63 int e = SSL_get_error(ssl, r);
5471 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
5472 /*
5473 # uncoverable branch true
5474 # uncoverable condition left count:1 class:ignore_covered_err */
5475 7 ▶ if (e == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (e == SSL_ERROR_WANT_WRITE) { 0 7 7
5476 /*
5477 # uncoverable statement
5478 # uncoverable branch true
5479 # uncoverable branch false
5480 # uncoverable condition left count:1
5481 # uncoverable condition right count:1 */
5482 0 ▶ if (!c->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!c->writing) { 0 0 0
5483 0 loop->be->add_io(loop->be, c->fd, HM_EV_WRITE, 0); /* # uncoverable statement */
5484 0 c->writing = 1; /* # uncoverable statement */
5485 }
5486 0 return; /* # uncoverable statement */
5487 }
5488 7 hm_close(aTHX_ loop, c); /* handshake failed */
5489 }
5490 #else
5491 (void)c;
5492 #endif
5493 }
5494  
5495 /* ---- timeouts, shutdown, loop -------------------------------------------- */
5496  
5497 /* Resolve an app io-readiness Future (fd became readable/writable), or run
5498 * a persistent watch_io callback. */
5499 22 static void hm_io_event(pTHX_ hm_loop *loop, int fd, int mask, hm_iow *slot) {
5500 22 SV *sv = slot->sv;
5501 PERL_UNUSED_VAR(loop);
5502 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
5503 /*
5504 # uncoverable branch true
5505 # uncoverable condition left count:1 class:ignore_covered_err */
5506 16 ▶ if (!sv) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return; 0 16 16
5507 16 ▶ if (slot->is_cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (slot->is_cb) { 8 8 16
5508 8 dSP;
5509 8 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 8 8
5510 8 PUTBACK;
5511 8 call_sv(sv, G_DISCARD | G_EVAL);
5512 8 hm_warn_died(aTHX_ "watch_io callback");
5513 8 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 8 8
5514 } else {
5515 8 slot->sv = NULL; /* one-shot */
5516 8 hmf_done0(aTHX_ sv);
5517 8 SvREFCNT_dec(sv);
5518 }
5519 }
5520  
5521 /* Timeout sweep: close idle keep-alive connections and slow/partial-request
5522 * (slowloris) connections. Runs on a periodic backend timer. */
5523 15 static void hm_sweep(pTHX_ hm_loop *loop) {
5524 15 hm_conn *c = loop->lru_head;
5525 15 time_t now = time(NULL);
5526 15 loop->now = now;
5527 24 ▶ while (c) {
Branch: 1 branch
BranchTrueFalseTotal
while (c) { 9 15 24
5528 9 hm_conn *next = c->lru_next;
5529 /* in_app: a synchronous handler is running for it (and pumping
5530 * this loop); its request is in progress, not idle */
5531 /*
5532 # uncoverable branch false class:ignore_covered_err
5533 # uncoverable condition right count:1 class:ignore_covered_err
5534 # uncoverable condition right count:2 class:ignore_covered_err */
5535 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
5536 9 double idle = difftime(now, c->last_active);
5537 /* Two guards for two phases. The header block is timed from the
5538 * request's first byte, which is the slowloris guard. Once the
5539 * headers are complete and a body is arriving, the clock is
5540 * progress: a body that has not delivered a byte for
5541 * body_timeout is dead, however long it has been coming - and
5542 * an upload slower than max_body in header_timeout is not. */
5543 17 ▶ int slow = c->req_start &&
Branch: 1 branch
BranchTrueFalseTotal
int slow = c->req_start && 8 1 9
5544 8 ▶ (c->body_phase
Branch: 1 branch
BranchTrueFalseTotal
(c->body_phase 5 3 8
5545 5 ▶ ? difftime(now, c->last_rx) > loop->body_timeout
Branch: 1 branch
BranchTrueFalseTotal
? difftime(now, c->last_rx) > loop->body_timeout 1 4 5
5546 3 ▶ : difftime(now, c->req_start) > loop->header_timeout);
Branch: 1 branch
BranchTrueFalseTotal
: difftime(now, c->req_start) > loop->header_timeout); 2 1 3
5547 /* Two OPT-IN floors under the progress clock, for a deployment
5548 * that cannot afford a body dribbled a byte a minute for ever:
5549 * a minimum average rate over the body phase (judged after two
5550 * seconds, so a first slow segment is not a verdict), and a
5551 * ceiling on the whole request from its first byte. */
5552 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
5553 1 double span = difftime(now, c->body_t0);
5554 /*
5555 # uncoverable branch false class:ignore_covered_err
5556 # uncoverable condition right count:1 class:ignore_covered_err
5557 # uncoverable condition right count:2 class:ignore_covered_err */
5558 1 ▶ if (span >= 2.0
Branch: 1 branch
BranchTrueFalseTotal
if (span >= 2.0 1 0 1
5559 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
5560 1 slow = 1;
5561 }
5562 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
5563 1 ▶ && difftime(now, c->req_start) > loop->request_timeout)
Branch: 1 branch
BranchTrueFalseTotal
&& difftime(now, c->req_start) > loop->request_timeout) 1 0 1
5564 1 slow = 1;
5565 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
5566 6 hm_close(aTHX_ loop, c);
5567 }
5568 9 c = next;
5569 }
5570 15 }
5571  
5572 /* Graceful shutdown: stop accepting, close idle (served) connections,
5573 * finish in-flight work bounded by shutdown_grace; responses during
5574 * shutdown get Connection: close. */
5575 134 static void hm_on_signal(pTHX_ hm_loop *loop) {
5576 hm_conn *c;
5577 /*
5578 # uncoverable branch true
5579 # uncoverable condition left count:1 class:ignore_covered_err */
5580 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
5581 134 loop->stopping = 1;
5582 {
5583 int i;
5584 279 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 145 134 279
5585 /*
5586 # uncoverable branch false class:ignore_covered_err
5587 # uncoverable condition right count:1 class:ignore_covered_err */
5588 145 ▶ if (loop->listeners[i].fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].fd >= 0) 145 0 145
5589 145 loop->be->remove_io(loop->be, loop->listeners[i].fd, HM_EV_READ);
5590 /* Stop taking datagrams too. A QUIC connection already up is
5591 * not on this fd in any fd-indexed sense, so nothing else here
5592 * reaches it; draining those needs a graceful shutdown that
5593 * sends CONNECTION_CLOSE, which is not implemented. */
5594 /*
5595 # uncoverable branch true class:ignore_covered_err
5596 # uncoverable condition left count:1 class:ignore_covered_err */
5597 145 ▶ if (loop->listeners[i].udp_fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].udp_fd >= 0) 0 145 145
5598 0 loop->be->remove_io(loop->be, loop->listeners[i].udp_fd, HM_EV_READ); /* # uncoverable statement class:ignore_covered_err */
5599 }
5600 }
5601 134 hm_quic_shutdown(aTHX_ loop);
5602 134 c = loop->lru_head;
5603 136 ▶ while (c) {
Branch: 1 branch
BranchTrueFalseTotal
while (c) { 2 134 136
5604 2 hm_conn *next = c->lru_next;
5605 /*
5606 # uncoverable condition right count:2 class:ignore_covered_err
5607 # uncoverable condition right count:3 class:ignore_covered_err
5608 # uncoverable condition right count:4 class:ignore_covered_err */
5609 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
5610 1 ▶ && c->nreqs > 0)
Branch: 1 branch
BranchTrueFalseTotal
&& c->nreqs > 0) 1 0 1
5611 1 hm_close(aTHX_ loop, c);
5612 2 c = next;
5613 }
5614 134 ▶ if (loop->nconns == 0) { loop->stop = 1; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (loop->nconns == 0) { loop->stop = 1; return; } 133 1 134
5615 /*
5616 # uncoverable branch false class:ignore_covered_err
5617 # uncoverable condition right count:1 class:ignore_covered_err */
5618 1 ▶ if (!loop->hardstop_tw) {
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->hardstop_tw) { 1 0 1
5619 1 loop->hardstop_tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
5620 1 loop->hardstop_tw->kind = HM_TW_HARDSTOP;
5621 1 loop->hardstop_tw->loop = loop;
5622 1 loop->hardstop_tw->due = hm_tw_due(loop->shutdown_grace);
5623 /*
5624 # uncoverable branch true class:ignore_covered_err
5625 # uncoverable condition left count:1 class:ignore_covered_err */
5626 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
5627 0 hm_errlog("Hyperman: cannot arm the shutdown_grace timer: %s\n", strerror(errno)); /* # uncoverable statement */
5628 }
5629 }
5630  
5631 /* Drain a snapshot of the deferred (run-soon) queue. */
5632 33643 static void hm_run_deferred(pTHX_ hm_loop *loop) {
5633 33643 SSize_t n = av_len(loop->deferred) + 1;
5634 SSize_t i;
5635 33643 ▶ if (!n) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!n) return; 33641 2 33643
5636 2 ENTER; SAVETMPS;
5637 5 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 3 2 5
5638 3 SV *cb = sv_2mortal(av_shift(loop->deferred));
5639 3 dSP;
5640 3 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 3 3
5641 3 PUTBACK;
5642 3 call_sv(cb, G_DISCARD | G_EVAL);
5643 3 hm_warn_died(aTHX_ "deferred callback");
5644 }
5645 2 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 2 0 2
5646 }
5647  
5648 /* Re-process connections that hit the fairness cap with requests still
5649 * buffered, now that everyone else has been serviced. */
5650 33643 static void hm_run_again(pTHX_ hm_loop *loop) {
5651 33643 int n = loop->again_n;
5652 int i;
5653 33643 ▶ if (!n) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!n) return; 33632 11 33643
5654 11 loop->again_n = 0;
5655 22 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 11 11 22
5656 11 hm_conn *c = loop->conns[loop->again[i].fd];
5657 /*
5658 # uncoverable branch false class:ignore_covered_err
5659 # uncoverable condition right count:1 class:ignore_covered_err
5660 # uncoverable condition right count:2 class:ignore_covered_err */
5661 11 ▶ 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; 11 0 11
if (c && c->id == loop->again[i].id) c->again_queued = 0; 11 0 11
5662 /*
5663 # uncoverable branch false class:ignore_covered_err
5664 # uncoverable condition right count:1 class:ignore_covered_err
5665 # uncoverable condition right count:2 class:ignore_covered_err
5666 # uncoverable condition right count:3 class:ignore_covered_err
5667 # uncoverable condition right count:4 class:ignore_covered_err
5668 # uncoverable condition left count:5 class:ignore_covered_err
5669 # uncoverable condition right count:5 class:ignore_covered_err
5670 # uncoverable condition right count:6 class:ignore_covered_err */
5671 11 ▶ if (c && c->id == loop->again[i].id && !c->awaiting
Branch: 3 branches
BranchTrueFalseTotal
if (c && c->id == loop->again[i].id && !c->awaiting 11 0 11
if (c && c->id == loop->again[i].id && !c->awaiting 11 0 11
if (c && c->id == loop->again[i].id && !c->awaiting 11 0 11
5672 11 ▶ && (!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 11 11
&& (!c->in_app || hm_h2_reentrant(c)) && !c->bsrc.kind) { 0 0 0
&& (!c->in_app || hm_h2_reentrant(c)) && !c->bsrc.kind) { 11 0 11
5673 11 hm_process(aTHX_ c);
5674 /*
5675 # uncoverable branch false class:ignore_covered_err
5676 # uncoverable condition right count:1 class:ignore_covered_err */
5677 11 ▶ if (loop->conns[c->fd] == c) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[c->fd] == c) { 11 0 11
5678 11 hm_flush(aTHX_ c);
5679 /* THE re-arm point for completion mode, and the reason
5680 * anything that wants a read armed calls hm_again_push
5681 * rather than arming for itself: this runs at the top of a
5682 * loop turn, so hm_process is not on the stack and growing
5683 * the read buffer cannot pull the ground out from under the
5684 * pointers it holds into it. */
5685 11 ▶ 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); 10 1 11
5686 }
5687 }
5688 }
5689 }
5690  
5691 33718 static void hm_dispatch(pTHX_ hm_loop *loop, hm_event *ev) {
5692 /*
5693 # uncoverable branch true count:3
5694 # uncoverable branch true count:6 class:ignore_covered_err */
5695 33718 switch (ev->kind) {
5696 2353 case HM_EV_TIMER: {
5697 2353 hm_tw *tw = (hm_tw *)ev->udata;
5698 2353 ▶ 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 */ 2353 0 2353
if (!tw || tw->dead) return; /* cancelled earlier in this batch */ /* # uncoverable condition left count:1 class:ignore_covered_err */ 10 2343 2353
5699 2343 ▶ 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; } 15 2328 2343
5700 /* A oneshot delivered before its deadline (NetBSD's kqueue timed a
5701 * 300ms Fetch request out at 246ms on a smoker) is re-armed for the
5702 * remainder and not fired. The backend has already dropped it, so the
5703 * same watcher is free to re-add; each re-arm is shorter, so a
5704 * backend that is always early still converges. Within a
5705 * millisecond is the backends' own rounding. */
5706 /*
5707 # uncoverable branch false class:ignore_covered_err
5708 # uncoverable condition right count:1 class:ignore_covered_err */
5709 2328 ▶ if (tw->due > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (tw->due > 0) { 2328 0 2328
5710 2328 double left = tw->due - (double)hm_now_ns() / 1e9;
5711 /* could not re-arm (no descriptor for a timerfd): early beats
5712 * never, so it fires now */
5713 /*
5714 # uncoverable branch true class:ignore_covered_err
5715 # uncoverable condition left count:1 class:ignore_covered_err
5716 # uncoverable condition left count:2 class:ignore_covered_err
5717 # uncoverable condition right count:2 class:ignore_covered_err */
5718 2328 ▶ 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 2328 2328
if (left > 1e-3 && loop->be->add_timer(loop->be, left, 1, tw) == 0) 0 0 0
5719 0 return; /* # uncoverable statement */
5720 }
5721 2328 ▶ 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 2327 2328
5722 2327 ▶ 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 */ 278 2049 2327
5723 278 hm_abi_timer_cb cb = tw->c_cb;
5724 278 void *ud = tw->c_ud;
5725 278 free(tw);
5726 278 cb(aTHX_ ud);
5727 278 return;
5728 }
5729 {
5730 2049 SV *sv = tw->sv;
5731 2049 int kind = tw->kind;
5732 2049 free(tw);
5733 2049 ▶ if (kind == HM_TW_FUTURE) {
Branch: 1 branch
BranchTrueFalseTotal
if (kind == HM_TW_FUTURE) { 2020 29 2049
5734 2020 hmf_done0(aTHX_ sv);
5735 } else {
5736 29 dSP;
5737 29 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 29 29
5738 29 PUTBACK;
5739 29 call_sv(sv, G_DISCARD | G_EVAL);
5740 29 hm_warn_died(aTHX_ "timer callback");
5741 29 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 29 29
5742 }
5743 2049 SvREFCNT_dec(sv);
5744 }
5745 2049 return;
5746 }
5747 129 case HM_EV_SIGNAL:
5748 129 ▶ if (ev->fd == SIGUSR1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ev->fd == SIGUSR1) { 3 126 129
5749 /* With a scoreboard the supervisor prints every row itself and
5750 * never forwards USR1; this line is the no-arena fallback. */
5751 /*
5752 # uncoverable branch false class:ignore_covered_err
5753 # uncoverable condition right count:1 class:ignore_covered_err */
5754 3 ▶ if (!hm_sa_board_live())
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_sa_board_live()) 3 0 3
5755 6 hm_errlog("Hyperman worker %d: requests=%lu accepts=%lu conns=%d "
5756 "bytes_out=%lu backend=%s%s\n",
5757 3 hm_os_getpid(),
5758 3 (unsigned long)loop->requests, (unsigned long)loop->accepts,
5759 3 loop->nconns, (unsigned long)loop->bytes_out,
5760 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
5761 3 return;
5762 }
5763 126 hm_on_signal(aTHX_ loop);
5764 126 return;
5765 0 case HM_EV_RECV: { /* # uncoverable statement */
5766 /* A read the core asked for has finished; the bytes are already in
5767 * the buffer it supplied. */
5768 0 int fd = ev->fd; /* # uncoverable statement */
5769 /*
5770 # uncoverable statement
5771 # uncoverable condition left count:1
5772 # uncoverable condition right count:1
5773 # uncoverable condition left count:2
5774 # uncoverable condition right count:2 */
5775 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
5776  
5777 /* Is this OUR read? A completion can outlive its connection - the fd
5778 * may have been closed and reused since - and the token is the only
5779 * thing that can tell the difference. Anything that does not match
5780 * belongs to a connection that is gone, and the buffer it was reading
5781 * into is parked waiting for exactly this moment. */
5782 /*
5783 # uncoverable statement
5784 # uncoverable branch true
5785 # uncoverable branch false
5786 # uncoverable condition left count:1
5787 # uncoverable condition right count:1
5788 # uncoverable condition left count:2
5789 # uncoverable condition right count:2
5790 # uncoverable condition left count:3
5791 # uncoverable condition right count:3 */
5792 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
5793 0 hm_quar_release(loop, ev->token); /* # uncoverable statement */
5794 0 return; /* # uncoverable statement */
5795 }
5796 0 c->recv_inflight = 0; /* # uncoverable statement */
5797 /*
5798 # uncoverable statement
5799 # uncoverable branch true
5800 # uncoverable branch false
5801 # uncoverable condition left count:1
5802 # uncoverable condition right count:1 */
5803 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
5804 /* The peer half-closed a tunnel: fin to the handle first, as
5805 * hm_readable's zero read does, then the close says the rest. */
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 # uncoverable condition left count:2
5813 # uncoverable condition right count:2 */
5814 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
5815 0 (void)hm_stream_deliver(aTHX_ c->fd, c->id, -1, c->rbuf, 0, 1); /* # uncoverable statement */
5816 /*
5817 # uncoverable statement
5818 # uncoverable branch true
5819 # uncoverable branch false
5820 # uncoverable condition left count:1
5821 # uncoverable condition right count:1 */
5822 0 ▶ if (loop->conns[fd] != c) return;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[fd] != c) return; 0 0 0
5823 }
5824 0 hm_close(aTHX_ loop, c); /* # uncoverable statement */
5825 0 return; /* # uncoverable statement */
5826 }
5827 0 c->rlen += (size_t)ev->res; /* # uncoverable statement */
5828 0 c->last_rx = loop->now; /* # uncoverable statement */
5829 0 c->body_rx += (UV)ev->res; /* # uncoverable statement */
5830 0 c->last_active = loop->now; /* # uncoverable statement */
5831 0 hm_lru_touch(loop, c); /* # uncoverable statement */
5832 /* A tunnel carries no requests: its bytes go to the handle. The
5833 * parser would hold them as an unfinished request line forever. */
5834 /*
5835 # uncoverable statement
5836 # uncoverable branch true
5837 # uncoverable branch false
5838 # uncoverable branch true count:2
5839 # uncoverable branch false count:2
5840 # uncoverable branch true count:3
5841 # uncoverable branch false count:3
5842 # uncoverable condition left count:1
5843 # uncoverable condition right count:1
5844 # uncoverable condition left count:2
5845 # uncoverable condition right count:2 */
5846 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
5847 /* The same rule hm_readable applies: a synchronous handler's frame
5848 * is on the stack for this connection (its ->get pumped the loop,
5849 * and this read was in flight when it was handed the pipeline), or
5850 * a tunnel was opened inside it and the request is still in rbuf.
5851 * That frame owns the buffer. The bytes wait in it, nothing is
5852 * dispatched or re-armed from under it, and whoever called that
5853 * frame re-arms when it returns (hm_deliver's hm_again_push, or the
5854 * re-arm below in the frame that called hm_process). Without this a
5855 * second hm_process re-parsed the request at rbuf[0], called the
5856 * application twice, and left the outer frame to memmove with a
5857 * consumed count larger than what remained. */
5858 /*
5859 # uncoverable statement
5860 # uncoverable branch true
5861 # uncoverable branch false
5862 # uncoverable condition left count:1
5863 # uncoverable condition right count:1
5864 # uncoverable condition left count:2
5865 # uncoverable condition right count:2
5866 # uncoverable condition left count:3
5867 # uncoverable condition right count:3 */
5868 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
5869 0 else hm_process(aTHX_ c); /* # uncoverable statement */
5870 /*
5871 # uncoverable statement
5872 # uncoverable branch true
5873 # uncoverable branch false
5874 # uncoverable condition left count:1
5875 # uncoverable condition right count:1 */
5876 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
5877 0 hm_flush(aTHX_ c); /* # uncoverable statement */
5878 /*
5879 # uncoverable statement
5880 # uncoverable branch true
5881 # uncoverable branch false
5882 # uncoverable condition left count:1
5883 # uncoverable condition right count:1 */
5884 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
5885 /* Re-armed even while PARKED or streaming, and that is not an
5886 * optimisation - it is how a disconnect is noticed at all.
5887 *
5888 * A readiness backend keeps a persistent watcher on every connection,
5889 * so a client that walks away from a parked async request wakes the
5890 * loop with EOF and the response Future gets cancelled. Completion
5891 * mode has no such watcher: with no read outstanding the close is
5892 * simply never seen, the Future is never cancelled, and the
5893 * connection sits there until the idle sweep. t/13-async-psgi.t
5894 * catches exactly this.
5895 *
5896 * Safe because the request's bytes are gone from the buffer before it
5897 * parks - hm_process consumes them, and hm_new_input COPIES the body
5898 * into an SV - so nothing points into rbuf across a park, and the
5899 * kernel only ever writes past rlen. */
5900 0 hm_rearm_read(loop, c); /* # uncoverable statement */
5901 0 return; /* # uncoverable statement */
5902 }
5903 31220 case HM_EV_READ: {
5904 31220 int fd = ev->fd;
5905 hm_conn *c;
5906 hm_listener *lst;
5907 31220 ▶ 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; } 30011 1209 31220
5908 /* Between the two, because a UDP listener fd is never in conns[]:
5909 * QUIC multiplexes every connection over the one socket, so there is
5910 * nothing fd-indexed to find. */
5911 /*
5912 # uncoverable branch true class:ignore_covered_err
5913 # uncoverable condition left count:1 class:ignore_covered_err */
5914 1209 ▶ if ((lst = hm_listener_for_udp(loop, fd))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((lst = hm_listener_for_udp(loop, fd))) { 0 1209 1209
5915 0 hm_quic_readable(aTHX_ loop, lst); /* # uncoverable statement class:ignore_covered_err */
5916 0 return; /* # uncoverable statement class:ignore_covered_err */
5917 }
5918 1209 ▶ if ((c = loop->conns[fd])) {
Branch: 1 branch
BranchTrueFalseTotal
if ((c = loop->conns[fd])) { 1188 21 1209
5919 1188 ▶ if (c->pp_wait) hm_proxy_readable(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (c->pp_wait) hm_proxy_readable(aTHX_ c); 50 1138 1188
5920 1138 ▶ 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 1022 1138
5921 1022 else hm_readable(aTHX_ c);
5922 }
5923 /*
5924 # uncoverable branch false class:ignore_covered_err
5925 # uncoverable condition right count:1 class:ignore_covered_err
5926 # uncoverable condition right count:2 class:ignore_covered_err */
5927 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
5928 21 hm_io_event(aTHX_ loop, fd, HM_EV_READ, &loop->io_r[fd]);
5929 1209 return;
5930 }
5931 16 case HM_EV_WRITE: {
5932 16 int fd = ev->fd;
5933 hm_conn *c;
5934 16 ▶ if ((c = loop->conns[fd])) {
Branch: 1 branch
BranchTrueFalseTotal
if ((c = loop->conns[fd])) { 15 1 16
5935 /* TLS post-handshake: when the write watcher is armed because
5936 * SSL_read wanted a writable socket, route through hm_readable so
5937 * the blocked read is re-driven (it flushes pending output at the
5938 * end). Otherwise this is ordinary write backpressure and the
5939 * read side is not blocked at all - going through hm_readable
5940 * then costs an SSL_read that can only return EAGAIN, once per
5941 * writable wakeup for the whole of a large response. */
5942 /*
5943 # uncoverable branch true
5944 # uncoverable condition left count:1 class:ignore_covered_err */
5945 15 ▶ if (c->tls_hs) hm_tls_handshake(aTHX_ c);
Branch: 1 branch
BranchTrueFalseTotal
if (c->tls_hs) hm_tls_handshake(aTHX_ c); 0 15 15
5946 /*
5947 # uncoverable branch true class:ignore_covered_err
5948 # uncoverable condition left count:1 class:ignore_covered_err
5949 # uncoverable condition left count:2 class:ignore_covered_err */
5950 15 ▶ 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 12 15
else if (c->ssl && c->tls_r_wants_w) hm_readable(aTHX_ c); 0 3 3
5951 15 else hm_flush(aTHX_ c);
5952 }
5953 /*
5954 # uncoverable condition left count:2 class:ignore_covered_err
5955 # uncoverable branch false class:ignore_covered_err
5956 # uncoverable condition right count:1 class:ignore_covered_err
5957 # uncoverable condition right count:2 class:ignore_covered_err */
5958 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
5959 1 hm_io_event(aTHX_ loop, fd, HM_EV_WRITE, &loop->io_w[fd]);
5960 16 return;
5961 }
5962 }
5963 }
5964  
5965 /* Run the loop until ->stop, or (when awaiting) until $until is ready.
5966 * Re-entrant: ->get/->await inside a handler pumps this same loop, so the
5967 * worker keeps serving other connections while awaiting. */
5968 /* Dispatch what the calling frames took from the backend and have not yet
5969 * reached, nearest first. Each index moves past an event BEFORE it is
5970 * dispatched, so a run nested deeper inside it skips it too. */
5971 26 static void hm_batch_drain(pTHX_ hm_loop *loop, hm_batch *b) {
5972 52 ▶ for (; b; b = b->up)
Branch: 1 branch
BranchTrueFalseTotal
for (; b; b = b->up) 26 26 52
5973 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
5974 26 }
5975  
5976 226 static void hm_loop_run(pTHX_ hm_loop *loop, SV *until) {
5977 hm_event evs[HM_MAXEV];
5978 hm_batch b;
5979 /* The fire queue is pumped by whoever enqueues, unless a pump is
5980 * already on the stack (hm_fq_active), which makes a continuation that
5981 * enqueues from inside a callback leave its work for the pump above
5982 * it. That pump is above THIS frame too when a handler reached through
5983 * the queue (a parked response delivering the next pipelined request)
5984 * calls ->get: the nested run here must pump for itself, or every
5985 * continuation it waits on - a ->then, a combinator - sits in the queue
5986 * until it returns, which is never.
5987 *
5988 * This frame's state goes on the save stack, so a croak out of here (a
5989 * die from a signal handler under a ->get) restores it as a return
5990 * does. loop->batch most of all: left behind, it names this frame's
5991 * evs after the frame is gone.
5992 *
5993 * The temps are freed on every turn. This frame lasts as long as the
5994 * worker, so a mortal made anywhere under it outside a call's own
5995 * SAVETMPS - the glob name newGVgen makes for each psgi.input, the
5996 * Future trampoline before 0.54 - was otherwise kept until the worker
5997 * exited. SAVETMPS sets a floor, so a nested run under ->get frees only
5998 * what it made itself. */
5999 226 ENTER;
6000 226 SAVETMPS;
6001 226 SAVEINT(hm_fq_active);
6002 226 SAVEVPTR(hm_cur_loop);
6003 226 SAVEINT(loop->running);
6004 226 SAVEVPTR(loop->batch);
6005 226 hm_fq_active = 0;
6006 226 hm_cur_loop = loop;
6007 226 loop->running++;
6008 226 b.evs = evs;
6009 226 b.n = b.i = 0;
6010 226 b.up = loop->batch;
6011 226 loop->batch = &b;
6012 /* Cleared for the OUTERMOST run only. A nested run is a handler's ->get
6013 * pumping this loop, and a stop asked for while it runs - the second
6014 * TERM, the shutdown_grace hard-stop, the last connection closing while
6015 * draining - is the outer run's to act on: the nested one breaks and
6016 * leaves the flag set. Clearing it on exit, as this once did, swallowed
6017 * every stop that landed under a handler, and the hard-stop timer is
6018 * one-shot so the worker then never left. */
6019 226 ▶ if (loop->running == 1) loop->stop = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->running == 1) loop->stop = 0; 205 21 226
6020 33417 for (;;) {
6021 33643 double timeout = -1.0;
6022 int n, i;
6023 33643 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 818 32825 33643
6024 33643 loop->now = time(NULL);
6025 33643 ▶ 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 33617 33643
6026 33643 ▶ 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 33635 33643
if (loop->recycle_pending && !loop->stopping) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 8 0 8
6027 8 loop->recycle_pending = 0;
6028 8 hm_on_signal(aTHX_ loop); /* max_requests recycle: drain + exit */
6029 }
6030 33643 hm_run_deferred(aTHX_ loop);
6031 33643 hm_run_again(aTHX_ loop);
6032 33643 ▶ if (loop->starved_retry) hm_accept_unstarve(loop);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->starved_retry) hm_accept_unstarve(loop); 28888 4755 33643
6033 33643 ▶ if (loop->stop) break;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stop) break; 12 33631 33643
6034 33631 ▶ if (until && hmf_state(aTHX_ until) != HMF_PENDING) break;
Branch: 2 branches
BranchTrueFalseTotal
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 2077 31554 33631
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 4 2073 2077
6035 33627 ▶ 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; 33626 1 33627
if (av_len(loop->deferred) >= 0 || loop->again_n) timeout = 0.0; 1 33625 33626
6036 /* QUIC's deadlines do not live in the backend's timer list - see the
6037 * costing in hm_quic.h - so the wait is clamped to the nearest one
6038 * here instead. Rounding UP is correct: ngtcp2 copes with a late
6039 * expiry and not with an early one, and the backends already round
6040 * to milliseconds. One compare when there is no QUIC listener. */
6041 /*
6042 # uncoverable branch true class:ignore_covered_err
6043 # uncoverable condition left count:1 class:ignore_covered_err */
6044 33627 ▶ if (loop->qheap.n) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->qheap.n) { 0 33627 33627
6045 /* Through a function rather than reaching into the heap here:
6046 * hm_qconn is an opaque forward declaration on a build without
6047 * QUIC, and dereferencing it would compile only where the
6048 * feature is present - which is not where the mistake shows up. */
6049 0 uint64_t now_ns = hm_now_ns(); /* # uncoverable statement class:ignore_covered_err */
6050 0 uint64_t due = hm_quic_next_deadline(loop); /* # uncoverable statement class:ignore_covered_err */
6051 /*
6052 # uncoverable statement class:ignore_covered_err
6053 # uncoverable branch true class:ignore_covered_err
6054 # uncoverable branch false class:ignore_covered_err
6055 # uncoverable condition left count:1 class:ignore_covered_err
6056 # uncoverable condition right count:1 class:ignore_covered_err */
6057 0 ▶ if (due != (uint64_t)-1) {
Branch: 1 branch
BranchTrueFalseTotal
if (due != (uint64_t)-1) { 0 0 0
6058 0 double secs = due <= now_ns ? 0.0 /* # uncoverable statement class:ignore_covered_err */
6059 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
6060 /*
6061 # uncoverable statement class:ignore_covered_err
6062 # uncoverable branch true class:ignore_covered_err
6063 # uncoverable branch false class:ignore_covered_err
6064 # uncoverable condition left count:1 class:ignore_covered_err
6065 # uncoverable condition right count:1 class:ignore_covered_err
6066 # uncoverable condition left count:2 class:ignore_covered_err
6067 # uncoverable condition right count:2 class:ignore_covered_err */
6068 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
6069 }
6070 }
6071 33627 n = loop->be->wait(loop->be, evs, HM_MAXEV, timeout);
6072 /*
6073 # uncoverable branch true
6074 # uncoverable condition left count:1 class:ignore_covered_err
6075 # uncoverable condition left count:2 class:ignore_covered_err
6076 # uncoverable condition right count:2 class:ignore_covered_err */
6077 33627 ▶ if (n < 0) { if (errno == EINTR) continue; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0) { if (errno == EINTR) continue; break; } 0 33627 33627
if (n < 0) { if (errno == EINTR) continue; break; } 0 0 0
6078 33627 b.n = n;
6079 33627 b.i = 0;
6080 67337 ▶ 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++]); 33710 33627 67337
6081 33627 b.n = 0;
6082 33627 ▶ 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 33616 33627
if (loop->tw_gy && loop->running == 1) hm_tw_gy_sweep(loop); /* # uncoverable condition right count:2 class:ignore_covered_err */ 11 0 11
6083 /*
6084 # uncoverable branch true class:ignore_covered_err
6085 # uncoverable condition left count:1 class:ignore_covered_err */
6086 33627 ▶ if (loop->qheap.n) hm_quic_expire(aTHX_ loop);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->qheap.n) hm_quic_expire(aTHX_ loop); 0 33627 33627
6087 33627 ▶ 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); 186 33441 33627
if (loop->log_fd >= 0 && loop->log_len) hm_log_flush(loop); 67 119 186
6088 33627 ▶ if (loop->stop) break;
Branch: 1 branch
BranchTrueFalseTotal
if (loop->stop) break; 145 33482 33627
6089 33482 ▶ if (until && hmf_state(aTHX_ until) != HMF_PENDING) break;
Branch: 2 branches
BranchTrueFalseTotal
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 2070 31412 33482
if (until && hmf_state(aTHX_ until) != HMF_PENDING) break; 65 2005 2070
6090 }
6091 /*
6092 # uncoverable branch true class:ignore_covered_err
6093 # uncoverable condition left count:1 class:ignore_covered_err
6094 # uncoverable condition left count:2 class:ignore_covered_err
6095 # uncoverable condition right count:2 class:ignore_covered_err */
6096 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
6097 226 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 0 226 226
6098 226 LEAVE;
6099 226 }
6100  
6101 /* ---- loop lifecycle ------------------------------------------------------- */
6102  
6103 177 static hm_loop *hm_loop_new(pTHX_ const char *backend_name) {
6104 177 hm_loop *loop = (hm_loop *)hm_xcalloc(1, sizeof(hm_loop));
6105 /*
6106 # uncoverable branch true
6107 # uncoverable condition left count:1 class:ignore_covered_err */
6108 177 ▶ if (!loop) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) return NULL; 0 177 177
6109 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
6110 153 backend_name = getenv("HYPERMAN_BACKEND");
6111 177 loop->be = hm_backend_create(backend_name);
6112 177 ▶ if (!loop->be) { free(loop); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->be) { free(loop); return NULL; } 4 173 177
6113 173 loop->pid = hm_os_getpid();
6114 173 loop->conns = (hm_conn **)hm_xcalloc(HM_MAXFD, sizeof(hm_conn *));
6115 173 loop->io_r = (hm_iow *)hm_xcalloc(HM_MAXFD, sizeof(hm_iow));
6116 173 loop->io_w = (hm_iow *)hm_xcalloc(HM_MAXFD, sizeof(hm_iow));
6117 173 loop->deferred = newAV();
6118 173 loop->log_fd = -1;
6119 173 loop->now = time(NULL);
6120 173 loop->idle_timeout = 60.0;
6121 173 loop->header_timeout = 30.0;
6122 173 loop->body_timeout = 60.0;
6123 173 loop->max_pipeline = 32;
6124 173 loop->max_read = 16 * 1024 * 1024; /* request ceiling */
6125 173 loop->compress = 0; /* off by default */
6126 173 loop->compress_min = HZ_MIN_LENGTH;
6127 173 loop->compress_level = HZ_LEVEL;
6128 173 loop->shutdown_grace = 30.0;
6129 /* Completion-mode reads, on wherever the backend can do them.
6130 *
6131 * That is io_uring alone, and io_uring IS auto-selected wherever
6132 * liburing was found at build time (the chooser goes kqueue, io_uring,
6133 * epoll, poll), so on such a Linux box this is the default read path -
6134 * which is why every change to how bytes ARRIVE lands on both the
6135 * readiness and the completion path (t/49 sweeps both).
6136 *
6137 * HYPERMAN_COMPLETION overrides, exactly as HYPERMAN_BACKEND overrides
6138 * the chooser; run(completion => ...) overrides both, being the most
6139 * specific thing the caller said. */
6140 173 loop->completion = loop->be->submit_recv ? 1 : 0;
6141 {
6142 173 const char *v = getenv("HYPERMAN_COMPLETION");
6143 /*
6144 # uncoverable branch true class:ignore_covered_err
6145 # uncoverable condition left count:1 class:ignore_covered_err
6146 # uncoverable condition left count:2 class:ignore_covered_err
6147 # uncoverable condition right count:2 class:ignore_covered_err */
6148 173 ▶ if (v && *v)
Branch: 2 branches
BranchTrueFalseTotal
if (v && *v) 0 173 173
if (v && *v) 0 0 0
6149 0 loop->completion = /* # uncoverable statement */
6150 /*
6151 # uncoverable statement
6152 # uncoverable condition left count:1
6153 # uncoverable condition right count:1
6154 # uncoverable condition left count:2
6155 # uncoverable condition right count:2 */
6156 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
6157 }
6158 173 return loop;
6159 }
6160  
6161 /* Free a loop.
6162 *
6163 * A loop belongs to the process that created it, and every DESCRIPTOR in it -
6164 * the backend's own (kqueue/epoll), the connection sockets, the log file -
6165 * belongs to that process too. A loop inherited across a fork is therefore
6166 * freed WITHOUT closing anything: the memory is ours to release, the fds are
6167 * not.
6168 *
6169 * Closing them is destructive, not merely untidy. kqueue descriptors do not
6170 * survive fork(2): the kernel invalidates the child's copy, so the number is
6171 * free and the child's very next kqueue() is handed it back - closing the
6172 * inherited loop then shuts the CHILD'S OWN queue and nothing it watches
6173 * fires again. The epoll and connection fds are the parent's, still live, and
6174 * closing our duplicates frees numbers the child immediately reuses. */
6175 /* A loop inherited across a fork must never reach its backend. On Linux an
6176 * epoll INSTANCE is a shared kernel object: fork duplicates the fd but both
6177 * processes' epoll_ctl calls edit the SAME interest list, so a child
6178 * "cleaning up" inherited watchers silently deregisters the PARENT's fds -
6179 * the parent then waits on an empty set forever (the DBIx::Loop
6180 * disown-in-a-forked-child hang, Punk t/39). kqueue merely hands the child
6181 * a dead descriptor, which is why macOS never showed it. The copied
6182 * user-space tables are ours to update; the kernel object is not. */
6183 #define HM_LOOP_INHERITED(loop) ((loop)->pid != hm_os_getpid())
6184  
6185 171 static void hm_loop_free(pTHX_ hm_loop *loop) {
6186 int i;
6187 int owned;
6188 /*
6189 # uncoverable branch true
6190 # uncoverable condition left count:1 class:ignore_covered_err */
6191 171 ▶ if (!loop) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) return; 0 171 171
6192 171 owned = (loop->pid == hm_os_getpid());
6193 /* Read buffers still parked for completions that will now never be
6194 * reaped. The ring is torn down with the backend below, so nothing can
6195 * be writing into them by the time this returns. */
6196 171 hm_quar_free_all(loop);
6197 171 hm_tw_gy_sweep(loop);
6198 11206827 ▶ for (i = 0; i < HM_MAXFD; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < HM_MAXFD; i++) { 11206656 171 11206827
6199 11206656 ▶ if (loop->conns[i]) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->conns[i]) { 1 11206655 11206656
6200 1 hm_conn *c = loop->conns[i];
6201 /*
6202 # uncoverable branch false class:ignore_covered_err
6203 # uncoverable condition right count:1 class:ignore_covered_err */
6204 1 ▶ if (owned) hm_os_close(c->fd);
Branch: 1 branch
BranchTrueFalseTotal
if (owned) hm_os_close(c->fd); 1 0 1
6205 /*
6206 # uncoverable branch true class:ignore_covered_err
6207 # uncoverable condition left count:1 class:ignore_covered_err */
6208 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
6209 /*
6210 # uncoverable branch false class:ignore_covered_err
6211 # uncoverable condition right count:1 class:ignore_covered_err */
6212 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
6213 /*
6214 # uncoverable branch false class:ignore_covered_err
6215 # uncoverable condition right count:1 class:ignore_covered_err */
6216 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
6217 /*
6218 # uncoverable branch true class:ignore_covered_err
6219 # uncoverable condition left count:1 class:ignore_covered_err */
6220 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
6221 /*
6222 # uncoverable branch false class:ignore_covered_err
6223 # uncoverable condition right count:1 class:ignore_covered_err */
6224 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
6225 /*
6226 # uncoverable branch false class:ignore_covered_err
6227 # uncoverable condition right count:1 class:ignore_covered_err */
6228 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
6229 /*
6230 # uncoverable branch false class:ignore_covered_err
6231 # uncoverable condition right count:1 class:ignore_covered_err */
6232 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
6233 /*
6234 # uncoverable branch false class:ignore_covered_err
6235 # uncoverable condition right count:1 class:ignore_covered_err */
6236 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
6237 /*
6238 # uncoverable branch false class:ignore_covered_err
6239 # uncoverable condition right count:1 class:ignore_covered_err */
6240 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
6241 /*
6242 # uncoverable branch false class:ignore_covered_err
6243 # uncoverable condition right count:1 class:ignore_covered_err
6244 # uncoverable branch true class:ignore_covered_err
6245 # uncoverable condition left count:1 class:ignore_covered_err */
6246 1 ▶ if (c->wbuf) free(c->wbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->wbuf) free(c->wbuf); 1 0 1
6247 /*
6248 # uncoverable branch false class:ignore_covered_err
6249 # uncoverable condition right count:1 class:ignore_covered_err */
6250 1 ▶ if (c->rbuf) free(c->rbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->rbuf) free(c->rbuf); 1 0 1
6251 1 free(c);
6252 1 loop->conns[i] = NULL;
6253 }
6254 /*
6255 # uncoverable branch true class:ignore_covered_err
6256 # uncoverable condition left count:1 class:ignore_covered_err */
6257 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
6258 /*
6259 # uncoverable statement class:ignore_covered_err
6260 # uncoverable branch true
6261 # uncoverable condition left count:1 */
6262 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
6263 }
6264 311 ▶ while (loop->pool) {
Branch: 1 branch
BranchTrueFalseTotal
while (loop->pool) { 140 171 311
6265 140 hm_conn *c = loop->pool;
6266 140 loop->pool = c->pool_next;
6267 140 ▶ if (c->wbuf) free(c->wbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->wbuf) free(c->wbuf); 119 21 140
6268 140 ▶ if (c->rbuf) free(c->rbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (c->rbuf) free(c->rbuf); 139 1 140
6269 140 free(c);
6270 }
6271 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
6272 171 ▶ if (loop->log_buf) free(loop->log_buf);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->log_buf) free(loop->log_buf); 8 163 171
6273 316 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 145 171 316
6274 /* Before the fds: freeing a connection writes a CONNECTION_CLOSE. */
6275 /*
6276 # uncoverable branch false class:ignore_covered_err
6277 # uncoverable condition right count:1 class:ignore_covered_err */
6278 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
6279 /*
6280 # uncoverable branch false class:ignore_covered_err
6281 # uncoverable condition right count:1 class:ignore_covered_err */
6282 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
6283 /*
6284 # uncoverable branch true class:ignore_covered_err
6285 # uncoverable condition left count:1 class:ignore_covered_err */
6286 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
6287 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
6288 /* `owned` for the same reason every other descriptor here is: a loop
6289 * belonging to another process holds fd NUMBERS that are ours, and
6290 * closing them would close whatever this process has since put
6291 * there. An inherited UDP listener is the third case of that, after
6292 * the backend descriptor and the connections. */
6293 /*
6294 # uncoverable branch true class:ignore_covered_err
6295 # uncoverable condition left count:1 class:ignore_covered_err
6296 # uncoverable condition left count:2 class:ignore_covered_err
6297 # uncoverable condition right count:2 class:ignore_covered_err */
6298 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
6299 0 hm_os_close(loop->listeners[i].udp_fd); /* # uncoverable statement class:ignore_covered_err */
6300 }
6301 171 ▶ if (loop->listeners) free(loop->listeners);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners) free(loop->listeners); 134 37 171
6302 /* A weak copy of the wrapper (hm_loop_to_sv): dropping it frees the RV
6303 * alone and runs no DESTROY. */
6304 171 ▶ if (loop->self_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->self_sv) { 124 47 171
6305 124 SV *self = loop->self_sv;
6306 124 loop->self_sv = NULL;
6307 124 loop->perl_owned = 0;
6308 124 SvREFCNT_dec(self);
6309 }
6310 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
6311 171 ▶ if (loop->app) SvREFCNT_dec(loop->app);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->app) SvREFCNT_dec(loop->app); 134 37 171
6312 171 SvREFCNT_dec((SV *)loop->deferred);
6313 171 ▶ if (loop->again) free(loop->again);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->again) free(loop->again); 7 164 171
6314 171 ▶ if (loop->hidx) free(loop->hidx);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->hidx) free(loop->hidx); 1 170 171
6315 171 ▶ if (loop->sweep_tw) free(loop->sweep_tw);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->sweep_tw) free(loop->sweep_tw); 134 37 171
6316 171 ▶ if (loop->hardstop_tw) free(loop->hardstop_tw);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->hardstop_tw) free(loop->hardstop_tw); 1 170 171
6317 /*
6318 # uncoverable branch true class:ignore_covered_err
6319 # uncoverable condition left count:1 class:ignore_covered_err */
6320 171 ▶ if (loop->qheap.a) free(loop->qheap.a);
Branch: 1 branch
BranchTrueFalseTotal
if (loop->qheap.a) free(loop->qheap.a); 0 171 171
6321 /* destroy() releases the backend's memory either way; `foreign` is what
6322 * stops it closing descriptors that are not ours - see the note above */
6323 171 ▶ if (!owned) loop->be->foreign = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!owned) loop->be->foreign = 1; 6 165 171
6324 171 loop->be->destroy(loop->be);
6325 171 free(loop->conns);
6326 171 free(loop->io_r);
6327 171 free(loop->io_w);
6328 171 free(loop);
6329 }
6330  
6331 /* Attach the PSGI server to a loop: listener, shutdown/stats signals via
6332 * the backend's signal watcher, and the timeout sweep timer. */
6333 134 static void hm_attach_server(pTHX_ hm_loop *loop, SV *app) {
6334 int i;
6335 134 loop->app = SvREFCNT_inc(app);
6336 134 loop->attached = 1;
6337 279 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 145 134 279
6338 145 loop->be->add_io(loop->be, loop->listeners[i].fd, HM_EV_READ, 0);
6339 /*
6340 # uncoverable branch true class:ignore_covered_err
6341 # uncoverable condition left count:1 class:ignore_covered_err */
6342 145 ▶ if (loop->listeners[i].udp_fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (loop->listeners[i].udp_fd >= 0) { 0 145 145
6343 /* After the fork, in the worker that will serve: the SSL_CTX and
6344 * the CID table belong to this process alone. */
6345 0 hm_quic_srv_attach(aTHX_ loop, &loop->listeners[i], i); /* # uncoverable statement class:ignore_covered_err */
6346 0 loop->be->add_io(loop->be, loop->listeners[i].udp_fd, HM_EV_READ, 0); /* # uncoverable statement class:ignore_covered_err */
6347 }
6348 }
6349 #ifndef _WIN32
6350 /* Ignore the default dispositions: these arrive through the backend's
6351 * signal watcher instead. Windows has no signal to ignore - the
6352 * WSAPoll backend's console handler is the only source there. */
6353 134 signal(SIGPIPE, SIG_IGN);
6354 134 signal(SIGTERM, SIG_IGN);
6355 134 signal(SIGINT, SIG_IGN);
6356 134 signal(SIGUSR1, SIG_IGN);
6357 #endif
6358 134 loop->be->add_signal(loop->be, SIGTERM);
6359 134 loop->be->add_signal(loop->be, SIGINT);
6360 134 loop->be->add_signal(loop->be, SIGUSR1);
6361 134 loop->sweep_tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
6362 134 loop->sweep_tw->kind = HM_TW_SWEEP;
6363 134 loop->sweep_tw->loop = loop;
6364 /*
6365 # uncoverable branch true class:ignore_covered_err
6366 # uncoverable condition left count:1 class:ignore_covered_err */
6367 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
6368 0 hm_errlog("Hyperman: cannot arm the timeout sweep: %s\n", strerror(errno)); /* # uncoverable statement class:ignore_covered_err */
6369 134 }
6370  
6371 /* register a timer watcher resolving a Future / running a callback */
6372 2061 static void hm_add_timer_watch(pTHX_ hm_loop *loop, double secs, SV *sv, int kind) {
6373 2061 hm_tw *tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
6374 2061 tw->kind = kind;
6375 2061 tw->sv = SvREFCNT_inc(sv);
6376 2061 tw->loop = loop;
6377 2061 tw->due = hm_tw_due(secs);
6378 /* A backend can refuse: on epoll every timer is a descriptor, so under
6379 * EMFILE there is none to be had. Silently dropping it left a ->get on
6380 * the timer's future pumping the loop for ever. */
6381 /*
6382 # uncoverable branch true class:ignore_covered_err
6383 # uncoverable condition left count:1 class:ignore_covered_err
6384 # uncoverable condition right count:1 class:ignore_covered_err
6385 # uncoverable condition left count:2 class:ignore_covered_err */
6386 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
6387 0 int e = errno; /* # uncoverable statement */
6388 0 SvREFCNT_dec(sv); /* # uncoverable statement */
6389 0 free(tw); /* # uncoverable statement */
6390 0 croak("Hyperman: cannot arm a timer: %s", strerror(e)); /* # uncoverable statement */
6391 }
6392 2061 }
6393  
6394 /* Let go of whatever a watcher slot held. A one-shot future that was still
6395 * pending is CANCELLED, not dropped: a `->get` waiting on it would otherwise
6396 * pump the loop for a readiness nothing is watching for any more. */
6397 143 static void hm_iow_release_sv(pTHX_ SV *sv, int is_cb) {
6398 143 ▶ if (!sv) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return; 136 7 143
6399 /*
6400 # uncoverable condition right count:2 class:ignore_covered_err
6401 # uncoverable condition right count:3 class:ignore_covered_err */
6402 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
6403 3 hmf_cancel(aTHX_ sv);
6404 7 SvREFCNT_dec(sv);
6405 }
6406  
6407 /* The slot is EMPTIED before the old occupant is released, and the new
6408 * occupant (where there is one) is seated before that too: releasing a
6409 * pending future fires its callbacks, and one of those may watch this same
6410 * fd again. With the release first, that inner registration landed in the
6411 * slot and was then overwritten by the outer one - a future that never
6412 * fired - or, on the remove path, was left in a slot whose kind had been
6413 * reset, so the next event settled a callback CV as if it were a future. */
6414 /*
6415 # uncoverable statement
6416 # uncoverable subroutine */
6417 0 static void hm_iow_release(pTHX_ hm_iow *slot) {
6418 0 SV *sv = slot->sv; /* # uncoverable statement */
6419 0 int is_cb = slot->is_cb; /* # uncoverable statement */
6420 /*
6421 # uncoverable statement
6422 # uncoverable branch true
6423 # uncoverable branch false
6424 # uncoverable condition left count:1
6425 # uncoverable condition right count:1 */
6426 0 ▶ if (!sv) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return; 0 0 0
6427 0 slot->sv = NULL; /* # uncoverable statement */
6428 0 hm_iow_release_sv(aTHX_ sv, is_cb); /* # uncoverable statement */
6429 }
6430  
6431 15 static void hm_add_io_watch(pTHX_ hm_loop *loop, int fd, const char *mode,
6432 SV *sv, int is_cb) {
6433 hm_iow *slot;
6434 SV *old;
6435 int old_cb;
6436 int mask;
6437 /*
6438 # uncoverable branch true class:ignore_covered_err
6439 # uncoverable condition left count:1 class:ignore_covered_err
6440 # uncoverable condition left count:2 class:ignore_covered_err */
6441 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
6442 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
6443 14 else { slot = &loop->io_r[fd]; mask = HM_EV_READ; }
6444 15 old = slot->sv;
6445 15 old_cb = slot->is_cb;
6446 15 slot->sv = SvREFCNT_inc(sv);
6447 15 slot->is_cb = (unsigned char)is_cb;
6448 15 slot->c_cb = NULL;
6449 15 slot->c_ud = NULL;
6450 /*
6451 # uncoverable branch false class:ignore_covered_err
6452 # uncoverable condition right count:1 class:ignore_covered_err */
6453 15 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 15 0 15
6454 15 loop->be->add_io(loop->be, fd, mask, is_cb ? 0 : 1);
6455 15 hm_iow_release_sv(aTHX_ old, old_cb);
6456 15 }
6457  
6458 /* ABI: persistent C watcher, replacing whatever held the slot. */
6459 121 static void hm_add_io_watch_c(pTHX_ hm_loop *loop, int fd, int mask,
6460 hm_abi_io_cb cb, void *ud) {
6461 hm_iow *slot;
6462 SV *old;
6463 int old_cb;
6464 /*
6465 # uncoverable branch true class:ignore_covered_err
6466 # uncoverable condition left count:1 class:ignore_covered_err
6467 # uncoverable condition left count:2 class:ignore_covered_err */
6468 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
6469 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
6470 121 old = slot->sv;
6471 121 old_cb = slot->is_cb;
6472 121 slot->sv = NULL;
6473 121 slot->is_cb = 0;
6474 121 slot->c_cb = cb;
6475 121 slot->c_ud = ud;
6476 /*
6477 # uncoverable branch false class:ignore_covered_err
6478 # uncoverable condition right count:1 class:ignore_covered_err */
6479 121 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 121 0 121
6480 121 loop->be->add_io(loop->be, fd,
6481 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
6482 121 hm_iow_release_sv(aTHX_ old, old_cb);
6483 121 }
6484  
6485 /* Drop one direction's watcher (any kind); idempotent. */
6486 7 static void hm_del_io_watch(pTHX_ hm_loop *loop, int fd, int mask) {
6487 hm_iow *slot;
6488 SV *old;
6489 int old_cb;
6490 /*
6491 # uncoverable branch true class:ignore_covered_err
6492 # uncoverable condition left count:1 class:ignore_covered_err
6493 # uncoverable condition left count:2 class:ignore_covered_err */
6494 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
6495 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
6496 /*
6497 # uncoverable branch true class:ignore_covered_err
6498 # uncoverable condition left count:1 class:ignore_covered_err
6499 # uncoverable condition left count:2 class:ignore_covered_err */
6500 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
6501 7 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 5 2 7
6502 5 loop->be->remove_io(loop->be, fd,
6503 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
6504 7 old = slot->sv;
6505 7 old_cb = slot->is_cb;
6506 7 slot->sv = NULL;
6507 7 slot->is_cb = 0;
6508 7 slot->c_cb = NULL;
6509 7 slot->c_ud = NULL;
6510 7 hm_iow_release_sv(aTHX_ old, old_cb);
6511 }
6512  
6513 /* ABI: one-shot C timer; the returned watcher doubles as the cancel handle
6514 * (freed on fire or on cancel, never both - single-threaded). */
6515 29311 static hm_tw *hm_add_timer_watch_c(hm_loop *loop, double secs,
6516 hm_abi_timer_cb cb, void *ud) {
6517 29311 hm_tw *tw = (hm_tw *)hm_xcalloc(1, sizeof(hm_tw));
6518 29311 tw->kind = HM_TW_C;
6519 29311 tw->loop = loop;
6520 29311 tw->c_cb = cb;
6521 29311 tw->c_ud = ud;
6522 29311 tw->due = hm_tw_due(secs);
6523 29311 ▶ 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 */ 28888 423 29311
6524 /* NULL, and a line in the log: the C callers (the scoreboard tick,
6525 * the bus poll, the accept re-arm) each have a fallback or a reason
6526 * to be loud, and an ABI consumer is told the handle is NULL. */
6527 28888 hm_errlog("Hyperman: cannot arm a %.3fs timer: %s\n", secs, strerror(errno)); /* # uncoverable statement class:ignore_covered_err */
6528 28888 free(tw); /* # uncoverable statement class:ignore_covered_err */
6529 28888 return NULL; /* # uncoverable statement class:ignore_covered_err */
6530 }
6531 423 return tw;
6532 }
6533  
6534 11 static void hm_del_timer_watch(pTHX_ hm_loop *loop, hm_tw *tw) {
6535 /*
6536 # uncoverable branch true class:ignore_covered_err
6537 # uncoverable condition left count:1 class:ignore_covered_err
6538 # uncoverable condition left count:2 class:ignore_covered_err */
6539 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
6540 /*
6541 # uncoverable branch false class:ignore_covered_err
6542 # uncoverable condition right count:1 class:ignore_covered_err */
6543 11 ▶ if (!HM_LOOP_INHERITED(loop))
Branch: 1 branch
BranchTrueFalseTotal
if (!HM_LOOP_INHERITED(loop)) 11 0 11
6544 11 loop->be->del_timer(loop->be, tw);
6545 /*
6546 # uncoverable branch true class:ignore_covered_err
6547 # uncoverable condition left count:1 class:ignore_covered_err */
6548 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
6549 /* Not freed here: an event naming it may already be in the batch being
6550 * dispatched (see hm_tw.dead). hm_dispatch skips it; hm_tw_gy_sweep
6551 * frees it once the outermost loop's batch is done. */
6552 11 tw->dead = 1;
6553 11 tw->gy_next = loop->tw_gy;
6554 11 loop->tw_gy = tw;
6555 }
6556  
6557 /* Free the cancelled timers. Only between batches of the OUTERMOST loop
6558 * run: a nested run (a handler's ->get) sits inside one of the outer
6559 * batch's events, and the outer batch may still name any of them. */
6560 182 static void hm_tw_gy_sweep(hm_loop *loop) {
6561 182 hm_tw *tw = loop->tw_gy, *n;
6562 182 loop->tw_gy = NULL;
6563 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
6564 182 }
6565  
6566 9 static hm_loop *hm_need_loop(void) {
6567 9 ▶ if (!hm_cur_loop)
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_cur_loop) 1 8 9
6568 1 croak("Hyperman: no event loop is running in this process");
6569 8 return hm_cur_loop;
6570 }
6571  
6572 /* ---- listener + process model -------------------------------------------- */
6573  
6574 /* Create, bind, and listen a non-blocking TCP socket. Returns fd or -1. */
6575 /* Resolve a listen address ONCE, at startup: an IPv4 or IPv6 literal (with
6576 * or without brackets), a hostname, or nothing for every IPv4 interface.
6577 * getaddrinfo's first answer is taken. Failure is an error string for the
6578 * croak and never a silent fallback: a host that did not parse used to bind
6579 * INADDR_ANY, which exposed the service on every interface for a typo. */
6580 108 static int hm_resolve(const char *host, int port, int socktype,
6581 struct sockaddr_storage *out, socklen_t *outlen,
6582 char *err, size_t errlen) {
6583 108 struct addrinfo hints, *res = NULL;
6584 char hbuf[256], pbuf[16];
6585 108 const char *h = host;
6586 int rc;
6587 /*
6588 # uncoverable branch true class:ignore_covered_err
6589 # uncoverable condition left count:1 class:ignore_covered_err
6590 # uncoverable condition left count:2 class:ignore_covered_err */
6591 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
6592 108 ▶ if (h[0] == '[') {
Branch: 1 branch
BranchTrueFalseTotal
if (h[0] == '[') { 2 106 108
6593 2 size_t l = strlen(h);
6594 /*
6595 # uncoverable condition left count:1 class:ignore_covered_err
6596 # uncoverable condition left count:3 class:ignore_covered_err */
6597 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
6598 1 snprintf(err, errlen, "malformed bracketed address");
6599 1 return -1;
6600 }
6601 1 memcpy(hbuf, h + 1, l - 2);
6602 1 hbuf[l - 2] = '\0';
6603 1 h = hbuf;
6604 }
6605 107 memset(&hints, 0, sizeof(hints));
6606 107 hints.ai_family = AF_UNSPEC;
6607 107 hints.ai_socktype = socktype;
6608 107 hints.ai_flags = AI_NUMERICSERV | AI_PASSIVE;
6609 107 snprintf(pbuf, sizeof(pbuf), "%d", port);
6610 107 rc = getaddrinfo(h, pbuf, &hints, &res);
6611 /*
6612 # uncoverable branch true class:ignore_covered_err
6613 # uncoverable condition left count:1 class:ignore_covered_err
6614 # uncoverable condition left count:2 class:ignore_covered_err */
6615 107 ▶ if (rc != 0 || !res) {
Branch: 2 branches
BranchTrueFalseTotal
if (rc != 0 || !res) { 107 0 107
if (rc != 0 || !res) { 0 107 107
6616 /*
6617 # uncoverable statement class:ignore_covered_err
6618 # uncoverable condition left count:1 class:ignore_covered_err
6619 # uncoverable condition right count:1 class:ignore_covered_err */
6620 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
6621 /*
6622 # uncoverable statement class:ignore_covered_err
6623 # uncoverable branch true class:ignore_covered_err
6624 # uncoverable branch false class:ignore_covered_err
6625 # uncoverable condition left count:1 class:ignore_covered_err
6626 # uncoverable condition right count:1 class:ignore_covered_err */
6627 0 ▶ if (res) freeaddrinfo(res);
Branch: 1 branch
BranchTrueFalseTotal
if (res) freeaddrinfo(res); 0 0 0
6628 0 return -1; /* # uncoverable statement class:ignore_covered_err */
6629 }
6630 /*
6631 # uncoverable branch true
6632 # uncoverable condition left count:1 class:ignore_covered_err */
6633 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
6634 107 memcpy(out, res->ai_addr, res->ai_addrlen);
6635 107 *outlen = (socklen_t)res->ai_addrlen;
6636 107 freeaddrinfo(res);
6637 107 return 0;
6638 }
6639  
6640 /* A unix-domain address. sun_path is 104 bytes on macOS and 108 on Linux,
6641 * and a path that does not fit is refused rather than truncated. */
6642 7 static int hm_resolve_unix(const char *path, struct sockaddr_storage *out,
6643 socklen_t *outlen, char *err, size_t errlen) {
6644 #ifdef _WIN32
6645 (void)path; (void)out; (void)outlen;
6646 snprintf(err, errlen, "unix-domain listeners are not supported on Windows");
6647 return -1;
6648 #else
6649 7 struct sockaddr_un *un = (struct sockaddr_un *)out;
6650 7 size_t l = strlen(path);
6651 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
6652 1 snprintf(err, errlen, "path is empty or longer than %d bytes",
6653 (int)sizeof(un->sun_path) - 1);
6654 1 return -1;
6655 }
6656 6 memset(out, 0, sizeof(*out));
6657 6 un->sun_family = AF_UNIX;
6658 6 memcpy(un->sun_path, path, l + 1);
6659 6 *outlen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + l + 1);
6660 6 return 0;
6661 #endif
6662 }
6663  
6664 /* An IPv6 listener is v6 ONLY, so `::` and `0.0.0.0` can both be listed on
6665 * one port; without it the second bind fails on Linux and the v4-mapped
6666 * addresses the dual-stack socket would report differ by platform. */
6667 87 static void hm_v6only(int fd, const struct sockaddr *sa) {
6668 #ifdef IPV6_V6ONLY
6669 /*
6670 # uncoverable branch true class:ignore_covered_err
6671 # uncoverable condition left count:1 class:ignore_covered_err */
6672 87 ▶ if (sa->sa_family == AF_INET6) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa->sa_family == AF_INET6) { 0 87 87
6673 0 int one = 1; /* # uncoverable statement class:ignore_covered_err */
6674 0 hm_os_setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)); /* # uncoverable statement class:ignore_covered_err */
6675 }
6676 #else
6677 (void)fd; (void)sa;
6678 #endif
6679 87 }
6680  
6681 88 static int hm_make_listener(const struct sockaddr *sa, socklen_t salen, int reuseport) {
6682 88 int one = 1;
6683 int fd;
6684 #ifndef _WIN32
6685 /* A path listener: a socket file left by an earlier run is replaced; a
6686 * regular file at the path is somebody else's and is refused. */
6687 88 ▶ if (sa->sa_family == AF_UNIX) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa->sa_family == AF_UNIX) { 3 85 88
6688 3 const char *p = ((const struct sockaddr_un *)sa)->sun_path;
6689 struct stat st;
6690 3 ▶ if (stat(p, &st) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (stat(p, &st) == 0) { 2 1 3
6691 int pfd;
6692 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
6693 /* Somebody answering at the path is a live server, and this
6694 * would have unlinked its socket from under it (a second
6695 * instance started by mistake took the path silently). Refused
6696 * as a TCP bind of a busy port is. */
6697 1 pfd = hm_os_socket(AF_UNIX, SOCK_STREAM, 0);
6698 /*
6699 # uncoverable branch false class:ignore_covered_err
6700 # uncoverable condition right count:1 class:ignore_covered_err */
6701 1 ▶ if (pfd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pfd >= 0) { 1 0 1
6702 1 int alive = connect(pfd, sa, salen) == 0;
6703 1 hm_os_close(pfd);
6704 /*
6705 # uncoverable branch true
6706 # uncoverable condition left count:1 class:ignore_covered_err */
6707 1 ▶ if (alive) { errno = EADDRINUSE; return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (alive) { errno = EADDRINUSE; return -1; } 0 1 1
6708 }
6709 1 (void)unlink(p);
6710 }
6711 }
6712 #endif
6713 87 fd = hm_os_socket(sa->sa_family, SOCK_STREAM, 0);
6714 /*
6715 # uncoverable branch true
6716 # uncoverable condition left count:1 class:ignore_covered_err */
6717 87 ▶ if (fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return -1; 0 87 87
6718 #ifndef _WIN32
6719 /* Not into anything the application execs. A re-exec successor is the
6720 * one program meant to inherit it, and hm_reexec clears this for that
6721 * child alone. */
6722 87 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
6723 #endif
6724 87 hm_v6only(fd, sa);
6725 #ifdef _WIN32
6726 /* SO_REUSEADDR on Windows lets a second bind STEAL a live listener,
6727 * which is the opposite of the Unix meaning we want here (rebind a
6728 * TIME_WAIT port). SO_EXCLUSIVEADDRUSE is the flag that buys what
6729 * SO_REUSEADDR buys everywhere else. */
6730 hm_os_setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &one, sizeof(one));
6731 #else
6732 87 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
6733 #endif
6734 #ifdef SO_REUSEPORT
6735 87 ▶ if (reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (reuseport) 3 84 87
6736 3 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
6737 #else
6738 (void)reuseport;
6739 #endif
6740 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
6741 1 hm_os_close(fd); return -1; /* # uncoverable statement class:ignore_covered_err */
6742 }
6743 /*
6744 # uncoverable branch true
6745 # uncoverable condition left count:1 class:ignore_covered_err */
6746 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
6747 86 hm_set_nonblock(fd);
6748 86 return fd;
6749 }
6750  
6751 /* The QUIC listener: the same address as its TCP twin, over UDP. No
6752 * listen(2) - there is no accept queue, because there is no accept: one
6753 * socket carries every connection and the Destination Connection ID in each
6754 * packet says which (hm_quic.h). SO_REUSEPORT is honoured the same way, and
6755 * carries the same caveat the TCP side does not have: the kernel's UDP
6756 * reuseport hash is over the 4-tuple, so a client that migrates lands on a
6757 * different worker than the one holding its connection. That is why
6758 * migration is deferred rather than half-supported. */
6759 /*
6760 # uncoverable statement class:ignore_covered_err
6761 # uncoverable subroutine class:ignore_covered_err */
6762 0 static int hm_make_udp_listener(const struct sockaddr *sa, socklen_t salen, int reuseport) {
6763 0 int one = 1; /* # uncoverable statement class:ignore_covered_err */
6764 0 int fd = hm_os_socket(sa->sa_family, SOCK_DGRAM, 0); /* # uncoverable statement class:ignore_covered_err */
6765 /*
6766 # uncoverable branch true class:ignore_covered_err
6767 # uncoverable statement class:ignore_covered_err
6768 # uncoverable branch false class:ignore_covered_err
6769 # uncoverable condition left count:1 class:ignore_covered_err
6770 # uncoverable condition right count:1 class:ignore_covered_err */
6771 0 ▶ if (fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return -1; 0 0 0
6772 #ifndef _WIN32
6773 0 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); /* # uncoverable statement class:ignore_covered_err */
6774 #endif
6775 0 hm_v6only(fd, sa); /* # uncoverable statement class:ignore_covered_err */
6776 #ifdef _WIN32
6777 hm_os_setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &one, sizeof(one));
6778 #else
6779 0 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); /* # uncoverable statement class:ignore_covered_err */
6780 #endif
6781 #ifdef SO_REUSEPORT
6782 /*
6783 # uncoverable statement class:ignore_covered_err
6784 # uncoverable branch true class:ignore_covered_err
6785 # uncoverable branch false class:ignore_covered_err
6786 # uncoverable condition left count:1 class:ignore_covered_err
6787 # uncoverable condition right count:1 class:ignore_covered_err */
6788 0 ▶ if (reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (reuseport) 0 0 0
6789 0 hm_os_setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)); /* # uncoverable statement */
6790 #else
6791 (void)reuseport;
6792 #endif
6793 /*
6794 # uncoverable branch true class:ignore_covered_err
6795 # uncoverable statement class:ignore_covered_err
6796 # uncoverable branch false class:ignore_covered_err
6797 # uncoverable condition left count:1 class:ignore_covered_err
6798 # uncoverable condition right count:1 class:ignore_covered_err */
6799 0 ▶ if (hm_os_bind(fd, sa, salen) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_os_bind(fd, sa, salen) < 0) { 0 0 0
6800 0 hm_os_close(fd); return -1; /* # uncoverable statement */
6801 }
6802 0 hm_set_nonblock(fd); /* # uncoverable statement class:ignore_covered_err */
6803 0 return fd; /* # uncoverable statement class:ignore_covered_err */
6804 }
6805  
6806 /* ---- the supervisor half: POSIX only --------------------------------------
6807 * Everything from here to the end of hm_run_server's pool branch needs
6808 * fork(2), waitpid(2) and POSIX signal delivery. Windows has none of the
6809 * three, and perl's fork emulation is ithreads - N interpreters inside ONE
6810 * process, sharing the file-scope state this server keeps per process - so
6811 * a pool there would corrupt, not scale. Windows runs the single-worker
6812 * in-process path instead (hm_run_server, above the pool branch), and an
6813 * explicit workers > 1 is refused at boot. */
6814 #ifndef _WIN32
6815  
6816 /* Supervisor signal flags: TERM/INT = shut the pool down, HUP/USR2 =
6817 * recycle workers with zero downtime, USR1 = stats dump. */
6818 static volatile sig_atomic_t hm_sup_term = 0;
6819 static volatile sig_atomic_t hm_sup_hup = 0;
6820 static volatile sig_atomic_t hm_sup_usr1 = 0;
6821 static volatile sig_atomic_t hm_sup_tick = 0; /* ALRM: the liveness look */
6822 static volatile sig_atomic_t hm_sup_usr2 = 0; /* re-exec a successor */
6823 /* The successor supervisor a USR2 started, until it has taken over (it
6824 * TERMs us) or died trying (the reaper clears it). */
6825 static pid_t hm_resup_pid = 0;
6826 /* What this process was started as, for the exec: $^X and perl's argv from
6827 * the first argument on. Copied at BOOT, because `$0 = ...` on Linux writes
6828 * over the memory PL_origargv points into. */
6829 static char **hm_boot_argv = NULL;
6830 /* Set in a successor: the supervisor that handed its sockets over and is
6831 * told to drain once this pool is up. */
6832 static pid_t hm_resup_old = 0;
6833 /* An alarm the caller had pending when run() was called: the deadline it asked
6834 * for, and whether it has come due. The supervisor's tick owns SIGALRM, so the
6835 * caller's is carried rather than cancelled. */
6836 static time_t hm_sup_alarm_at = 0;
6837 static int hm_sup_alarmed = 0;
6838 86 static void hm_sup_sig(int sig) {
6839 86 ▶ if (sig == SIGHUP) hm_sup_hup = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (sig == SIGHUP) hm_sup_hup = 1; 2 84 86
6840 84 ▶ else if (sig == SIGUSR2) hm_sup_usr2 = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGUSR2) hm_sup_usr2 = 1; 5 79 84
6841 79 ▶ else if (sig == SIGUSR1) hm_sup_usr1 = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGUSR1) hm_sup_usr1 = 1; 5 74 79
6842 74 ▶ else if (sig == SIGALRM) hm_sup_tick = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGALRM) hm_sup_tick = 1; 3 71 74
6843 71 ▶ else if (sig == SIGCHLD) ; /* no-op: just wakes sigsuspend() */
Branch: 1 branch
BranchTrueFalseTotal
else if (sig == SIGCHLD) ; /* no-op: just wakes sigsuspend() */ 27 44 71
6844 27 else hm_sup_term = 1;
6845 86 }
6846  
6847 /* Wedged is not dead. A worker that is alive but has stopped turning its
6848 * loop keeps its pid and its row; what stops is the row's `updated` stamp,
6849 * which the one-second tick moves. Three looks three seconds apart with the
6850 * stamp unmoved and the pid answering kill(0) is the signal, logged once per
6851 * episode. The respawn policy is untouched: this says, it does not act. */
6852 #define HM_SUP_TICK_SECS 3
6853 #define HM_SUP_WEDGED_TICKS 3
6854 static uint64_t hm_child_seen[1024];
6855 static int hm_child_stale[1024];
6856  
6857 2 static void hm_sup_watch_board(void) {
6858 int i;
6859 /*
6860 # uncoverable branch true
6861 # uncoverable condition left count:1 class:ignore_covered_err */
6862 2 ▶ if (!hm_sa_board_live()) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_sa_board_live()) return; 0 2 2
6863 6 ▶ for (i = 0; i < hm_nchildren; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) { 4 2 6
6864 sa_sb_reading rd;
6865 4 pid_t pid = hm_children[i];
6866 /*
6867 # uncoverable branch true
6868 # uncoverable condition left count:1 class:ignore_covered_err */
6869 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
6870 /*
6871 # uncoverable branch true
6872 # uncoverable condition left count:1 class:ignore_covered_err */
6873 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
6874 /*
6875 # uncoverable branch true
6876 # uncoverable condition left count:1 class:ignore_covered_err */
6877 4 ▶ if (rd.updated == hm_child_seen[i]) {
Branch: 1 branch
BranchTrueFalseTotal
if (rd.updated == hm_child_seen[i]) { 0 4 4
6878 /*
6879 # uncoverable statement
6880 # uncoverable branch true
6881 # uncoverable branch false
6882 # uncoverable condition left count:1
6883 # uncoverable condition right count:1 */
6884 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
6885 0 hm_errlog("Hyperman: worker %d is alive but has not " /* # uncoverable statement */
6886 "updated its scoreboard row for %d seconds: wedged?\n",
6887 (int)pid, HM_SUP_TICK_SECS * HM_SUP_WEDGED_TICKS); /* # uncoverable statement */
6888 }
6889 else {
6890 4 hm_child_seen[i] = rd.updated;
6891 4 hm_child_stale[i] = 0;
6892 }
6893 }
6894 }
6895  
6896 /* What to exec on USR2: perl's own argv from the first argument on. $^X
6897 * supplies the interpreter at exec time. Copied at BOOT, because `$0 = ...`
6898 * on Linux writes over the memory PL_origargv points into. */
6899 149 static void hm_boot_argv_save(pTHX) {
6900 149 int i, n = PL_origargc;
6901 /*
6902 # uncoverable branch true class:ignore_covered_err
6903 # uncoverable condition left count:1 class:ignore_covered_err
6904 # uncoverable condition left count:2 class:ignore_covered_err */
6905 149 ▶ if (n <= 0 || !PL_origargv) return;
Branch: 2 branches
BranchTrueFalseTotal
if (n <= 0 || !PL_origargv) return; 149 0 149
if (n <= 0 || !PL_origargv) return; 0 149 149
6906 149 hm_boot_argv = (char **)hm_xmalloc(sizeof(char *) * (size_t)(n + 1));
6907 650 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 501 149 650
6908 501 ▶ 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 */ 501 0 501
6909 501 hm_boot_argv[i] = (char *)hm_xmalloc(strlen(a) + 1);
6910 501 memcpy(hm_boot_argv[i], a, strlen(a) + 1);
6911 }
6912 149 hm_boot_argv[n] = NULL;
6913 /* argv[0] becomes the interpreter path at exec; keep the name perl was
6914 * invoked under as its argv[0] */
6915 }
6916  
6917 #else
6918 /* No re-exec on Windows: there is no USR2 to ask for one. */
6919 #define hm_boot_argv_save(x) ((void)0)
6920 #endif /* !_WIN32 - the rest of this section is shared; hm_spawn and the
6921 * pool branch of hm_run_server re-open the guard below */
6922  
6923 /* One listener as configured by run(): its bind address, optional TLS, h2,
6924 * and https-redirect target. The bound fd and built SSL_CTX are filled in by
6925 * hm_run_server before the workers fork. */
6926 typedef struct {
6927 const char *host;
6928 int port;
6929 const char *path; /* a unix-domain listener instead of host:port */
6930 int mode_set, mode; /* its file mode, when given */
6931 int inherit; /* adopt this one from LISTEN_FDS */
6932 int proxy_protocol; /* every connection opens with a PROXY header */
6933 const char *tls_cert, *tls_key, *tls_ca;
6934 int tls_verify;
6935 SV *tls_sni;
6936 int http2;
6937 int http3;
6938 int redirect_https;
6939 int fd; /* bound fd (parent), or -1 under reuseport */
6940 int udp_fd; /* the QUIC socket, same rules; -1 if no h3 */
6941 void *tls_ctx; /* built SSL_CTX*, or NULL for plain */
6942 struct sockaddr_storage sa; /* host:port resolved once, in the parent; */
6943 socklen_t salen; /* what every bind, incl. a reuseport
6944 * rebind in a worker, binds */
6945 } hm_listener_spec;
6946  
6947 /* Validate one listener's options at run() time (before any bind/fork). */
6948 129 static void hm_check_listener(pTHX_ const hm_listener_spec *s) {
6949 /*
6950 # uncoverable condition left count:2 class:ignore_covered_err
6951 # uncoverable condition left count:3 class:ignore_covered_err
6952 # uncoverable condition left count:4 class:ignore_covered_err
6953 # uncoverable condition left count:5 class:ignore_covered_err */
6954 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
6955 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
6956 1 croak("Hyperman->run: tls_cert and tls_key must be given together");
6957 /*
6958 # uncoverable branch true
6959 # uncoverable condition left count:1 class:ignore_covered_err */
6960 13 ▶ if (!hm_tls_available())
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_tls_available()) 0 13 13
6961 0 croak("Hyperman->run: TLS requested but OpenSSL support was not " /* # uncoverable statement */
6962 "built (install libssl-dev and reinstall Hyperman)");
6963 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
6964 1 croak("Hyperman->run: tls_verify needs tls_ca (the CA to verify "
6965 "client certificates against)");
6966 }
6967 /*
6968 # uncoverable branch true class:ignore_covered_err
6969 # uncoverable condition left count:1 class:ignore_covered_err
6970 # uncoverable condition left count:2 class:ignore_covered_err */
6971 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
6972 1 croak("Hyperman->run: http2 requested but nghttp2 support was not " /* # uncoverable statement */
6973 "built (install libnghttp2-dev and reinstall Hyperman)");
6974 126 ▶ if (s->http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) { 3 123 126
6975 /*
6976 # uncoverable branch true class:ignore_covered_err
6977 # uncoverable branch false class:ignore_covered_err
6978 # uncoverable condition right count:1 class:ignore_covered_err */
6979 3 ▶ if (!hm_h3_available())
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_h3_available()) 3 0 3
6980 3 croak("Hyperman->run: http3 requested but QUIC support was not " /* # uncoverable statement class:ignore_covered_err */
6981 "built (it needs ngtcp2, ngtcp2_crypto_ossl, nghttp3 and "
6982 "OpenSSL 3.5 or newer - reinstall Hyperman once they are "
6983 "installed)");
6984 /* There is no cleartext QUIC the way there is h2c: the transport's
6985 * handshake IS a TLS handshake, so a certificate is not optional. */
6986 /*
6987 # uncoverable statement class:ignore_covered_err
6988 # uncoverable branch true class:ignore_covered_err
6989 # uncoverable branch false class:ignore_covered_err
6990 # uncoverable condition left count:1 class:ignore_covered_err
6991 # uncoverable condition right count:1 class:ignore_covered_err
6992 # uncoverable condition left count:2 class:ignore_covered_err
6993 # uncoverable condition right count:2 class:ignore_covered_err */
6994 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
6995 0 croak("Hyperman->run: http3 needs tls_cert and tls_key (QUIC has " /* # uncoverable statement class:ignore_covered_err */
6996 "no cleartext mode)");
6997 }
6998 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
6999 1 croak("Hyperman->run: redirect_https on a TLS listener makes no sense");
7000 122 ▶ if (s->path) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) { 8 114 122
7001 /*
7002 # uncoverable branch true class:ignore_covered_err
7003 # uncoverable condition left count:1 class:ignore_covered_err */
7004 8 ▶ if (s->http3)
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) 0 8 8
7005 0 croak("Hyperman->run: http3 needs an IP listener; a path listener " /* # uncoverable statement class:ignore_covered_err */
7006 "has no UDP twin");
7007 }
7008 /*
7009 # uncoverable branch true class:ignore_covered_err
7010 # uncoverable condition left count:1 class:ignore_covered_err
7011 # uncoverable condition left count:2 class:ignore_covered_err */
7012 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
7013 0 warn("Hyperman->run: proxy_protocol applies to the TCP side of this " /* # uncoverable statement class:ignore_covered_err */
7014 "listener only; QUIC has no byte stream before its handshake and "
7015 "reports real datagram sources");
7016 122 }
7017  
7018 /* Overlay per-listener options from a `listen => [ {..} ]` hashref onto a spec
7019 * pre-seeded with the top-level defaults. Unknown keys croak. A bare true
7020 * redirect_https means "the standard 443". */
7021 22 static void hm_listener_from_hv(pTHX_ HV *h, hm_listener_spec *s) {
7022 HE *he;
7023 22 hv_iterinit(h);
7024 58 ▶ while ((he = hv_iternext(h))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(h))) { 39 19 58
7025 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
7026 39 ▶ if (strEQ(k, "port")) s->port = (int)SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(k, "port")) s->port = (int)SvIV(v); 11 28 39
7027 /*
7028 # uncoverable branch true count:3 class:ignore_covered_err
7029 # uncoverable condition right count:2 class:ignore_covered_err */
7030 35 ▶ 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 21 28
else if (strEQ(k, "host")) { if (SvOK(v)) s->host = SvPV_nolen(v); } 7 0 7
7031 /*
7032 # uncoverable branch true count:3 class:ignore_covered_err
7033 # uncoverable condition right count:2 class:ignore_covered_err */
7034 30 ▶ 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); } 9 12 21
else if (strEQ(k, "path")) { if (SvOK(v)) s->path = SvPV_nolen(v); } 9 0 9
7035 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
7036 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
7037 8 ▶ else if (strEQ(k, "mode")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "mode")) { 2 6 8
7038 /*
7039 # uncoverable branch false class:ignore_covered_err
7040 # uncoverable condition right count:1 class:ignore_covered_err */
7041 2 ▶ if (SvOK(v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(v)) { 2 0 2
7042 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
7043 else {
7044 char *end;
7045 1 const char *m = SvPV_nolen(v);
7046 1 s->mode = (int)strtol(m, &end, 8);
7047 /*
7048 # uncoverable branch false class:ignore_covered_err
7049 # uncoverable condition left count:1 class:ignore_covered_err
7050 # uncoverable condition right count:1 class:ignore_covered_err
7051 # uncoverable condition right count:2 class:ignore_covered_err */
7052 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
7053 1 croak("Hyperman->run: mode '%s' is not an octal number", m);
7054 }
7055 1 s->mode_set = 1;
7056 }
7057 }
7058 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
7059 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
7060 /*
7061 # uncoverable branch true
7062 # uncoverable condition left count:1 class:ignore_covered_err
7063 # uncoverable condition left count:2 class:ignore_covered_err
7064 # uncoverable condition right count:2 class:ignore_covered_err */
7065 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
7066 /*
7067 # uncoverable branch true
7068 # uncoverable condition left count:1 class:ignore_covered_err
7069 # uncoverable condition left count:2 class:ignore_covered_err
7070 # uncoverable condition right count:2 class:ignore_covered_err */
7071 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
7072 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
7073 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
7074 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
7075 2 ▶ else if (strEQ(k, "tls_verify")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "tls_verify")) { 1 1 2
7076 1 const char *m = SvPV_nolen(v);
7077 /*
7078 # uncoverable branch true
7079 # uncoverable condition left count:1 class:ignore_covered_err */
7080 1 ▶ if (strEQ(m, "require")) s->tls_verify = 2;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(m, "require")) s->tls_verify = 2; 0 1 1
7081 /*
7082 # uncoverable branch true
7083 # uncoverable condition left count:1 class:ignore_covered_err */
7084 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
7085 /*
7086 # uncoverable branch true
7087 # uncoverable condition left count:1 class:ignore_covered_err */
7088 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
7089 1 else croak("Hyperman->run: tls_verify must be none/optional/require");
7090 }
7091 1 else croak("Hyperman->run: unknown listen option '%s'", k);
7092 }
7093 /*
7094 # uncoverable branch true class:ignore_covered_err
7095 # uncoverable condition left count:1 class:ignore_covered_err */
7096 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
7097 /* A path listener is seeded with the top-level host and port like every
7098 * other spec; the path is the address, so those defaults are dropped
7099 * rather than read as a contradiction. */
7100 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
7101 19 }
7102  
7103 /* Everything a worker needs; one struct so spawn plumbing stays sane. */
7104 typedef struct {
7105 SV *app;
7106 hm_listener_spec *lspecs; /* one or more listeners */
7107 int nlspecs;
7108 double idle_t, header_t, body_t, request_t, grace;
7109 UV body_min_rate;
7110 int max_pipe, reuseport, affinity, nworkers;
7111 int completion; /* -1 = say nothing, 0/1 = force */
7112 int compress;
7113 size_t compress_min;
7114 int compress_level;
7115 size_t max_read; /* request ceiling; 16MB by default */
7116 SV *compress_types;
7117 UV max_requests;
7118 SV *log_cb; /* access_log coderef, or NULL */
7119 int log_fd; /* fast access-log fd, or -1 */
7120 const char *log_path; /* access_log file to open (parent), or NULL */
7121 const char *log_format; /* access_log_format, NULL = Combined */
7122 hm_logtok *logtok; /* ... compiled, before the fork */
7123 int nlogtok, log_json, log_wants_t0;
7124 int err_fd; /* error_log fd, or -1 = stderr */
7125 const char *err_path; /* error_log file to open (parent), or NULL */
7126 /* Privileges, dropped in the parent after every bind and before the
7127 * first fork (hm_drop_privileges). Names are resolved FIRST, before the
7128 * bind, so an unknown user is a croak with the port still free. */
7129 const char *drop_user; /* user => name or uid, or NULL */
7130 const char *drop_group; /* group => name or gid, or NULL */
7131 const char *pid_path; /* pid_file, or NULL */
7132 int listen_fds; /* adopt every listener from LISTEN_FDS */
7133 int umask_set; /* umask => given */
7134 unsigned umask_val;
7135 int drop_uid_set, drop_gid_set;
7136 long drop_uid, drop_gid;
7137 char drop_name[64]; /* the user's name, for initgroups */
7138 SV *deny; /* arrayref of IPs to denylist, or NULL */
7139 unsigned deny_cap, rate_cap; /* arena table sizes, 0 = default */
7140 unsigned bus_slots, bus_slot_size, bus_groups; /* 0 = default */
7141 UV http3_max_conns; /* QUIC connection ceiling, 0 = off */
7142 const char *arena_name; /* Shared::Arena name, NULL = anonymous */
7143 STRLEN arena_name_len;
7144 UV arena_size; /* bytes, 0 = computed from the tenants */
7145 int distinct_clients; /* count distinct peers at accept (HLL) */
7146 } hm_worker_cfg;
7147  
7148 /* Populate the loop's listener array from the (already bound) specs. Under
7149 * reuseport each worker rebinds, so fds are passed in; otherwise they are the
7150 * parent's inherited fds. Returns 0, or -1 if a reuseport rebind failed. */
7151 134 static int hm_worker_listeners(hm_loop *loop, const hm_worker_cfg *cfg,
7152 const int *fds) {
7153 int i;
7154 134 loop->listeners = (hm_listener *)hm_xcalloc(cfg->nlspecs, sizeof(hm_listener));
7155 134 loop->nlisteners = cfg->nlspecs;
7156 279 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 145 134 279
7157 145 const hm_listener_spec *s = &cfg->lspecs[i];
7158 145 hm_listener *l = &loop->listeners[i];
7159 145 ▶ l->fd = fds ? fds[i] : s->fd;
Branch: 1 branch
BranchTrueFalseTotal
l->fd = fds ? fds[i] : s->fd; 2 143 145
7160 /*
7161 # uncoverable branch true
7162 # uncoverable condition left count:1 class:ignore_covered_err */
7163 145 ▶ if (l->fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (l->fd < 0) return -1; 0 145 145
7164 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
7165 145 l->is_unix = s->path ? 1 : 0;
7166 145 l->proxy_protocol = s->proxy_protocol;
7167 282 ▶ l->host = strdup(s->path ? s->path
Branch: 1 branch
BranchTrueFalseTotal
l->host = strdup(s->path ? s->path 8 137 145
7168 /*
7169 # uncoverable condition right count:1 class:ignore_covered_err
7170 # uncoverable condition right count:2 class:ignore_covered_err */
7171 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
7172 145 l->port = s->port;
7173 145 l->tls_ctx = s->tls_ctx;
7174 145 l->http2 = s->http2;
7175 145 l->http3 = s->http3;
7176 145 l->redirect_https = s->redirect_https;
7177 /* Copied, not borrowed: hm_tls_reload frees the context it
7178 * replaces, and a rebuild has to name the same cert and key. */
7179 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
7180 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
7181 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
7182 145 l->tls_verify = s->tls_verify;
7183 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
7184 /* Precomputed once here rather than per response: the value never
7185 * changes for the life of the listener, and a header built per
7186 * request would be built on the hot path for every request the
7187 * listener ever serves. */
7188 /*
7189 # uncoverable branch true class:ignore_covered_err
7190 # uncoverable condition left count:1 class:ignore_covered_err */
7191 145 ▶ if (l->udp_fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (l->udp_fd >= 0) { 0 145 145
7192 char b[64];
7193 0 int n = snprintf(b, sizeof(b), "h3=\":%d\"; ma=86400", l->port); /* # uncoverable statement class:ignore_covered_err */
7194 /*
7195 # uncoverable statement class:ignore_covered_err
7196 # uncoverable condition left count:1 class:ignore_covered_err
7197 # uncoverable condition right count:1 class:ignore_covered_err
7198 # uncoverable condition left count:2 class:ignore_covered_err
7199 # uncoverable condition right count:2 class:ignore_covered_err */
7200 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
7201 }
7202 }
7203 134 return 0;
7204 }
7205  
7206 /* Rebuild this worker's TLS contexts from a fresh SNI map.
7207 *
7208 * The listener array is the WORKER'S: hm_worker_listeners above ran after
7209 * the fork and copied the parent's tls_ctx pointer into it, so swapping
7210 * that pointer changes this process and nothing else. The listening fd is
7211 * not touched, so nothing is unbound and no connection is refused;
7212 * connections already handshook keep the SSL they hold, and the next one
7213 * this worker accepts uses the new context.
7214 *
7215 * NOTHING IS INSTALLED THAT SERVES LESS THAN WHAT IS RUNNING. Two ways a
7216 * rebuild can come back worse, and both keep the old context:
7217 *
7218 * - the default certificate will not load. It is the one every
7219 * hostname falls back to, so a fleet keeps serving the stale one
7220 * rather than none.
7221 * - a per-host certificate will not load. hm_tls_ctx_build skips it
7222 * with a message and still returns a usable default, which is right
7223 * at boot but silently drops that domain to the fallback here. So
7224 * the built registry is counted against what was asked for, and a
7225 * context carrying fewer hosts is thrown away. The cost is that one
7226 * corrupt PEM defers everybody's update to the next poll, against
7227 * installing a context that quietly stopped serving a domain.
7228 *
7229 * Returns the number of listeners rebuilt. */
7230 3 static int hm_tls_reload(pTHX_ hm_loop *loop, SV *sni) {
7231 3 int i, done = 0;
7232 /*
7233 # uncoverable condition right count:1 class:ignore_covered_err
7234 # uncoverable condition right count:2 class:ignore_covered_err
7235 # uncoverable condition right count:3 class:ignore_covered_err */
7236 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
7237 /*
7238 # uncoverable branch true
7239 # uncoverable condition left count:1 class:ignore_covered_err */
7240 3 ▶ if (!loop) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) return 0; 0 3 3
7241  
7242 6 ▶ for (i = 0; i < loop->nlisteners; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < loop->nlisteners; i++) { 3 3 6
7243 3 hm_listener *l = &loop->listeners[i];
7244 void *fresh;
7245 unsigned char tkey[HM_TLS_TKEY_MAX];
7246 3 const unsigned char *tk = NULL;
7247 3 size_t tklen = 0;
7248 /* No map given: the listener's own, so a reload called for the
7249 * default certificate alone keeps every SNI host. Without this the
7250 * rebuilt context had no registry and the "fewer hosts" refusal
7251 * below did not apply to it, so every name fell to the default. */
7252 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
7253 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
7254 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
7255 /*
7256 # uncoverable condition left count:1 class:ignore_covered_err
7257 # uncoverable condition left count:2 class:ignore_covered_err
7258 # uncoverable condition left count:3 class:ignore_covered_err */
7259 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
7260  
7261 /* Carry the running context's session-ticket key into the new one.
7262 * The boot-time contexts are built before the fork, so every worker
7263 * starts out able to decrypt every other worker's tickets - but this
7264 * reload runs independently in each of them, and SSL_CTX_new mints a
7265 * fresh random key. Left alone, the first rotation would leave a
7266 * ticket issued by one worker undecryptable by its siblings, and
7267 * every resumption a client attempted would quietly become a full
7268 * handshake: the signature and key exchange that tickets exist to
7269 * avoid, on a fleet that rotates certificates continuously. */
7270 /*
7271 # uncoverable branch false class:ignore_covered_err
7272 # uncoverable condition right count:1 class:ignore_covered_err */
7273 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
7274  
7275 3 fresh = hm_tls_ctx_build(aTHX_ l->tls_cert, l->tls_key, l->tls_ca,
7276 l->tls_verify, use, l->http2, tk, tklen);
7277 /*
7278 # uncoverable branch true
7279 # uncoverable condition left count:1 class:ignore_covered_err */
7280 3 ▶ if (!fresh) continue; /* keep what we are serving */
Branch: 1 branch
BranchTrueFalseTotal
if (!fresh) continue; /* keep what we are serving */ 0 3 3
7281  
7282 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
7283 1 hm_errlog("Hyperman TLS: reload built %d of %d SNI hosts; "
7284 "keeping the running certificates\n",
7285 hm_tls_sni_count(fresh), want);
7286 1 hm_tls_ctx_free(fresh);
7287 1 continue;
7288 }
7289  
7290 /* The QUIC context serves the SAME certificate over the same origin,
7291 * so it is rebuilt with the TCP one and the two are swapped together
7292 * or not at all. Swapping only the TCP side leaves a fleet serving a
7293 * fresh certificate over TCP and a stale one over QUIC - a mismatch
7294 * no TCP-only monitor can see, on the transport a browser prefers.
7295 *
7296 * The new QUIC context is built BEFORE either is installed, so a
7297 * failure to build it keeps both of the running pair rather than
7298 * leaving a half-swapped listener. */
7299 /*
7300 # uncoverable statement class:ignore_covered_err
7301 # uncoverable branch true
7302 # uncoverable condition left count:1
7303 # uncoverable condition left count:2
7304 # uncoverable condition right count:2 */
7305 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
7306 0 void *qfresh = hm_tls_quic_ctx_build(l->tls_cert, l->tls_key, /* # uncoverable statement */
7307 0 l->tls_ca, l->tls_verify, /* # uncoverable statement */
7308 tk, tklen); /* # uncoverable statement */
7309 /*
7310 # uncoverable statement
7311 # uncoverable branch true
7312 # uncoverable branch false
7313 # uncoverable condition left count:1
7314 # uncoverable condition right count:1 */
7315 0 ▶ if (!qfresh) {
Branch: 1 branch
BranchTrueFalseTotal
if (!qfresh) { 0 0 0
7316 0 hm_errlog("Hyperman TLS: reload could not rebuild the " /* # uncoverable statement */
7317 "QUIC context; keeping both running "
7318 "certificates\n");
7319 0 hm_tls_ctx_free(fresh); /* # uncoverable statement */
7320 0 continue; /* # uncoverable statement */
7321 }
7322 0 hm_quic_ctx_swap(aTHX_ l, qfresh); /* # uncoverable statement */
7323 }
7324  
7325 2 hm_tls_ctx_free(l->tls_ctx);
7326 2 l->tls_ctx = fresh;
7327 2 done++;
7328 }
7329 3 return done;
7330 }
7331  
7332 /* The bus wakeup, on this worker's loop.
7333 *
7334 * Lives here rather than in hm_sa_bus.h because it is the one part that needs
7335 * both halves: hm_sa_bus.h deliberately knows nothing about the server, and
7336 * the loop knows nothing about the ring.
7337 *
7338 * The callback MUST NOT CROAK. It is called from the event loop with no Perl
7339 * frame around it, and a die from a subscriber would unwind through the loop
7340 * and take the worker with it - so the dispatch below is the only thing here,
7341 * and anything Perl-facing wraps itself in G_EVAL before it gets this far. */
7342 5 static void hm_bus_wake_cb(pTHX_ int fd, int mask, void *ud) {
7343 PERL_UNUSED_ARG(fd);
7344 PERL_UNUSED_ARG(mask);
7345 PERL_UNUSED_ARG(ud);
7346 PERL_UNUSED_CONTEXT;
7347 /* Empty the pipe and clear the flag BEFORE dispatching, so a publish that
7348 * lands while we are dispatching sets it again and pokes afresh, rather
7349 * than being folded into a wakeup that has already been handled. The
7350 * order inside the ring's wake_drained matters too - see hm_sa_bus.h. */
7351 5 hm_sa_bus_waker_drained();
7352 5 (void)hm_sa_bus_dispatch();
7353 5 }
7354  
7355 /* The one-second tick: the loop's counters into this worker's scoreboard
7356 * row in one seqlock bracket, a heartbeat on the peer row, and the next
7357 * tick armed. A C timer is one-shot and freed on fire, so re-arming here is
7358 * the whole of the repetition. Stops with the loop: a draining worker keeps
7359 * mirroring until its last connection closes, and nothing here holds the
7360 * loop open once it wants to end. */
7361 252 static void hm_board_tick(pTHX_ void *ud) {
7362 252 hm_loop *loop = (hm_loop *)ud;
7363 252 hm_sa_board_mirror((uint64_t)loop->requests, (uint64_t)loop->accepts,
7364 252 (uint64_t)loop->denied, loop->nconns,
7365 252 (uint64_t)loop->bytes_out, (uint64_t)loop->datagrams,
7366 252 (uint64_t)loop->h3_requests);
7367 /*
7368 # uncoverable branch false class:ignore_covered_err
7369 # uncoverable condition right count:1 class:ignore_covered_err
7370 # uncoverable condition right count:2 class:ignore_covered_err */
7371 252 ▶ 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); 252 0 252
if (HM_SA && hm_sa_region) HM_SA->beat(hm_sa_region); 252 0 252
7372 252 ▶ if (!loop->stopping)
Branch: 1 branch
BranchTrueFalseTotal
if (!loop->stopping) 250 2 252
7373 250 (void)hm_add_timer_watch_c(loop, 1.0, hm_board_tick, loop);
7374 252 }
7375  
7376 /* The polling fallback's tick: drain the ring, re-arm. */
7377 68 static void hm_bus_poll_cb(pTHX_ void *ud) {
7378 68 hm_loop *loop = (hm_loop *)ud;
7379 68 (void)hm_sa_bus_dispatch();
7380 /*
7381 # uncoverable branch false class:ignore_covered_err
7382 # uncoverable condition right count:1 class:ignore_covered_err */
7383 68 ▶ 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); 68 0 68
7384 68 }
7385  
7386 134 static void hm_bus_worker_attach(pTHX_ hm_loop *loop) {
7387 int fd;
7388 134 ▶ if (!hm_sa_bus_live()) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_sa_bus_live()) return; 8 126 134
7389 /* A worker inherited the parent's cursors along with everything else, and
7390 * a cursor is a position in a stream this process has not been reading.
7391 * Left alone it either replays what the parent already handled or skips
7392 * what it has not. From now on. */
7393 126 hm_sa_bus_reset_cursors();
7394  
7395 /* THE LAST WORD ON WHETHER THIS PROCESS CAN BE WOKEN.
7396 *
7397 * hm_spawn asks for a slot by worker index, which is what keeps two
7398 * workers off one descriptor. It can come back empty-handed: the index it
7399 * asked for may still be held by a worker that is draining after a HUP,
7400 * and single-worker mode never goes through hm_spawn at all. Either way
7401 * the process ends up with no descriptor.
7402 *
7403 * Before this, that was the end of it - no watch was installed and this
7404 * worker never dispatched again, so a published invalidation or room
7405 * broadcast reached every worker but this one, for as long as it ran, with
7406 * nothing in any statistic to say so. Single-worker mode never delivered
7407 * to its own subscribers at all.
7408 *
7409 * So take whatever is going rather than go deaf. Which slot a worker holds
7410 * has never mattered; holding one is the whole of it. */
7411 126 fd = hm_sa_bus_waker_fd();
7412 126 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 58 68 126
7413 58 (void)hm_sa_bus_waker_take(-1);
7414 58 fd = hm_sa_bus_waker_fd();
7415 }
7416 126 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 6 120 126
7417 /* No descriptor: the slots were all held, or this process attached
7418 * the arena by name (a re-exec successor's pool does) and the pipes
7419 * in it belong to another process. Poll the ring instead, every
7420 * fifty milliseconds. Slower to notice a message than a poke, never
7421 * deaf. */
7422 6 hm_errlog("Hyperman: worker %d has no wakeup descriptor; polling the "
7423 6 "bus every 50ms instead", hm_os_getpid());
7424 6 (void)hm_add_timer_watch_c(loop, 0.05, hm_bus_poll_cb, loop);
7425 6 return;
7426 }
7427 120 hm_add_io_watch_c(aTHX_ loop, fd, HM_EV_READ, hm_bus_wake_cb, NULL);
7428 /* Anything published between the fork and this attach is already on the
7429 * ring with no poke coming, because nothing was watching to be poked. */
7430 120 (void)hm_sa_bus_dispatch();
7431 }
7432  
7433 134 static void hm_worker(pTHX_ const hm_worker_cfg *cfg, const int *fds) {
7434 134 hm_loop *loop = hm_loop_new(aTHX_ NULL);
7435 /*
7436 # uncoverable branch true
7437 # uncoverable condition left count:1 class:ignore_covered_err */
7438 134 ▶ if (!loop) croak("Hyperman: cannot create event loop");
Branch: 1 branch
BranchTrueFalseTotal
if (!loop) croak("Hyperman: cannot create event loop"); 0 134 134
7439 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
7440 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
7441 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
7442 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
7443 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
7444 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
7445 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
7446 134 loop->max_requests = cfg->max_requests;
7447 /* Only when the caller actually said so: -1 leaves whatever the loop
7448 * decided for itself from the backend and the environment. */
7449 134 ▶ if (cfg->completion >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->completion >= 0) 1 133 134
7450 /*
7451 # uncoverable condition left count:1 class:ignore_covered_err
7452 # uncoverable condition left count:2 class:ignore_covered_err
7453 # uncoverable condition right count:2 class:ignore_covered_err */
7454 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
7455 134 loop->compress = cfg->compress;
7456 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
7457 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
7458 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
7459 134 loop->http3_max_conns = cfg->http3_max_conns;
7460 268 loop->compress_types = cfg->compress_types
7461 /*
7462 # uncoverable statement class:ignore_covered_err
7463 # uncoverable condition left count:1 */
7464 134 ▶ ? SvREFCNT_inc(cfg->compress_types) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? SvREFCNT_inc(cfg->compress_types) : NULL; 0 134 134
7465 134 loop->logtok = cfg->logtok; /* compiled once, in the parent */
7466 134 loop->nlogtok = cfg->nlogtok;
7467 134 loop->log_json = cfg->log_json;
7468 134 loop->log_wants_t0 = cfg->log_wants_t0;
7469 /*
7470 # uncoverable branch true class:ignore_covered_err
7471 # uncoverable condition left count:1 class:ignore_covered_err */
7472 134 ▶ if (hm_worker_listeners(loop, cfg, fds) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_worker_listeners(loop, cfg, fds) < 0) { 0 134 134
7473 0 hm_loop_free(aTHX_ loop); /* # uncoverable statement */
7474 0 hm_exit(1); /* # uncoverable statement */
7475 }
7476 134 ▶ if (cfg->log_fd >= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->log_fd >= 0) 8 126 134
7477 8 loop->log_fd = cfg->log_fd; /* fast C writer wins */
7478 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
7479 4 loop->log_cb = SvREFCNT_inc(cfg->log_cb);
7480 134 hm_attach_server(aTHX_ loop, cfg->app);
7481 /* v4 on_worker_start: the loop exists and has not started turning, and in
7482 * a prefork server this is already the child. The one moment a consumer
7483 * can attach something loop-bound and have it belong to the process that
7484 * will actually serve. Fires here rather than at either call site so the
7485 * single-worker case, which never forks, gets it too. */
7486 134 hm_worker_hook_fire(aTHX_ (void *)loop);
7487  
7488 /* The bus wakeup. The descriptors were made before the fork; this worker
7489 * takes the one that is its own and puts it on the loop, so a publish from
7490 * a sibling returns this loop from epoll with the message already on the
7491 * ring rather than leaving it to be found whenever somebody next looks.
7492 *
7493 * After hm_worker_hook_fire, so an application's own on_worker_start has
7494 * already run and anything it subscribed is registered before the first
7495 * wakeup can arrive. */
7496 134 hm_bus_worker_attach(aTHX_ loop);
7497 /* A peer slot of this worker's own in the Shared::Arena, keyed on the
7498 * pid it has now rather than the one it inherited. */
7499 134 hm_sa_worker_join();
7500 /* This worker's scoreboard row, mirrored now and then once a second.
7501 * The tick also beats the peer row, so a worker that only ever receives
7502 * on the bus never looks dead to the ring's hole escalation. */
7503 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
7504 130 hm_board_tick(aTHX_ loop);
7505  
7506 134 hm_loop_run(aTHX_ loop, NULL);
7507 134 hm_loop_free(aTHX_ loop);
7508 134 }
7509  
7510 #ifndef _WIN32
7511 /* Fork one worker. With reuseport each worker binds its own listeners; with
7512 * affinity (Linux) worker widx is pinned to core widx % ncpu. */
7513 82 static pid_t hm_spawn(pTHX_ const hm_worker_cfg *cfg, int widx) {
7514 82 pid_t pid = fork();
7515 166 ▶ if (pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) { 84 82 166
7516 int stackfds[8];
7517 84 int *fds = NULL;
7518  
7519 /* A RESPAWNED worker is forked from inside the supervisor's loop,
7520 * where the pool's signals are handled by hm_sup_sig and BLOCKED.
7521 * The child inherits both. Until the worker's own loop has taken
7522 * over its signals, a TERM landing here would run the supervisor's
7523 * handler and set a flag nobody in this process reads: the signal
7524 * is swallowed, the worker never learns the pool is shutting down,
7525 * and the supervisor waits for it for ever. Found by a test that
7526 * killed a worker and sent TERM the moment its replacement had a
7527 * scoreboard row. Default dispositions and an empty mask, so a
7528 * TERM in that window ends the child, which is what TERM means. */
7529 {
7530 sigset_t none;
7531 84 sigemptyset(&none);
7532 84 signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL);
7533 84 signal(SIGHUP, SIG_DFL); signal(SIGUSR1, SIG_DFL);
7534 84 signal(SIGUSR2, SIG_DFL); signal(SIGCHLD, SIG_DFL);
7535 84 signal(SIGALRM, SIG_DFL);
7536 84 alarm(0);
7537 84 sigprocmask(SIG_SETMASK, &none, NULL);
7538 }
7539  
7540 /* Tell perl it has been forked. $$ is a plain SV that perl only
7541 * refreshes inside pp_fork; forking from C here happens behind its
7542 * back, so without this the worker keeps reporting the supervisor's
7543 * pid - and POSIX::getpid is `sub getpid { $$ }`, so that reads wrong
7544 * too. Anything in the application that names a log line, a temp file
7545 * or a pid file after $$ then collides across the whole pool. This is
7546 * what pp_fork itself does in the child. */
7547 {
7548 84 GV *pidgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV);
7549 /*
7550 # uncoverable branch false class:ignore_covered_err
7551 # uncoverable condition right count:1 class:ignore_covered_err */
7552 84 ▶ if (pidgv) {
Branch: 1 branch
BranchTrueFalseTotal
if (pidgv) { 84 0 84
7553 84 SvREADONLY_off(GvSV(pidgv));
7554 84 sv_setiv(GvSV(pidgv), (IV)getpid());
7555 84 SvREADONLY_on(GvSV(pidgv));
7556 }
7557 }
7558  
7559 #if defined(__linux__) && defined(CPU_SET)
7560 /*
7561 # uncoverable branch true
7562 # uncoverable condition left count:1 */
7563 84 ▶ if (cfg->affinity) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->affinity) { 0 84 84
7564 0 long ncpu = sysconf(_SC_NPROCESSORS_ONLN); /* # uncoverable statement */
7565 /*
7566 # uncoverable statement
7567 # uncoverable branch true
7568 # uncoverable branch false
7569 # uncoverable condition left count:1
7570 # uncoverable condition right count:1 */
7571 0 ▶ if (ncpu > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ncpu > 0) { 0 0 0
7572 cpu_set_t set;
7573 0 CPU_ZERO(&set); /* # uncoverable statement */
7574 0 ▶ CPU_SET((int)(widx % ncpu), &set); /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
CPU_SET((int)(widx % ncpu), &set); /* # uncoverable statement */ 0 0 0
7575 0 sched_setaffinity(0, sizeof(set), &set); /* # uncoverable statement */
7576 }
7577 }
7578 #else
7579 (void)widx;
7580 #endif
7581 84 ▶ if (cfg->reuseport) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) { 2 82 84
7582 2 int i, n = cfg->nlspecs;
7583 /* Two descriptors per listener now, TCP in the first half and
7584 * QUIC in the second, so hm_worker_listeners reads fds[i] and
7585 * fds[n + i]. */
7586 4 fds = 2 * n <= (int)(sizeof(stackfds)/sizeof(stackfds[0]))
7587 ? stackfds
7588 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
7589 4 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 2 2 4
7590 4 fds[i] = hm_make_listener((struct sockaddr *)&cfg->lspecs[i].sa,
7591 2 cfg->lspecs[i].salen, 1);
7592 /*
7593 # uncoverable branch true class:ignore_covered_err
7594 # uncoverable condition left count:1 class:ignore_covered_err */
7595 2 ▶ if (fds[i] < 0) hm_exit(1);
Branch: 1 branch
BranchTrueFalseTotal
if (fds[i] < 0) hm_exit(1); 0 2 2
7596 2 fds[n + i] = -1; /* # uncoverable statement class:ignore_covered_err */
7597 /*
7598 # uncoverable statement class:ignore_covered_err
7599 # uncoverable branch true
7600 # uncoverable condition left count:1 */
7601 2 ▶ if (cfg->lspecs[i].http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->lspecs[i].http3) { 0 2 2
7602 0 fds[n + i] = hm_make_udp_listener((struct sockaddr *)&cfg->lspecs[i].sa, /* # uncoverable statement */
7603 0 cfg->lspecs[i].salen, 1); /* # uncoverable statement */
7604 /*
7605 # uncoverable statement
7606 # uncoverable branch true
7607 # uncoverable branch false
7608 # uncoverable condition left count:1
7609 # uncoverable condition right count:1 */
7610 0 ▶ if (fds[n + i] < 0) hm_exit(1);
Branch: 1 branch
BranchTrueFalseTotal
if (fds[n + i] < 0) hm_exit(1); 0 0 0
7611 }
7612 }
7613 }
7614 /* This child's own waker slot, claimed before hm_worker so the
7615 * attach below finds it. Index by worker number, so two workers never
7616 * share a descriptor. */
7617 84 (void)hm_sa_bus_waker_take(widx);
7618 84 hm_worker(aTHX_ cfg, fds);
7619 84 hm_exit(0);
7620 }
7621 82 return pid;
7622 }
7623 #endif /* !_WIN32 */
7624  
7625 /* The full server: validate + bind, then either run in-process (1 worker)
7626 * or supervise a pool (respawn with backoff, HUP/USR2 recycle, USR1 stats,
7627 * TERM/INT bounded drain). */
7628 /* ---- privileges and the pid file ----------------------------------------- */
7629  
7630 11 static int hm_all_digits(const char *s) {
7631 /*
7632 # uncoverable branch true
7633 # uncoverable condition left count:1 class:ignore_covered_err */
7634 11 ▶ if (!*s) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!*s) return 0; 0 11 11
7635 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
7636 7 return 1;
7637 }
7638  
7639 /* Turn user/group names into ids. Called before anything is bound: a typo
7640 * in `user` must not leave a server listening as root. */
7641 114 static void hm_resolve_drop(pTHX_ hm_worker_cfg *cfg) {
7642 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
7643 92 return;
7644 #ifdef _WIN32
7645 croak("Hyperman->run: user, group, umask and pid_file are not supported "
7646 "on Windows");
7647 #else
7648 22 cfg->drop_name[0] = '\0';
7649 22 ▶ if (cfg->drop_user) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_user) { 9 13 22
7650 9 ▶ if (hm_all_digits(cfg->drop_user)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_all_digits(cfg->drop_user)) { 6 3 9
7651 struct passwd *pw;
7652 6 cfg->drop_uid = atol(cfg->drop_user);
7653 6 cfg->drop_uid_set = 1;
7654 6 pw = getpwuid((uid_t)cfg->drop_uid);
7655 6 ▶ if (pw) {
Branch: 1 branch
BranchTrueFalseTotal
if (pw) { 3 3 6
7656 3 strncpy(cfg->drop_name, pw->pw_name, sizeof(cfg->drop_name) - 1);
7657 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
7658 /*
7659 # uncoverable branch false
7660 # uncoverable condition right count:1 class:ignore_covered_err */
7661 3 ▶ } else if (!cfg->drop_group) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!cfg->drop_group) { 3 0 3
7662 /* No entry to take a group from: without one the workers
7663 * would keep gid 0 and root's supplementary groups behind a
7664 * harmless-looking uid. */
7665 3 croak("Hyperman->run: user %s has no passwd entry; name a "
7666 "group => as well", cfg->drop_user);
7667 }
7668 } else {
7669 3 struct passwd *pw = getpwnam(cfg->drop_user);
7670 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
7671 1 cfg->drop_uid = (long)pw->pw_uid;
7672 1 cfg->drop_uid_set = 1;
7673 1 strncpy(cfg->drop_name, pw->pw_name, sizeof(cfg->drop_name) - 1);
7674 /*
7675 # uncoverable branch false class:ignore_covered_err
7676 # uncoverable condition right count:1 class:ignore_covered_err */
7677 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
7678 }
7679 }
7680 17 ▶ if (cfg->drop_group) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_group) { 2 15 17
7681 2 ▶ if (hm_all_digits(cfg->drop_group)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_all_digits(cfg->drop_group)) { 1 1 2
7682 1 cfg->drop_gid = atol(cfg->drop_group);
7683 } else {
7684 1 struct group *gr = getgrnam(cfg->drop_group);
7685 /*
7686 # uncoverable branch false
7687 # uncoverable condition right count:1 class:ignore_covered_err */
7688 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
7689 0 cfg->drop_gid = (long)gr->gr_gid; /* # uncoverable statement */
7690 }
7691 1 cfg->drop_gid_set = 1;
7692 }
7693 #endif
7694 }
7695  
7696 /* Group first, then the user: once the uid is gone the gid cannot follow.
7697 * Each step is checked and a failure CROAKS - a server that could not drop
7698 * must not go on serving as root as if it had. */
7699 77 static void hm_drop_privileges(pTHX_ const hm_worker_cfg *cfg) {
7700 #ifndef _WIN32
7701 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
7702 /* Not root: a re-exec successor forked by a supervisor that had already
7703 * dropped. It cannot change its ids and need not, if it already has the
7704 * ones asked for; anything else is refused, as before. */
7705 /*
7706 # uncoverable branch true class:ignore_covered_err
7707 # uncoverable condition left count:1 class:ignore_covered_err
7708 # uncoverable condition left count:2 class:ignore_covered_err
7709 # uncoverable condition right count:2 class:ignore_covered_err
7710 # uncoverable condition left count:3 class:ignore_covered_err
7711 # uncoverable condition right count:3 class:ignore_covered_err */
7712 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
7713 /*
7714 # uncoverable statement
7715 # uncoverable branch true
7716 # uncoverable branch false
7717 # uncoverable condition left count:1
7718 # uncoverable condition right count:1
7719 # uncoverable condition left count:2
7720 # uncoverable condition right count:2
7721 # uncoverable condition left count:3
7722 # uncoverable condition right count:3 */
7723 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
7724 0 ▶ || geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
|| geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */ 0 0 0
7725 0 croak("Hyperman->run: not root, and not uid %ld either: cannot " /* # uncoverable statement */
7726 "become user '%s'", cfg->drop_uid, cfg->drop_user); /* # uncoverable statement */
7727 /*
7728 # uncoverable statement
7729 # uncoverable branch true
7730 # uncoverable branch false
7731 # uncoverable condition left count:1
7732 # uncoverable condition right count:1
7733 # uncoverable condition left count:2
7734 # uncoverable condition right count:2 */
7735 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
7736 0 croak("Hyperman->run: not root, and not gid %ld either: cannot " /* # uncoverable statement */
7737 "change group", cfg->drop_gid); /* # uncoverable statement */
7738 0 return; /* # uncoverable statement */
7739 }
7740 /*
7741 # uncoverable statement class:ignore_covered_err
7742 # uncoverable branch true
7743 # uncoverable condition left count:1 */
7744 77 ▶ if (cfg->drop_gid_set) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_gid_set) { 0 77 77
7745 /*
7746 # uncoverable statement
7747 # uncoverable branch true
7748 # uncoverable branch false
7749 # uncoverable condition left count:1
7750 # uncoverable condition right count:1 */
7751 0 ▶ if (cfg->drop_name[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_name[0]) { 0 0 0
7752 /*
7753 # uncoverable statement
7754 # uncoverable branch true
7755 # uncoverable branch false
7756 # uncoverable condition left count:1
7757 # uncoverable condition right count:1 */
7758 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
7759 0 croak("Hyperman->run: initgroups(%s): %s", cfg->drop_name, strerror(errno)); /* # uncoverable statement */
7760 } else {
7761 0 gid_t g = (gid_t)cfg->drop_gid; /* # uncoverable statement */
7762 /*
7763 # uncoverable statement
7764 # uncoverable branch true
7765 # uncoverable branch false
7766 # uncoverable condition left count:1
7767 # uncoverable condition right count:1 */
7768 0 ▶ if (setgroups(1, &g) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (setgroups(1, &g) < 0) 0 0 0
7769 0 croak("Hyperman->run: setgroups: %s", strerror(errno)); /* # uncoverable statement */
7770 }
7771 /*
7772 # uncoverable statement
7773 # uncoverable branch true
7774 # uncoverable branch false
7775 # uncoverable condition left count:1
7776 # uncoverable condition right count:1 */
7777 0 ▶ if (setgid((gid_t)cfg->drop_gid) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (setgid((gid_t)cfg->drop_gid) < 0) 0 0 0
7778 0 croak("Hyperman->run: setgid(%ld): %s", cfg->drop_gid, strerror(errno)); /* # uncoverable statement */
7779 }
7780 /*
7781 # uncoverable statement class:ignore_covered_err
7782 # uncoverable branch true
7783 # uncoverable condition left count:1 */
7784 77 ▶ if (cfg->drop_uid_set) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->drop_uid_set) { 0 77 77
7785 /*
7786 # uncoverable statement
7787 # uncoverable branch true
7788 # uncoverable branch false
7789 # uncoverable condition left count:1
7790 # uncoverable condition right count:1 */
7791 0 ▶ if (setuid((uid_t)cfg->drop_uid) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (setuid((uid_t)cfg->drop_uid) < 0) 0 0 0
7792 0 croak("Hyperman->run: setuid(%ld): %s", cfg->drop_uid, strerror(errno)); /* # uncoverable statement */
7793 /*
7794 # uncoverable statement
7795 # uncoverable branch true
7796 # uncoverable branch false
7797 # uncoverable condition left count:1
7798 # uncoverable condition right count:1
7799 # uncoverable condition left count:2
7800 # uncoverable condition right count:2
7801 # uncoverable condition left count:3
7802 # uncoverable condition right count:3 */
7803 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
7804 0 ▶ || geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
|| geteuid() != (uid_t)cfg->drop_uid)) /* # uncoverable statement */ 0 0 0
7805 0 croak("Hyperman->run: still not uid %ld after setuid", cfg->drop_uid); /* # uncoverable statement */
7806 }
7807 #else
7808 (void)cfg;
7809 #endif
7810 }
7811  
7812 /* The pid file is written whole and renamed into place, so a reader never
7813 * sees it empty, and removed at exit ONLY if it still holds this pid: two
7814 * supervisors overlap during a re-exec reload, and the one leaving must not
7815 * take the other's file with it. */
7816 #ifndef O_NOFOLLOW
7817 #define O_NOFOLLOW 0
7818 #endif
7819 /* loud: a failure croaks (boot). Quiet: -1 and a log line, for the
7820 * supervisor re-asserting its own pid after a successor died. */
7821 83 static int hm_write_pidfile_(pTHX_ const hm_worker_cfg *cfg, int loud) {
7822 83 const char *path = cfg->pid_path;
7823 char tmp[1024], num[32];
7824 83 int fd = -1, n, tries, in_place = 0;
7825 83 ▶ if (!path) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!path) return 0; 69 14 83
7826 /* The temporary is created EXCLUSIVELY and never through a symlink: it
7827 * is written as root, before the drop, in a directory others may be
7828 * able to write to, and a predictable name opened with O_TRUNC was an
7829 * invitation to point it at a file of theirs. The suffix is random too,
7830 * so a planted name is not even a denial of service. */
7831 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
7832 14 unsigned long r = (unsigned long)(hm_now_ns() ^ ((uint64_t)hm_os_getpid() << 20));
7833 14 n = snprintf(tmp, sizeof(tmp), "%s.%lx.tmp", path, r + (unsigned long)tries * 7919UL);
7834 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
7835 1 croak("Hyperman->run: pid_file path too long");
7836 13 fd = hm_os_open_file(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644);
7837 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
7838 }
7839 /* Eight random names cannot all exist: an EEXIST that outlasts the loop
7840 * is a directory that will not create anything for this user, which
7841 * DragonFly reports this way where others say EACCES (CPAN Testers,
7842 * 0.68). It is handled as that refusal below. */
7843 /*
7844 # uncoverable branch true
7845 # uncoverable condition left count:1
7846 # uncoverable condition left count:2 */
7847 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
7848 #ifndef _WIN32
7849 /*
7850 # uncoverable branch true class:ignore_covered_err
7851 # uncoverable condition left count:1 class:ignore_covered_err
7852 # uncoverable condition left count:2 class:ignore_covered_err
7853 # uncoverable condition left count:3 class:ignore_covered_err
7854 # uncoverable condition left count:4 class:ignore_covered_err
7855 # uncoverable condition right count:4 class:ignore_covered_err */
7856 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
7857 /* A re-exec successor already running as the dropped user, in a
7858 * directory only root may create in (/run): the file itself was
7859 * chowned to that user when root wrote it, so it is rewritten in
7860 * place. Not atomic - a reader can catch it empty - but a pid file
7861 * the successor cannot update at all named a dead process. */
7862 4 fd = hm_os_open_file(path, O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0644); /* # uncoverable statement class:ignore_covered_err */
7863 4 in_place = 1; /* # uncoverable statement class:ignore_covered_err */
7864 }
7865 #endif
7866 13 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 4 9 13
7867 /*
7868 # uncoverable branch false
7869 # uncoverable condition right count:1 class:ignore_covered_err
7870 # uncoverable condition right count:2 class:ignore_covered_err */
7871 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
7872 strerror(errno));
7873 0 hm_errlog("Hyperman: pid_file '%s': %s\n", path, strerror(errno)); /* # uncoverable statement */
7874 0 return -1; /* # uncoverable statement */
7875 }
7876 9 n = (int)hm_itoa(num, (long)hm_os_getpid());
7877 9 num[n++] = '\n';
7878 /*
7879 # uncoverable branch true
7880 # uncoverable condition left count:1 class:ignore_covered_err */
7881 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
7882 0 int e = errno; /* # uncoverable statement */
7883 0 hm_os_close(fd); /* # uncoverable statement */
7884 /*
7885 # uncoverable statement
7886 # uncoverable branch true
7887 # uncoverable branch false
7888 # uncoverable condition left count:1
7889 # uncoverable condition right count:1 */
7890 0 ▶ if (!in_place) (void)unlink(tmp);
Branch: 1 branch
BranchTrueFalseTotal
if (!in_place) (void)unlink(tmp); 0 0 0
7891 /*
7892 # uncoverable statement
7893 # uncoverable branch true
7894 # uncoverable branch false
7895 # uncoverable condition left count:1
7896 # uncoverable condition right count:1 */
7897 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
7898 0 hm_errlog("Hyperman: pid_file '%s': write: %s\n", path, strerror(e)); /* # uncoverable statement */
7899 0 return -1; /* # uncoverable statement */
7900 }
7901 #ifndef _WIN32
7902 /* Owned by the user the server will run as, so the successor of a
7903 * re-exec (born dropped) and the exit path can both still write it. */
7904 /*
7905 # uncoverable branch true class:ignore_covered_err
7906 # uncoverable condition left count:1 class:ignore_covered_err
7907 # uncoverable condition left count:2 class:ignore_covered_err
7908 # uncoverable condition right count:2 class:ignore_covered_err */
7909 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
7910 0 (void)fchown(fd, (uid_t)cfg->drop_uid, /* # uncoverable statement */
7911 /*
7912 # uncoverable statement
7913 # uncoverable condition left count:1
7914 # uncoverable condition right count:1 */
7915 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
7916 #endif
7917 9 hm_os_close(fd);
7918 /*
7919 # uncoverable branch true class:ignore_covered_err
7920 # uncoverable condition left count:1 class:ignore_covered_err */
7921 9 ▶ if (in_place) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (in_place) return 0; 1 8 9
7922 /*
7923 # uncoverable branch true
7924 # uncoverable condition left count:1 class:ignore_covered_err */
7925 8 ▶ if (rename(tmp, path) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (rename(tmp, path) < 0) { 0 8 8
7926 0 int e = errno; /* # uncoverable statement */
7927 0 (void)unlink(tmp); /* # uncoverable statement */
7928 /*
7929 # uncoverable statement
7930 # uncoverable branch true
7931 # uncoverable branch false
7932 # uncoverable condition left count:1
7933 # uncoverable condition right count:1 */
7934 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
7935 0 hm_errlog("Hyperman: pid_file '%s': rename: %s\n", path, strerror(e)); /* # uncoverable statement */
7936 0 return -1; /* # uncoverable statement */
7937 }
7938 8 return 0;
7939 }
7940 82 static void hm_write_pidfile(pTHX_ const hm_worker_cfg *cfg) {
7941 82 (void)hm_write_pidfile_(aTHX_ cfg, 1);
7942 77 }
7943  
7944 /* Removed at exit if it still holds this pid. A process that dropped
7945 * privileges may not unlink in the directory any more (/run is root's);
7946 * then the file is emptied instead, which is what a reader should take as
7947 * "not running", where a stale pid is a live lie. */
7948 77 static void hm_unlink_pidfile(const char *path) {
7949 char buf[32];
7950 int fd, n;
7951 84 ▶ if (!path) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!path) return; 69 8 77
7952 8 fd = hm_os_open_file(path, O_RDONLY | O_NOFOLLOW, 0);
7953 /*
7954 # uncoverable branch true
7955 # uncoverable condition left count:1 class:ignore_covered_err */
7956 8 ▶ if (fd < 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return; 0 8 8
7957 8 n = (int)read(fd, buf, sizeof(buf) - 1);
7958 8 hm_os_close(fd);
7959 /*
7960 # uncoverable branch true
7961 # uncoverable condition left count:1 class:ignore_covered_err */
7962 8 ▶ if (n <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return; 0 8 8
7963 8 buf[n] = '\0';
7964 8 ▶ if (atol(buf) != (long)hm_os_getpid()) return;
Branch: 1 branch
BranchTrueFalseTotal
if (atol(buf) != (long)hm_os_getpid()) return; 3 5 8
7965 /*
7966 # uncoverable branch false class:ignore_covered_err
7967 # uncoverable condition right count:1 class:ignore_covered_err */
7968 5 ▶ if (unlink(path) == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (unlink(path) == 0) return; 4 1 5
7969 /*
7970 # uncoverable statement class:ignore_covered_err
7971 # uncoverable branch true class:ignore_covered_err
7972 # uncoverable branch false class:ignore_covered_err
7973 # uncoverable condition left count:1 class:ignore_covered_err
7974 # uncoverable condition right count:1 class:ignore_covered_err
7975 # uncoverable condition left count:2 class:ignore_covered_err
7976 # uncoverable condition right count:2 class:ignore_covered_err */
7977 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
7978 1 fd = hm_os_open_file(path, O_WRONLY | O_TRUNC | O_NOFOLLOW, 0); /* # uncoverable statement class:ignore_covered_err */
7979 /*
7980 # uncoverable statement class:ignore_covered_err
7981 # uncoverable branch true class:ignore_covered_err
7982 # uncoverable branch false class:ignore_covered_err
7983 # uncoverable condition left count:1 class:ignore_covered_err
7984 # uncoverable condition right count:1 class:ignore_covered_err */
7985 1 ▶ if (fd >= 0) hm_os_close(fd);
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) hm_os_close(fd); 1 0 1
7986 }
7987 }
7988  
7989 /* Remove a variable from the C environment AND perl's %ENV, which is a hash
7990 * of its own, filled at startup: unsetenv alone leaves the application
7991 * reading the old value from the hash. Deleting through the hash updates
7992 * the C side via its magic; the explicit unsetenv covers a perl built
7993 * without that. */
7994 8 static void hm_env_unset(pTHX_ const char *name) {
7995 8 HV *penv = GvHV(PL_envgv);
7996 /*
7997 # uncoverable branch false class:ignore_covered_err
7998 # uncoverable condition right count:1 class:ignore_covered_err */
7999 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
8000 #ifndef _WIN32
8001 8 unsetenv(name);
8002 #endif
8003 8 }
8004  
8005 /* Socket activation: a service manager that bound the sockets hands them
8006 * over as fds 3.., naming the count in LISTEN_FDS and this pid in
8007 * LISTEN_PID. Specs marked `inherit` (or all of them under listen_fds) take
8008 * them in order instead of binding. Each one is checked to be a listening
8009 * socket of the family the spec resolved to, and both variables are removed
8010 * at once so no worker - and no server an application forks - adopts them
8011 * again. The same helper will seat a re-exec successor (08). */
8012 104 static void hm_adopt_fds(pTHX_ hm_worker_cfg *cfg) {
8013 104 const char *nfds = getenv("LISTEN_FDS"), *lpid = getenv("LISTEN_PID");
8014 104 int i, n, next = 3, want = 0;
8015 /* A spec that already holds a socket was seated by hm_adopt_env: a
8016 * re-exec successor of a socket-activated server. LISTEN_FDS was
8017 * removed from the environment at the first boot, so counting those
8018 * specs made every USR2 under systemd croak "not set". */
8019 216 ▶ for (i = 0; i < cfg->nlspecs; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) 112 104 216
8020 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
8021 10 want++;
8022 104 ▶ if (!want) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!want) return; 95 9 104
8023 #ifdef _WIN32
8024 croak("Hyperman->run: socket activation is not supported on Windows");
8025 #else
8026 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
8027 1 croak("Hyperman->run: a listener asks to inherit a socket but LISTEN_FDS "
8028 "and LISTEN_PID are not set");
8029 8 ▶ if (atol(lpid) != (long)hm_os_getpid())
Branch: 1 branch
BranchTrueFalseTotal
if (atol(lpid) != (long)hm_os_getpid()) 2 6 8
8030 2 croak("Hyperman->run: LISTEN_PID is %s, this is %d: the sockets were "
8031 "not handed to this process", lpid, hm_os_getpid());
8032 6 ▶ if (cfg->reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) 1 5 6
8033 1 croak("Hyperman->run: an inherited socket cannot be rebound per worker; "
8034 "drop reuseport");
8035 5 n = atoi(nfds);
8036 7 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 6 1 7
8037 6 hm_listener_spec *s = &cfg->lspecs[i];
8038 struct sockaddr_storage got;
8039 6 socklen_t gl = sizeof(got);
8040 6 int fd, acc = 0;
8041 6 socklen_t al = sizeof(acc);
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 # uncoverable condition right count:2 class:ignore_covered_err
8047 # uncoverable condition left count:3 class:ignore_covered_err */
8048 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
8049 6 ▶ if (next - 3 >= n)
Branch: 1 branch
BranchTrueFalseTotal
if (next - 3 >= n) 1 5 6
8050 1 croak("Hyperman->run: LISTEN_FDS=%d but listener %d wants one too", n, i);
8051 5 fd = next++;
8052 /*
8053 # uncoverable branch true class:ignore_covered_err
8054 # uncoverable condition left count:1 class:ignore_covered_err */
8055 5 ▶ if (s->http3)
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) 0 5 5
8056 0 croak("Hyperman->run: an inherited listener cannot carry http3"); /* # uncoverable statement class:ignore_covered_err */
8057 5 ▶ if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0) 1 4 5
8058 1 croak("Hyperman->run: inherited fd %d: getsockname: %s", fd, strerror(errno));
8059 4 ▶ if (got.ss_family != s->sa.ss_family)
Branch: 1 branch
BranchTrueFalseTotal
if (got.ss_family != s->sa.ss_family) 1 3 4
8060 1 croak("Hyperman->run: inherited fd %d is address family %d, listener %d "
8061 "resolved to %d", fd, (int)got.ss_family, i, (int)s->sa.ss_family);
8062 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
8063 1 croak("Hyperman->run: inherited fd %d is not a listening socket", fd); /* # uncoverable statement class:ignore_covered_err */
8064 2 hm_set_nonblock(fd);
8065 /* As a bound listener is (hm_make_listener): not into anything the
8066 * application execs; hm_reexec clears it for the successor alone. */
8067 2 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
8068 2 s->fd = fd;
8069 }
8070 1 hm_env_unset(aTHX_ "LISTEN_FDS");
8071 1 hm_env_unset(aTHX_ "LISTEN_PID");
8072 1 hm_env_unset(aTHX_ "LISTEN_FDNAMES");
8073 #endif
8074 }
8075  
8076 /* ---- re-exec reload (USR2) -------------------------------------------------
8077 *
8078 * HUP reforks the pool from this process, which still holds the application
8079 * as it was compiled at boot. USR2 starts a NEW supervisor - a fresh perl, a
8080 * fresh compile of the application - that takes the bound listeners over,
8081 * forks its own pool, and only then asks this one to drain. The listen fds
8082 * are held by one process or the other the whole time, so no connection is
8083 * refused. A successor that fails to start changes nothing here; this
8084 * supervisor keeps serving and says so.
8085 *
8086 * What crosses the exec: the listener fds, named in HYPERMAN_REEXEC by the
8087 * host:port (or path) each was bound for, so the successor's configuration
8088 * may reorder or add listeners; the arena NAME, when there is one, so both
8089 * pools share the one arena during the overlap; and the old supervisor's
8090 * pid, to TERM. An anonymous arena is not shared: it is a private mapping
8091 * with no name to attach to, and the successor starts a fresh one (the
8092 * denylist and the rate counters begin again at the handoff). */
8093  
8094 #ifndef _WIN32
8095 5 static void hm_reexec(pTHX_ const hm_worker_cfg *cfg, const sigset_t *orig) {
8096 char env[4096];
8097 5 size_t n = 0;
8098 int i, k;
8099 pid_t pid;
8100 SV *perl;
8101 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
8102 1 hm_errlog("Hyperman: USR2 ignored: successor %d is still starting",
8103 (int)hm_resup_pid);
8104 1 return;
8105 }
8106 /*
8107 # uncoverable branch true class:ignore_covered_err
8108 # uncoverable condition left count:1 class:ignore_covered_err
8109 # uncoverable condition left count:2 class:ignore_covered_err */
8110 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
8111 0 hm_errlog("Hyperman: USR2 ignored: no argv to re-exec with"); /* # uncoverable statement */
8112 0 return; /* # uncoverable statement */
8113 }
8114 4 k = snprintf(env + n, sizeof(env) - n, "sup=%d", hm_os_getpid());
8115 /*
8116 # uncoverable branch true class:ignore_covered_err
8117 # uncoverable condition left count:1 class:ignore_covered_err
8118 # uncoverable condition left count:2 class:ignore_covered_err */
8119 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
8120 4 n += (size_t)k;
8121 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
8122 3 k = snprintf(env + n, sizeof(env) - n, ";arena=%.*s",
8123 3 (int)cfg->arena_name_len, cfg->arena_name);
8124 /*
8125 # uncoverable branch true class:ignore_covered_err
8126 # uncoverable condition left count:1 class:ignore_covered_err
8127 # uncoverable condition left count:2 class:ignore_covered_err */
8128 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
8129 0 hm_errlog("Hyperman: USR2 ignored: the arena name does not fit the " /* # uncoverable statement */
8130 "handover environment");
8131 0 return; /* # uncoverable statement */
8132 }
8133 3 n += (size_t)k;
8134 }
8135 9 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 5 4 9
8136 5 const hm_listener_spec *s = &cfg->lspecs[i];
8137 /*
8138 # uncoverable branch true
8139 # uncoverable condition left count:1 class:ignore_covered_err */
8140 5 ▶ if (s->fd < 0) continue; /* reuseport: nothing held */
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd < 0) continue; /* reuseport: nothing held */ 0 5 5
8141 5 ▶ if (s->path)
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) 1 4 5
8142 1 k = snprintf(env + n, sizeof(env) - n, ";u=%s|%d", s->path, s->fd);
8143 else
8144 4 k = snprintf(env + n, sizeof(env) - n, ";l=%s|%d|%d|%d",
8145 /*
8146 # uncoverable condition right count:1
8147 # uncoverable condition right count:2 */
8148 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
8149 4 ▶ s->fd, s->udp_fd);
Branch: 1 branch
BranchTrueFalseTotal
s->fd, s->udp_fd); 4 0 4
8150 /*
8151 # uncoverable branch true class:ignore_covered_err
8152 # uncoverable condition left count:1 class:ignore_covered_err
8153 # uncoverable condition left count:2 class:ignore_covered_err */
8154 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
8155 0 hm_errlog("Hyperman: USR2 ignored: too many listeners to hand over"); /* # uncoverable statement */
8156 0 return; /* # uncoverable statement */
8157 }
8158 5 n += (size_t)k;
8159 }
8160 4 perl = get_sv("\030", 0); /* $^X */
8161 /*
8162 # uncoverable branch true class:ignore_covered_err
8163 # uncoverable condition left count:1 class:ignore_covered_err
8164 # uncoverable condition left count:2 class:ignore_covered_err */
8165 4 ▶ if (!perl || !SvOK(perl)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!perl || !SvOK(perl)) { 4 0 4
if (!perl || !SvOK(perl)) { 0 4 4
8166 0 hm_errlog("Hyperman: USR2 ignored: $^X is not set"); /* # uncoverable statement */
8167 0 return; /* # uncoverable statement */
8168 }
8169 4 pid = fork();
8170 /*
8171 # uncoverable branch true
8172 # uncoverable condition left count:1 class:ignore_covered_err */
8173 8 ▶ if (pid < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid < 0) { 0 8 8
8174 0 hm_errlog("Hyperman: USR2: fork: %s", strerror(errno)); /* # uncoverable statement */
8175 0 return; /* # uncoverable statement */
8176 }
8177 8 ▶ if (pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) { 4 4 8
8178 /* The supervisor runs with its signals BLOCKED and the mask survives
8179 * exec, as does a pending alarm: a successor born with either would
8180 * never wake in its own sigsuspend. */
8181 4 sigprocmask(SIG_SETMASK, orig, NULL);
8182 4 alarm(0);
8183 4 signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL);
8184 4 signal(SIGHUP, SIG_DFL); signal(SIGUSR1, SIG_DFL);
8185 4 signal(SIGUSR2, SIG_DFL); signal(SIGCHLD, SIG_DFL);
8186 4 signal(SIGALRM, SIG_DFL);
8187 9 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 5 4 9
8188 5 const hm_listener_spec *s = &cfg->lspecs[i];
8189 /*
8190 # uncoverable branch false class:ignore_covered_err
8191 # uncoverable condition right count:1 class:ignore_covered_err */
8192 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
8193 /*
8194 # uncoverable branch true class:ignore_covered_err
8195 # uncoverable condition left count:1 class:ignore_covered_err */
8196 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
8197 }
8198 4 setenv("HYPERMAN_REEXEC", env, 1);
8199 4 execv(SvPV_nolen(perl), hm_boot_argv);
8200 4 _exit(127); /* # uncoverable statement class:ignore_covered_err */
8201 }
8202 4 hm_resup_pid = pid;
8203 4 hm_errlog("Hyperman: USR2: successor %d started; serving until it takes over",
8204 (int)pid);
8205 }
8206  
8207 /* The successor's half: HYPERMAN_REEXEC names the sockets and the arena.
8208 * Runs after the addresses are resolved and before anything binds. */
8209 105 static void hm_adopt_env(pTHX_ hm_worker_cfg *cfg) {
8210 105 const char *raw = getenv("HYPERMAN_REEXEC");
8211 105 char *buf, *tok, *save = NULL;
8212 int i;
8213 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
8214 5 buf = strdup(raw);
8215 /*
8216 # uncoverable branch true
8217 # uncoverable condition left count:1 class:ignore_covered_err */
8218 5 ▶ if (!buf) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!buf) return; 0 5 5
8219 5 hm_env_unset(aTHX_ "HYPERMAN_REEXEC");
8220 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
8221 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
8222 17 ▶ if (strncmp(tok, "sup=", 4) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (strncmp(tok, "sup=", 4) == 0) { 5 12 17
8223 5 hm_resup_old = (pid_t)atol(tok + 4);
8224 12 ▶ } else if (strncmp(tok, "arena=", 6) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (strncmp(tok, "arena=", 6) == 0) { 4 8 12
8225 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
8226 2 cfg->arena_name = strdup(tok + 6); /* process lifetime */
8227 2 cfg->arena_name_len = strlen(tok + 6);
8228 }
8229 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
8230 7 int unix_ = tok[0] == 'u';
8231 7 char *f1, *f2, *f3, *f4, *s2 = NULL;
8232 7 int fd = -1, udp = -1, port = 0, matched = 0;
8233 const char *name;
8234 7 f1 = strtok_r(tok + 2, "|", &s2);
8235 7 f2 = strtok_r(NULL, "|", &s2);
8236 7 f3 = strtok_r(NULL, "|", &s2);
8237 7 f4 = strtok_r(NULL, "|", &s2);
8238 /*
8239 # uncoverable branch true class:ignore_covered_err
8240 # uncoverable condition left count:1 class:ignore_covered_err
8241 # uncoverable condition left count:2 class:ignore_covered_err */
8242 7 ▶ if (!f1 || !f2) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!f1 || !f2) continue; 7 0 7
if (!f1 || !f2) continue; 0 7 7
8243 7 name = f1;
8244 7 ▶ if (unix_) { fd = atoi(f2); }
Branch: 1 branch
BranchTrueFalseTotal
if (unix_) { fd = atoi(f2); } 2 5 7
8245 /*
8246 # uncoverable condition left count:1 class:ignore_covered_err
8247 # uncoverable condition right count:2 class:ignore_covered_err */
8248 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
8249 /* reuseport pools rebind per worker and hold nothing to adopt */
8250 /*
8251 # uncoverable branch false class:ignore_covered_err
8252 # uncoverable condition right count:1 class:ignore_covered_err */
8253 7 ▶ if (!cfg->reuseport) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg->reuseport) { 7 0 7
8254 10 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 8 2 10
8255 8 hm_listener_spec *s = &cfg->lspecs[i];
8256 8 ▶ if (s->fd >= 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd >= 0) continue; 1 7 8
8257 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
8258 5 ▶ : (!s->path && s->port == port
Branch: 1 branch
BranchTrueFalseTotal
: (!s->path && s->port == port 4 1 5
8259 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
8260 struct sockaddr_storage got;
8261 5 socklen_t gl = sizeof(got);
8262 5 int acc = 0;
8263 5 socklen_t al = sizeof(acc);
8264 /*
8265 # uncoverable condition left count:2 class:ignore_covered_err
8266 # uncoverable condition left count:3 class:ignore_covered_err
8267 # uncoverable condition right count:3 class:ignore_covered_err
8268 # uncoverable condition left count:4 class:ignore_covered_err */
8269 5 ▶ if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0
Branch: 1 branch
BranchTrueFalseTotal
if (getsockname(fd, (struct sockaddr *)&got, &gl) < 0 4 1 5
8270 4 ▶ || got.ss_family != s->sa.ss_family
Branch: 1 branch
BranchTrueFalseTotal
|| got.ss_family != s->sa.ss_family 4 0 4
8271 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
8272 1 croak("Hyperman->run: re-exec: handed fd %d for %s is not "
8273 "the listener it was said to be", fd, name);
8274 4 hm_set_nonblock(fd); /* # uncoverable statement class:ignore_covered_err */
8275 4 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); /* # uncoverable statement class:ignore_covered_err */
8276 4 s->fd = fd; /* # uncoverable statement class:ignore_covered_err */
8277 /*
8278 # uncoverable statement class:ignore_covered_err
8279 # uncoverable branch true
8280 # uncoverable condition left count:1
8281 # uncoverable condition left count:2
8282 # uncoverable condition right count:2 */
8283 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
8284 0 hm_set_nonblock(udp); /* # uncoverable statement */
8285 0 (void)fcntl(udp, F_SETFD, fcntl(udp, F_GETFD, 0) | FD_CLOEXEC); /* # uncoverable statement */
8286 0 s->udp_fd = udp; /* # uncoverable statement */
8287 /*
8288 # uncoverable statement class:ignore_covered_err
8289 # uncoverable branch true
8290 # uncoverable condition left count:1 */
8291 4 ▶ } else if (udp >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (udp >= 0) { 0 4 4
8292 0 hm_os_close(udp); /* # uncoverable statement */
8293 }
8294 4 matched = 1;
8295 4 break;
8296 }
8297 }
8298 }
8299 6 ▶ if (!matched) { /* a listener the new config dropped */
Branch: 1 branch
BranchTrueFalseTotal
if (!matched) { /* a listener the new config dropped */ 2 4 6
8300 /*
8301 # uncoverable branch false class:ignore_covered_err
8302 # uncoverable condition right count:1 class:ignore_covered_err */
8303 2 ▶ if (fd >= 0) hm_os_close(fd);
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) hm_os_close(fd); 2 0 2
8304 /*
8305 # uncoverable branch true class:ignore_covered_err
8306 # uncoverable condition left count:1 class:ignore_covered_err */
8307 2 ▶ if (udp >= 0) hm_os_close(udp);
Branch: 1 branch
BranchTrueFalseTotal
if (udp >= 0) hm_os_close(udp); 0 2 2
8308 }
8309 }
8310 }
8311 4 free(buf);
8312 4 hm_errlog("Hyperman: re-exec successor %d: sockets adopted from supervisor %d",
8313 4 hm_os_getpid(), (int)hm_resup_old);
8314 }
8315  
8316 /* The successor's pool is up: tell the old supervisor to drain. Waited for a
8317 * scoreboard row per child (ten seconds at most), or one second flat when
8318 * there is no board, so the old pool is not torn down ahead of the new one
8319 * answering. */
8320 27 static void hm_reexec_takeover(const pid_t *kids, int nkids) {
8321 int i, tries;
8322 27 ▶ if (hm_resup_old <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hm_resup_old <= 0) return; 23 4 27
8323 /*
8324 # uncoverable branch false class:ignore_covered_err
8325 # uncoverable condition right count:1 class:ignore_covered_err */
8326 4 ▶ if (hm_sa_board_live()) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sa_board_live()) { 4 0 4
8327 /*
8328 # uncoverable branch false class:ignore_covered_err
8329 # uncoverable condition right count:1 class:ignore_covered_err */
8330 8 ▶ for (tries = 0; tries < 100; tries++) {
Branch: 1 branch
BranchTrueFalseTotal
for (tries = 0; tries < 100; tries++) { 8 0 8
8331 8 int ready = 1;
8332 16 ▶ for (i = 0; i < nkids; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nkids; i++) { 12 4 16
8333 sa_sb_reading rd;
8334 12 ▶ 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 8 12
8335 }
8336 8 ▶ if (ready) break;
Branch: 1 branch
BranchTrueFalseTotal
if (ready) break; 4 4 8
8337 4 poll(NULL, 0, 100);
8338 }
8339 } else {
8340 0 poll(NULL, 0, 1000); /* # uncoverable statement class:ignore_covered_err */
8341 }
8342 /*
8343 # uncoverable branch false class:ignore_covered_err
8344 # uncoverable condition right count:1 class:ignore_covered_err */
8345 4 ▶ if (kill(hm_resup_old, SIGTERM) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (kill(hm_resup_old, SIGTERM) == 0) 4 0 4
8346 4 hm_errlog("Hyperman: re-exec: pool up, supervisor %d asked to drain",
8347 (int)hm_resup_old);
8348 4 hm_resup_old = 0;
8349 }
8350 #endif /* !_WIN32 */
8351  
8352 114 static void hm_run_server(pTHX_ hm_worker_cfg *cfg) {
8353 114 int workers = cfg->nworkers;
8354  
8355 /* Before the arena, before the bind: an unknown user or group is refused
8356 * while nothing is held, and on Windows the whole family is. */
8357 114 hm_resolve_drop(aTHX_ cfg);
8358 #ifndef _WIN32
8359 /* The umask FIRST: it is asked for so that what the server creates - the
8360 * unix socket, the pid file, the logs - comes out with it, and all of
8361 * those are made below. Applied at the drop it reached only the files
8362 * the application made. */
8363 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
8364 #endif
8365 /* Likewise every listen address: a host that does not resolve is a
8366 * croak here, never a bind of INADDR_ANY in its place. */
8367 {
8368 int i;
8369 char err[128];
8370 221 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 116 105 221
8371 116 hm_listener_spec *s = &cfg->lspecs[i];
8372 116 s->fd = -1; /* calloc'd, and 0 is a descriptor */
8373 116 s->udp_fd = -1;
8374 116 ▶ if (s->path) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->path) { 8 108 116
8375 8 ▶ if (cfg->reuseport)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) 1 7 8
8376 1 croak("Hyperman->run: reuseport cannot rebind a path listener "
8377 "per worker (each rebind would unlink the other's socket)");
8378 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
8379 1 croak("Hyperman->run: listen path '%s': %s", s->path, err);
8380 }
8381 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
8382 err, sizeof(err)) < 0)
8383 1 ▶ croak("Hyperman->run: listen host '%s': %s",
Branch: 1 branch
BranchTrueFalseTotal
croak("Hyperman->run: listen host '%s': %s", 1 0 1
8384 s->host ? s->host : "", err); /* # uncoverable condition right count:1 class:ignore_covered_err */
8385 }
8386 }
8387 #ifndef _WIN32
8388 105 hm_adopt_env(aTHX_ cfg); /* a re-exec successor: the old sockets */
8389 #endif
8390 104 hm_adopt_fds(aTHX_ cfg);
8391  
8392 96 ▶ if (!hm_empty_input)
Branch: 1 branch
BranchTrueFalseTotal
if (!hm_empty_input) 83 13 96
8393 83 hm_empty_input = hm_new_input(aTHX_ "", 0); /* inherited by workers */
8394 96 ▶ if (workers < 1) /* default: one per CPU */
Branch: 1 branch
BranchTrueFalseTotal
if (workers < 1) /* default: one per CPU */ 13 83 96
8395 13 workers = hm_os_ncpu(); /* always 1 on Windows */
8396 96 cfg->nworkers = workers;
8397  
8398 /* The Shared::Arena, created HERE - before any worker forks - so every
8399 * worker inherits the one mapping, and from Perl, so Hyperman->arena is
8400 * the real object with every tenant on it. The denylist and the rate
8401 * counters are two maps in it; static `deny` entries are loaded now, in
8402 * the parent, so they are live from the first accepted connection.
8403 * Single-worker (dev) mode maps it too, so the ABI behaves the same
8404 * whether or not a supervisor forks. */
8405 96 hm_sa_open(aTHX_ cfg->arena_name, cfg->arena_name_len,
8406 96 ▶ cfg->arena_size ? cfg->arena_size
Branch: 1 branch
BranchTrueFalseTotal
cfg->arena_size ? cfg->arena_size 2 94 96
8407 94 : hm_sa_bytes(cfg->deny_cap, cfg->rate_cap,
8408 cfg->bus_slots, cfg->bus_slot_size));
8409 {
8410 96 const char *which = NULL;
8411 96 int err = 0;
8412 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
8413 2 warn("Hyperman: could not carve the \"%s\" map in the arena "
8414 "(Shared::Arena error %d): the denylist and the rate "
8415 "counters fail open; raise arena_size", which, err);
8416 }
8417  
8418 /* QUIC's stateless-reset and (later) Retry secret, generated HERE - once,
8419 * before any worker forks - for the same reason the TLS ticket key is:
8420 * under SO_REUSEPORT a client's token can land on a different worker than
8421 * the one that issued it, and a per-worker secret would make every such
8422 * token unverifiable. Inherited across the fork, so every worker agrees. */
8423 96 hm_quic_secret_init();
8424  
8425 /* The message bus, a ring in the same arena and for the same reason: a
8426 * ring created after the fork would be one ring per worker, which is a
8427 * bus that delivers to nobody. Opened even in single-worker mode, so the
8428 * ABI behaves the same whether or not a supervisor forks. */
8429 {
8430 96 int err = 0;
8431 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
8432 2 warn("Hyperman: could not carve the bus ring in the arena "
8433 "(Shared::Arena error %d): the bus is local-only; raise "
8434 "arena_size", err);
8435 }
8436 /* ... and the wakeup descriptors, HERE for the same reason as the ring
8437 * and one more: a pipe created inside a worker is invisible to its
8438 * siblings, so a bus built after the fork delivers to some workers and
8439 * not others.
8440 *
8441 * TWO GENERATIONS' WORTH, plus the supervisor's own. A HUP or USR2 forks
8442 * the replacement pool while the old one is still draining, so both exist
8443 * at once and both want descriptors - and sized for one generation the
8444 * fresh workers found every slot held and came up deaf, which outlives the
8445 * recycle that caused it. Shared::Arena caps this at its own ceiling. */
8446 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
8447 /* The worker scoreboard, one row per worker plus one, and the
8448 * distinct-client sketch when asked for. Neither is on a hot path by
8449 * default: the board is mirrored by a timer, the sketch is opt-in. */
8450 {
8451 96 int err = 0;
8452 /* Two generations' worth, like the wakers: a re-exec successor's
8453 * pool shares this board with the pool it replaces until that one
8454 * has drained, and a row is not reclaimable while its worker lives. */
8455 /*
8456 # uncoverable branch true class:ignore_covered_err
8457 # uncoverable condition right count:1 class:ignore_covered_err
8458 # uncoverable condition left count:2 class:ignore_covered_err */
8459 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
8460 0 warn("Hyperman: could not carve the worker scoreboard in the arena " /* # uncoverable statement class:ignore_covered_err */
8461 "(Shared::Arena error %d): pool_stats is empty; raise "
8462 "arena_size", err);
8463 /*
8464 # uncoverable branch true class:ignore_covered_err
8465 # uncoverable condition left count:1 class:ignore_covered_err
8466 # uncoverable condition left count:2 class:ignore_covered_err */
8467 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
8468 0 warn("Hyperman: could not carve the distinct-client sketch in the " /* # uncoverable statement */
8469 "arena (Shared::Arena error %d): distinct_clients is off", err); /* # uncoverable statement */
8470 }
8471 /*
8472 # uncoverable condition right count:2 class:ignore_covered_err
8473 # uncoverable condition right count:3 class:ignore_covered_err */
8474 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
8475 3 AV *av = (AV *)SvRV(cfg->deny);
8476 3 SSize_t i, n = av_len(av) + 1;
8477 6 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 3 3 6
8478 3 SV **e = av_fetch(av, i, 0);
8479 /*
8480 # uncoverable branch false class:ignore_covered_err
8481 # uncoverable condition right count:1 class:ignore_covered_err
8482 # uncoverable condition right count:2 class:ignore_covered_err
8483 # uncoverable condition right count:3 class:ignore_covered_err */
8484 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
8485 }
8486 }
8487  
8488 #ifndef SO_REUSEPORT
8489 if (cfg->reuseport) croak("Hyperman: SO_REUSEPORT not supported on this platform");
8490 #endif
8491 #ifndef __linux__
8492 if (cfg->affinity) croak("Hyperman: CPU affinity is Linux-only");
8493 #endif
8494  
8495 /* Per listener: build the TLS context before forking, so a bad cert/key
8496 * fails fast and the (read-only) SSL_CTX is shared copy-on-write across
8497 * workers. Then bind - in the parent, unless reuseport (each worker binds
8498 * its own). Under reuseport the parent still binds one probe fd so an
8499 * unusable address (e.g. a privileged port without root) fails fast. */
8500 {
8501 int i;
8502 197 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 104 93 197
8503 104 hm_listener_spec *s = &cfg->lspecs[i];
8504 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
8505 11 s->tls_ctx = hm_tls_ctx_build(aTHX_ s->tls_cert, s->tls_key,
8506 s->tls_ca, s->tls_verify,
8507 s->tls_sni, s->http2, NULL, 0);
8508 11 ▶ if (!s->tls_ctx)
Branch: 1 branch
BranchTrueFalseTotal
if (!s->tls_ctx) 3 8 11
8509 3 croak("Hyperman: TLS: could not initialise from cert '%s' "
8510 "/ key '%s'", s->tls_cert, s->tls_key);
8511 }
8512 }
8513 }
8514  
8515 /* The access-log format, compiled once here so an unknown directive is a
8516 * croak before the fork and a line is a walk over an array after it. The
8517 * tokens are process-lifetime: every worker reads the parent's copy. */
8518 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
8519 3 hm_logfmt_json(aTHX_ &cfg->logtok, &cfg->nlogtok);
8520 3 cfg->log_json = 1;
8521 3 cfg->log_wants_t0 = 1;
8522 } else {
8523 char err[64];
8524 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
8525 &cfg->logtok, &cfg->nlogtok, &cfg->log_wants_t0,
8526 err, sizeof(err)) < 0)
8527 4 croak("Hyperman->run: access_log_format: unknown directive %s", err);
8528 }
8529 /* The error log, likewise opened once and inherited. */
8530 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 */ 12 77 89
if (cfg->err_path && cfg->err_fd < 0) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 12 0 12
8531 12 cfg->err_fd = hm_os_open_file(cfg->err_path,
8532 O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
8533 12 ▶ if (cfg->err_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->err_fd < 0) 1 11 12
8534 1 croak("Hyperman: open error_log '%s': %s", cfg->err_path, strerror(errno));
8535 }
8536 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; 12 76 88
8537  
8538 /* Open the access-log file once in the parent so all workers share (and
8539 * O_APPEND to) the same fd - whole-line writes stay atomic between them. */
8540 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
8541 8 cfg->log_fd = hm_os_open_file(cfg->log_path,
8542 O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
8543 8 ▶ if (cfg->log_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->log_fd < 0) 1 7 8
8544 1 croak("Hyperman: open access_log '%s': %s",
8545 cfg->log_path, strerror(errno));
8546 }
8547  
8548 /* Under reuseport the workers rebind their ports themselves, which
8549 * needs the privilege for a port below 1024 that a dropped user no
8550 * longer has; that pairing is refused rather than half-honoured, and
8551 * refused here, before any bind, so it is the error a caller sees even
8552 * where this process could not bind the low port either. */
8553 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
8554 int i;
8555 /*
8556 # uncoverable branch false
8557 # uncoverable condition right count:1 class:ignore_covered_err */
8558 3 ▶ for (i = 0; i < cfg->nlspecs; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) 3 0 3
8559 /*
8560 # uncoverable branch false
8561 # uncoverable condition right count:1 class:ignore_covered_err */
8562 3 ▶ if (cfg->lspecs[i].port < 1024)
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->lspecs[i].port < 1024) 3 0 3
8563 3 croak("Hyperman->run: user => with reuseport => 1 cannot rebind "
8564 "port %d as the dropped user; drop reuseport or use a "
8565 "port above 1023", cfg->lspecs[i].port);
8566 }
8567  
8568 {
8569 int i;
8570 174 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 92 82 174
8571 92 hm_listener_spec *s = &cfg->lspecs[i];
8572 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
8573 #ifndef _WIN32
8574 /* `mode` through the umask around the bind, not a chmod of the
8575 * path afterwards: in a directory others can write to, the path
8576 * could be swapped for a symlink between the two and root would
8577 * chmod whatever it pointed at. A bind creates the socket with
8578 * 0777 less the umask, so the mask is the mode's complement. */
8579 86 mode_t saved_umask = 0;
8580 86 int have_saved = 0;
8581 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
8582 1 saved_umask = umask((mode_t)(~(unsigned)s->mode & 0777u));
8583 1 have_saved = 1;
8584 }
8585 #endif
8586 86 s->fd = hm_make_listener((struct sockaddr *)&s->sa, s->salen, cfg->reuseport);
8587 #ifndef _WIN32
8588 86 ▶ if (have_saved) (void)umask(saved_umask);
Branch: 1 branch
BranchTrueFalseTotal
if (have_saved) (void)umask(saved_umask); 1 85 86
8589 #endif
8590 86 ▶ if (s->fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd < 0) 2 84 86
8591 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
8592 s->path ? "" : s->host, s->port, strerror(errno));
8593 84 s->udp_fd = -1;
8594 /*
8595 # uncoverable branch true class:ignore_covered_err
8596 # uncoverable condition left count:1 class:ignore_covered_err */
8597 84 ▶ if (s->http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) { 0 84 84
8598 0 s->udp_fd = hm_make_udp_listener((struct sockaddr *)&s->sa, s->salen, cfg->reuseport); /* # uncoverable statement class:ignore_covered_err */
8599 /*
8600 # uncoverable branch true class:ignore_covered_err
8601 # uncoverable statement class:ignore_covered_err
8602 # uncoverable branch false class:ignore_covered_err
8603 # uncoverable condition left count:1 class:ignore_covered_err
8604 # uncoverable condition right count:1 class:ignore_covered_err */
8605 0 ▶ if (s->udp_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->udp_fd < 0) 0 0 0
8606 0 croak("Hyperman: bind udp %s:%d: %s", s->host, s->port, /* # uncoverable statement */
8607 strerror(errno)); /* # uncoverable statement */
8608 }
8609 84 ▶ if (cfg->reuseport) { /* probe only */
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) { /* probe only */ 1 83 84
8610 1 hm_os_close(s->fd); s->fd = -1;
8611 /*
8612 # uncoverable branch true class:ignore_covered_err
8613 # uncoverable condition left count:1 class:ignore_covered_err */
8614 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
8615 }
8616 }
8617 }
8618  
8619 /* Everything that needed root is held: the ports, the logs, the arena.
8620 * Record who we are, then stop being root, before the first fork so
8621 * every worker is born as the configured user. */
8622 82 hm_write_pidfile(aTHX_ cfg);
8623 77 hm_drop_privileges(aTHX_ cfg);
8624  
8625 77 ▶ if (workers == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (workers == 1) { 50 27 77
8626 /* dev mode: run the worker in this process, no supervisor. reuseport
8627 * needs a real bound fd here since there is no per-worker rebind. */
8628 /*
8629 # uncoverable branch true class:ignore_covered_err
8630 # uncoverable condition left count:1 class:ignore_covered_err */
8631 50 ▶ if (cfg->reuseport) {
Branch: 1 branch
BranchTrueFalseTotal
if (cfg->reuseport) { 0 50 50
8632 int i;
8633 /*
8634 # uncoverable statement
8635 # uncoverable branch true
8636 # uncoverable branch false
8637 # uncoverable condition left count:1
8638 # uncoverable condition right count:1 */
8639 0 ▶ for (i = 0; i < cfg->nlspecs; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < cfg->nlspecs; i++) { 0 0 0
8640 0 hm_listener_spec *s = &cfg->lspecs[i]; /* # uncoverable statement */
8641 0 s->fd = hm_make_listener((struct sockaddr *)&s->sa, s->salen, 1); /* # uncoverable statement */
8642 /*
8643 # uncoverable statement
8644 # uncoverable branch true
8645 # uncoverable branch false
8646 # uncoverable condition left count:1
8647 # uncoverable condition right count:1 */
8648 0 ▶ if (s->fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->fd < 0) 0 0 0
8649 0 croak("Hyperman: bind %s:%d: %s", s->host, s->port, /* # uncoverable statement */
8650 strerror(errno)); /* # uncoverable statement */
8651 /*
8652 # uncoverable statement
8653 # uncoverable branch true
8654 # uncoverable branch false
8655 # uncoverable condition left count:1
8656 # uncoverable condition right count:1 */
8657 0 ▶ if (s->http3) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->http3) { 0 0 0
8658 0 s->udp_fd = hm_make_udp_listener((struct sockaddr *)&s->sa, s->salen, 1); /* # uncoverable statement */
8659 /*
8660 # uncoverable statement
8661 # uncoverable branch true
8662 # uncoverable branch false
8663 # uncoverable condition left count:1
8664 # uncoverable condition right count:1 */
8665 0 ▶ if (s->udp_fd < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (s->udp_fd < 0) 0 0 0
8666 0 croak("Hyperman: bind udp %s:%d: %s", s->host, s->port, /* # uncoverable statement */
8667 strerror(errno)); /* # uncoverable statement */
8668 }
8669 }
8670 }
8671 50 hm_worker(aTHX_ cfg, NULL);
8672 50 hm_unlink_pidfile(cfg->pid_path);
8673 50 return;
8674 }
8675  
8676 #ifdef _WIN32
8677 /* Not a silent downgrade: an application sized for a pool is told, at
8678 * boot, in the log it already reads. */
8679 croak("Hyperman: a worker pool needs fork(2); Windows runs a single "
8680 "worker (workers => 1).");
8681 #else
8682 {
8683 int i;
8684 27 int backoff = 0;
8685 struct sigaction sa;
8686  
8687 93 ▶ for (i = 0; i < workers; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < workers; i++) { 66 27 93
8688 66 pid_t pid = hm_spawn(aTHX_ cfg, i);
8689 /*
8690 # uncoverable branch true
8691 # uncoverable condition left count:1 class:ignore_covered_err */
8692 66 ▶ if (pid < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid < 0) { 0 66 66
8693 /* take the pool down with us: croaking out of run() leaves
8694 * nobody supervising the workers already forked, and they
8695 * would keep the listening socket alive forever. */
8696 int j;
8697 /*
8698 # uncoverable statement
8699 # uncoverable branch true
8700 # uncoverable branch false
8701 # uncoverable condition left count:1
8702 # uncoverable condition right count:1 */
8703 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
8704 0 croak("Hyperman: fork: %s", strerror(errno)); /* # uncoverable statement */
8705 }
8706 66 hm_child_start[hm_nchildren] = time(NULL);
8707 66 hm_child_widx[hm_nchildren] = i;
8708 66 hm_children[hm_nchildren++] = pid;
8709 }
8710  
8711 27 memset(&sa, 0, sizeof(sa));
8712 27 sa.sa_handler = hm_sup_sig; /* no SA_RESTART: waitpid must EINTR */
8713 27 sigemptyset(&sa.sa_mask);
8714 27 sigaction(SIGTERM, &sa, NULL);
8715 27 sigaction(SIGINT, &sa, NULL);
8716 27 sigaction(SIGHUP, &sa, NULL);
8717 27 sigaction(SIGUSR1, &sa, NULL);
8718 27 sigaction(SIGUSR2, &sa, NULL);
8719 /* SIGCHLD must be delivered so sigsuspend() below wakes when a worker
8720 * exits; hm_sup_sig() treats it as a no-op wakeup. */
8721 27 sigaction(SIGCHLD, &sa, NULL);
8722 /* ALRM is the supervisor's only clock: a look at the scoreboard every
8723 * few seconds for a worker that is alive and not moving.
8724 *
8725 * An alarm the CALLER already had pending is not ours to cancel. A
8726 * watchdog that says `alarm(120); $server->run` has asked to be killed
8727 * at that deadline, and taking SIGALRM over - a handler that only sets
8728 * a flag, re-armed every tick - silently turns that into a promise
8729 * nothing keeps, leaving an unsupervised pool running for ever.
8730 *
8731 * So the pending deadline is read out and carried on the tick, which
8732 * is armed for it even with no board to watch. Letting the signal
8733 * through unhandled instead would kill the supervisor where it stood
8734 * and leave the workers holding the listening socket with nobody to
8735 * shut them down - a watchdog that takes half the pool with it is not
8736 * one. The tick is three seconds, so the deadline is met to within
8737 * that, and what follows is the death the caller asked for. */
8738 27 hm_sup_alarm_at = 0;
8739 {
8740 27 unsigned pending = alarm(0);
8741 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
8742 /*
8743 # uncoverable branch false class:ignore_covered_err
8744 # uncoverable condition right count:1 class:ignore_covered_err
8745 # uncoverable condition right count:2 class:ignore_covered_err */
8746 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
8747 27 sigaction(SIGALRM, &sa, NULL);
8748 27 alarm(HM_SUP_TICK_SECS);
8749 }
8750 }
8751  
8752 /* A successor: the pool is forked and serving on the adopted sockets;
8753 * the supervisor that handed them over can drain now. AFTER the
8754 * handlers above: this waits up to ten seconds, and the pid file
8755 * already names this process, so a deploy script retrying its
8756 * `kill -USR2 $(cat pidfile)` into that window hit SIG_DFL and
8757 * killed the successor, orphaning its workers on the sockets. */
8758 27 hm_reexec_takeover(hm_children, hm_nchildren);
8759  
8760 /* Race-free supervision: keep the acted-on signals blocked, check the
8761 * flags, reap without blocking, then sigsuspend() to wait for the next
8762 * signal atomically. A plain blocking waitpid() has a lost-wakeup
8763 * window - a signal arriving between a flag check and re-entering
8764 * waitpid() goes unserviced until some child happens to exit, which
8765 * for USR1 (stats dump) on an otherwise idle pool could be never. */
8766 {
8767 sigset_t block, orig;
8768 27 sigemptyset(&block);
8769 27 sigaddset(&block, SIGTERM); sigaddset(&block, SIGINT);
8770 27 sigaddset(&block, SIGHUP); sigaddset(&block, SIGUSR1);
8771 27 sigaddset(&block, SIGUSR2); sigaddset(&block, SIGCHLD);
8772 27 sigaddset(&block, SIGALRM);
8773 27 sigprocmask(SIG_BLOCK, &block, &orig);
8774  
8775 58 for (;;) {
8776 int st;
8777 pid_t pid;
8778  
8779 85 ▶ if (hm_sup_term) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_term) { 27 58 85
8780 93 ▶ for (i = 0; i < hm_nchildren; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) 66 27 93
8781 66 kill(hm_children[i], SIGTERM);
8782 /* workers self-bound their drain with shutdown_grace.
8783 * Waited for BY PID: a re-exec successor is a child of
8784 * this process too, and it does not exit - it is the
8785 * one that asked us to; waitpid(-1) would wait for it
8786 * for ever. */
8787 93 ▶ for (i = 0; i < hm_nchildren; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) { 66 27 93
8788 /*
8789 # uncoverable branch true class:ignore_covered_err
8790 # uncoverable condition left count:1 class:ignore_covered_err
8791 # uncoverable condition left count:2 class:ignore_covered_err
8792 # uncoverable condition right count:2 class:ignore_covered_err */
8793 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
8794 }
8795 27 break;
8796 }
8797  
8798 58 ▶ if (hm_sup_usr1) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_usr1) { 5 53 58
8799 5 hm_sup_usr1 = 0;
8800 /* With a scoreboard the supervisor has every worker's
8801 * numbers already: one aggregate line and one per row,
8802 * a dead row marked. Without one, each worker prints its
8803 * own line as it always did. */
8804 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
8805 else
8806 3 ▶ for (i = 0; i < hm_nchildren; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) 2 1 3
8807 2 kill(hm_children[i], SIGUSR1);
8808 }
8809  
8810 58 ▶ if (hm_sup_tick) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_tick) { 2 56 58
8811 2 hm_sup_tick = 0;
8812 /* The caller's own deadline, if it had one: take the pool
8813 * down and then let SIGALRM do what it would have done. */
8814 /*
8815 # uncoverable branch true class:ignore_covered_err
8816 # uncoverable condition left count:1 class:ignore_covered_err
8817 # uncoverable condition right count:1 class:ignore_covered_err
8818 # uncoverable condition left count:2 class:ignore_covered_err */
8819 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
8820 0 hm_sup_alarmed = 1; /* # uncoverable statement */
8821 0 hm_sup_term = 1; /* # uncoverable statement */
8822 2 continue; /* # uncoverable statement class:ignore_covered_err */
8823 }
8824 2 hm_sup_watch_board();
8825 2 alarm(HM_SUP_TICK_SECS);
8826 }
8827  
8828 58 ▶ if (hm_sup_usr2) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_usr2) { 5 53 58
8829 5 hm_sup_usr2 = 0;
8830 5 hm_reexec(aTHX_ cfg, &orig);
8831 }
8832  
8833 58 ▶ if (hm_sup_hup) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_hup) { 2 56 58
8834 pid_t old[1024];
8835 time_t old_start[1024];
8836 int old_widx[1024];
8837 2 int nold = hm_nchildren, nfresh = 0;
8838 2 memcpy(old, hm_children, nold * sizeof(pid_t));
8839 2 memcpy(old_start, hm_child_start, nold * sizeof(time_t));
8840 2 memcpy(old_widx, hm_child_widx, nold * sizeof(int));
8841 2 hm_sup_hup = 0;
8842 2 hm_nchildren = 0;
8843 6 ▶ for (i = 0; i < workers; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < workers; i++) { 4 2 6
8844 /* a failed fork must never reach hm_children: -1 there
8845 * turns the TERM sweep below into kill(-1, SIGTERM),
8846 * which signals every process this uid owns. */
8847 4 pid_t pid = hm_spawn(aTHX_ cfg, i);
8848 /*
8849 # uncoverable branch true
8850 # uncoverable condition left count:1 class:ignore_covered_err */
8851 4 ▶ if (pid < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (pid < 0) continue; 0 4 4
8852 4 hm_child_start[hm_nchildren] = time(NULL);
8853 4 hm_child_widx[hm_nchildren] = i;
8854 4 hm_children[hm_nchildren++] = pid;
8855 4 nfresh++;
8856 }
8857 /* retire one old worker per fresh one. Short of processes
8858 * the survivors stay in the live set, so a HUP under fork
8859 * pressure shrinks the pool instead of emptying it. */
8860 6 ▶ for (i = 0; i < nold; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nold; i++) { 4 2 6
8861 /*
8862 # uncoverable branch false
8863 # uncoverable condition right count:1 class:ignore_covered_err */
8864 4 ▶ if (i < nfresh) {
Branch: 1 branch
BranchTrueFalseTotal
if (i < nfresh) { 4 0 4
8865 4 kill(old[i], SIGTERM); /* drain gracefully */
8866 } else {
8867 0 hm_child_start[hm_nchildren] = old_start[i]; /* # uncoverable statement */
8868 0 hm_child_widx[hm_nchildren] = old_widx[i]; /* # uncoverable statement */
8869 0 hm_children[hm_nchildren++] = old[i]; /* # uncoverable statement */
8870 }
8871 }
8872 }
8873  
8874 /* reap every exited child without blocking, respawning the
8875 * live set. Recycled workers exiting are expected; only a
8876 * death in the live set is respawned. Abnormal quick deaths
8877 * (crash loops) back off exponentially; clean exits respawn
8878 * immediately. */
8879 73 ▶ while ((pid = waitpid(-1, &st, WNOHANG)) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
while ((pid = waitpid(-1, &st, WNOHANG)) > 0) { 17 56 73
8880 17 int live = 0;
8881 17 int dead_widx = 0;
8882 17 time_t started = 0;
8883 17 ▶ if (pid == hm_resup_pid) {
Branch: 1 branch
BranchTrueFalseTotal
if (pid == hm_resup_pid) { 1 16 17
8884 /* It never took over (a successor that did would have
8885 * TERMed us first). Nothing here changed, so nothing
8886 * is undone: this pool serves on. Except the pid
8887 * file, which it may have written before it died,
8888 * and which would then name a dead process for the
8889 * next `kill -USR2 $(cat pidfile)`: re-asserted. */
8890 1 hm_errlog("Hyperman: re-exec successor %d exited (%s %d) "
8891 "before taking over; still serving", (int)pid,
8892 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
8893 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
8894 1 hm_resup_pid = 0;
8895 1 (void)hm_write_pidfile_(aTHX_ cfg, 0);
8896 1 continue;
8897 }
8898 29 ▶ for (i = 0; i < hm_nchildren; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < hm_nchildren; i++) { 25 4 29
8899 25 ▶ if (hm_children[i] == pid) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_children[i] == pid) { 12 13 25
8900 12 started = hm_child_start[i];
8901 12 dead_widx = hm_child_widx[i];
8902 12 hm_nchildren--;
8903 12 hm_children[i] = hm_children[hm_nchildren];
8904 12 hm_child_start[i] = hm_child_start[hm_nchildren];
8905 12 hm_child_widx[i] = hm_child_widx[hm_nchildren];
8906 12 live = 1;
8907 12 break;
8908 }
8909 }
8910 16 ▶ if (!live) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!live) continue; 4 12 16
8911  
8912 {
8913 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
8914 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
8915 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
8916 /*
8917 # uncoverable branch true class:ignore_covered_err
8918 # uncoverable condition left count:1 class:ignore_covered_err */
8919 4 ▶ if (backoff > 30) backoff = 30;
Branch: 1 branch
BranchTrueFalseTotal
if (backoff > 30) backoff = 30; 0 4 4
8920 /* keep TERM responsive during crash-loop backoff */
8921 4 sigprocmask(SIG_SETMASK, &orig, NULL);
8922 4 sleep((unsigned)backoff);
8923 4 sigprocmask(SIG_BLOCK, &block, NULL);
8924 /*
8925 # uncoverable branch false class:ignore_covered_err
8926 # uncoverable condition right count:1 class:ignore_covered_err
8927 # uncoverable condition left count:2 class:ignore_covered_err
8928 # uncoverable condition right count:2 class:ignore_covered_err */
8929 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
8930 8 backoff = 0;
8931 }
8932 }
8933 {
8934 /* The replacement takes the DEAD worker's index, not
8935 * the position it is about to occupy here.
8936 *
8937 * Those are different numbers, because the array above
8938 * is kept packed by swapping the last entry down: kill
8939 * the worker at position 0 of three and the survivor
8940 * from position 2 moves into it, so the next free
8941 * position is 2 - an index a LIVE worker still holds.
8942 * Spawned with that, the replacement asked for a waker
8943 * slot its own sibling owned, was refused, and ran
8944 * deaf to the bus for the rest of its life while the
8945 * slot its predecessor had died holding went spare. It
8946 * was pinned to that sibling's CPU too.
8947 *
8948 * So identity comes from the child that left, and only
8949 * the bookkeeping position is reused. */
8950 12 int slot = hm_nchildren;
8951 12 pid_t fresh = hm_spawn(aTHX_ cfg, dead_widx);
8952 /*
8953 # uncoverable branch false class:ignore_covered_err
8954 # uncoverable condition right count:1 class:ignore_covered_err */
8955 12 ▶ if (fresh > 0) { /* never record a -1 */
Branch: 1 branch
BranchTrueFalseTotal
if (fresh > 0) { /* never record a -1 */ 12 0 12
8956 12 hm_child_start[slot] = time(NULL);
8957 12 hm_child_widx[slot] = dead_widx;
8958 12 hm_children[slot] = fresh;
8959 12 hm_nchildren = slot + 1;
8960 }
8961 }
8962 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
8963 }
8964  
8965 58 ▶ 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 56 58
8966  
8967 /* atomically unblock and sleep until the next signal */
8968 56 sigsuspend(&orig);
8969 }
8970  
8971 27 sigprocmask(SIG_SETMASK, &orig, NULL);
8972 27 hm_unlink_pidfile(cfg->pid_path);
8973  
8974 /* The pool is down because the caller's own alarm came due, so
8975 * finish the job the alarm was set to do. */
8976 /*
8977 # uncoverable branch true class:ignore_covered_err
8978 # uncoverable condition left count:1 class:ignore_covered_err */
8979 27 ▶ if (hm_sup_alarmed) {
Branch: 1 branch
BranchTrueFalseTotal
if (hm_sup_alarmed) { 0 27 27
8980 0 signal(SIGALRM, SIG_DFL); /* # uncoverable statement */
8981 0 raise(SIGALRM); /* # uncoverable statement */
8982 }
8983 }
8984 }
8985 #endif /* !_WIN32 */
8986 }
8987  
8988 /* loop object <-> pointer */
8989 3039 static hm_loop *hm_loop_from_sv(pTHX_ SV *sv) {
8990 /*
8991 # uncoverable condition left count:1 class:ignore_covered_err
8992 # uncoverable condition left count:3 class:ignore_covered_err */
8993 3039 ▶ if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop")))
Branch: 3 branches
BranchTrueFalseTotal
if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop"))) 3039 0 3039
if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop"))) 3038 1 3039
if (!(sv && SvROK(sv) && sv_derived_from(sv, "Hyperman::Loop"))) 0 3038 3038
8994 1 croak("not a Hyperman::Loop");
8995 3038 return INT2PTR(hm_loop *, SvIV(SvRV(sv)));
8996 }
8997  
8998 /* The Perl wrapper for a loop. ONE blessed referent per loop, however many
8999 * times this is asked: Hyperman::Loop->new, psgix.loop, Hyperman->loop and
9000 * the ABI's sv_of_loop used to each mint their own, and the first wrapper
9001 * whose refcount hit zero freed a Perl-owned loop under every other one.
9002 * The loop keeps a WEAK copy, so holding the wrapper is what keeps the loop,
9003 * and the loop holding its own wrapper keeps nothing alive. */
9004 925 static SV *hm_loop_to_sv(pTHX_ hm_loop *loop) {
9005 SV *rv;
9006 925 ▶ 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); 801 124 925
if (loop->self_sv && SvROK(loop->self_sv)) return newSVsv(loop->self_sv); 14 787 801
9007 911 rv = newRV_noinc(newSViv(PTR2IV(loop)));
9008 911 sv_bless(rv, gv_stashpv("Hyperman::Loop", GV_ADD));
9009 911 ▶ 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 */ 787 124 911
9010 911 loop->self_sv = newSVsv(rv);
9011 911 sv_rvweaken(loop->self_sv);
9012 911 return rv;
9013 }
9014  
9015 /* install_await: $Hyperman::Future::AWAIT pumps this loop */
9016 XS_INTERNAL(hm_xs_await_cb);
9017 1 XS_INTERNAL(hm_xs_await_cb) {
9018 1 dXSARGS;
9019 1 hm_clos *cl = hm_clos_of(aTHX_ cv);
9020 /*
9021 # uncoverable branch true class:ignore_covered_err
9022 # uncoverable condition left count:1 class:ignore_covered_err
9023 # uncoverable condition left count:2 class:ignore_covered_err */
9024 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
9025 1 hm_loop_run(aTHX_ hm_loop_from_sv(aTHX_ cl->a), ST(0));
9026 1 XSRETURN_EMPTY;
9027 }
9028  
9029 /* A run() option that is a count: a non-negative number, never a string
9030 * that is not one ("10M" read as 10) and never a negative ("-1" read as
9031 * UV_MAX, which for max_body was an unbounded request buffer). */
9032 40 static UV hm_opt_count(pTHX_ SV *val, const char *key) {
9033 /*
9034 # uncoverable condition left count:1 class:ignore_covered_err
9035 # uncoverable condition left count:2 class:ignore_covered_err
9036 # uncoverable condition right count:4 class:ignore_covered_err
9037 # uncoverable condition right count:5 class:ignore_covered_err */
9038 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
9039 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
9040 36 ▶ || SvNV(val) < 0)
Branch: 1 branch
BranchTrueFalseTotal
|| SvNV(val) < 0) 4 32 36
9041 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
9042 key, SvOK(val) ? SvPV_nolen(val) : "undef"); /* # uncoverable condition right count:1 class:ignore_covered_err */
9043 32 return SvUV(val);
9044 }
9045  
9046 #endif /* HM_CORE_H */
« include/hyperman/hm_future.h ↑ Summary include/hyperman/hm_compress.h »