File Coverage

feersum_core.c.inc
Criterion Covered Total %
statement 579 726 79.7
branch 249 378 65.8
condition n/a
subroutine n/a
pod n/a
total 828 1104 75.0


line stmt bran cond sub pod time code
1              
2             INLINE_UNLESS_DEBUG
3             static SV*
4 185           fetch_av_normal (pTHX_ AV *av, I32 i)
5             {
6 185           SV **elt = av_fetch(av, i, 0);
7 185 50         if (elt == NULL) return NULL;
8 185           SV *sv = *elt;
9 185 100         if (unlikely(SvMAGICAL(sv))) sv = sv_2mortal(newSVsv(sv));
10 185 100         if (unlikely(!SvOK(sv))) return NULL;
11             // usually array ref elems aren't RVs (for PSGI anyway)
12 182 100         if (unlikely(SvROK(sv))) sv = SvRV(sv);
13 182           return sv;
14             }
15              
16             INLINE_UNLESS_DEBUG
17             static struct iomatrix *
18 1028           next_iomatrix (struct feer_conn *c)
19             {
20 1028           bool add_iomatrix = 0;
21             struct iomatrix *m;
22              
23 1028 100         if (!c->wbuf_rinq) {
24             trace3("next_iomatrix(%d): head\n", c->fd);
25 787           add_iomatrix = 1;
26             }
27             else {
28             // get the tail-end struct
29 241           m = (struct iomatrix *)c->wbuf_rinq->prev->ref;
30             trace3("next_iomatrix(%d): tail, count=%d, offset=%d\n",
31             c->fd, m->count, m->offset);
32 241 50         if (m->count >= FEERSUM_IOMATRIX_SIZE) {
33 0           add_iomatrix = 1;
34             }
35             }
36              
37 1028 100         if (add_iomatrix) {
38             trace3("next_iomatrix(%d): alloc\n", c->fd);
39 787 100         IOMATRIX_ALLOC(m);
40 787           m->offset = m->count = 0;
41 787           rinq_push(&c->wbuf_rinq, m);
42             }
43              
44             trace3("next_iomatrix(%d): end, count=%d, offset=%d\n",
45             c->fd, m->count, m->offset);
46 1028           return m;
47             }
48              
49             INLINE_UNLESS_DEBUG
50             static STRLEN
51 338           add_sv_to_wbuf(struct feer_conn *c, SV *sv)
52             {
53 338           struct iomatrix *m = next_iomatrix(c);
54 338           unsigned idx = m->count++;
55             STRLEN cur;
56 338 100         if (unlikely(SvMAGICAL(sv))) {
57 1           sv = newSVsv(sv); // copy to force it to be normal.
58             }
59 337 50         else if (unlikely(SvPADTMP(sv))) {
60             // PADTMPs have their PVs re-used, so we can't simply keep a
61             // reference. TEMPs maybe behave in a similar way and are potentially
62             // stealable. If not stealing, we must make a copy.
63             #ifdef FEERSUM_STEAL
64 0 0         if (SvFLAGS(sv) == (SVs_PADTMP|SVf_POK|SVp_POK)) {
65             trace3("STEALING\n");
66 0           SV *thief = newSV(0);
67 0           sv_upgrade(thief, SVt_PV);
68              
69 0           SvPV_set(thief, SvPVX(sv));
70 0           SvLEN_set(thief, SvLEN(sv));
71 0           SvCUR_set(thief, SvCUR(sv));
72              
73             // make the temp null
74 0 0         (void)SvOK_off(sv);
75 0           SvPV_set(sv, NULL);
76 0           SvLEN_set(sv, 0);
77 0           SvCUR_set(sv, 0);
78              
79 0           SvFLAGS(thief) |= SVf_READONLY|SVf_POK|SVp_POK;
80              
81 0           sv = thief;
82             }
83             else {
84 0           sv = newSVsv(sv);
85             }
86             #else
87             sv = newSVsv(sv);
88             #endif
89             }
90             else {
91 337           sv = SvREFCNT_inc(sv);
92             }
93              
94 338           m->iov[idx].iov_base = SvPV(sv, cur);
95 338           m->iov[idx].iov_len = cur;
96 338           m->sv[idx] = sv;
97              
98 338           c->wbuf_len += cur;
99 338           return cur;
100             }
101              
102             INLINE_UNLESS_DEBUG
103             static STRLEN
104 103           add_const_to_wbuf(struct feer_conn *c, const char *str, size_t str_len)
105             {
106 103           struct iomatrix *m = next_iomatrix(c);
107 103           unsigned idx = m->count++;
108 103           m->iov[idx].iov_base = (void*)str;
109 103           m->iov[idx].iov_len = str_len;
110 103           m->sv[idx] = NULL;
111 103           c->wbuf_len += str_len;
112 103           return str_len;
113             }
114              
115             INLINE_UNLESS_DEBUG
116             static void
117 75           add_placeholder_to_wbuf(struct feer_conn *c, SV **sv, struct iovec **iov_ref)
118             {
119 75           struct iomatrix *m = next_iomatrix(c);
120 75           unsigned idx = m->count++;
121 75           *sv = newSV(31);
122 75           SvPOK_on(*sv);
123 75           m->sv[idx] = *sv;
124 75           *iov_ref = &m->iov[idx];
125 75           }
126              
127             INLINE_UNLESS_DEBUG
128             static void
129 59           finish_wbuf(struct feer_conn *c)
130             {
131 59 100         if (!c->use_chunked) return; // nothing required unless chunked encoding
132 40           add_const_to_wbuf(c, "0\r\n\r\n", 5); // terminating chunk
133             }
134              
135             INLINE_UNLESS_DEBUG
136             static void
137 75           update_wbuf_placeholder(struct feer_conn *c, SV *sv, struct iovec *iov)
138             {
139             STRLEN cur;
140             // can't pass iov_len for cur; incompatible pointer type on some systems:
141 75           iov->iov_base = SvPV(sv,cur);
142 75           iov->iov_len = cur;
143 75           c->wbuf_len += cur;
144 75           }
145              
146             static void
147 59           add_chunk_sv_to_wbuf(struct feer_conn *c, SV *sv)
148             {
149             STRLEN len;
150 59           (void)SvPV(sv, len);
151 59 50         if (unlikely(len == 0)) return; /* skip: "0\r\n\r\n" is the terminal chunk */
152              
153             SV *chunk;
154             struct iovec *chunk_iov;
155 59           add_placeholder_to_wbuf(c, &chunk, &chunk_iov);
156 59           STRLEN cur = add_sv_to_wbuf(c, sv);
157 59           add_crlf_to_wbuf(c);
158 59           sv_setpvf(chunk, "%"Sz_xf CRLF, (Sz)cur);
159 59           update_wbuf_placeholder(c, chunk, chunk_iov);
160             }
161              
162             static const char *
163 215           http_code_to_msg (int code) {
164 215           switch (code) {
165 0           case 100: return "Continue";
166 0           case 101: return "Switching Protocols";
167 0           case 102: return "Processing"; // RFC 2518
168 0           case 200: return "OK";
169 0           case 201: return "Created";
170 0           case 202: return "Accepted";
171 0           case 203: return "Non Authoritative Information";
172 0           case 204: return "No Content";
173 0           case 205: return "Reset Content";
174 0           case 206: return "Partial Content";
175 0           case 207: return "Multi-Status"; // RFC 4918 (WebDav)
176 0           case 300: return "Multiple Choices";
177 0           case 301: return "Moved Permanently";
178 0           case 302: return "Found";
179 0           case 303: return "See Other";
180 0           case 304: return "Not Modified";
181 0           case 305: return "Use Proxy";
182 0           case 307: return "Temporary Redirect";
183 160           case 400: return "Bad Request";
184 0           case 401: return "Unauthorized";
185 0           case 402: return "Payment Required";
186 0           case 403: return "Forbidden";
187 0           case 404: return "Not Found";
188 3           case 405: return "Method Not Allowed";
189 0           case 406: return "Not Acceptable";
190 0           case 407: return "Proxy Authentication Required";
191 9           case 408: return "Request Timeout";
192 0           case 409: return "Conflict";
193 0           case 410: return "Gone";
194 4           case 411: return "Length Required";
195 0           case 412: return "Precondition Failed";
196 4           case 413: return "Request Entity Too Large";
197 3           case 414: return "Request URI Too Long";
198 0           case 415: return "Unsupported Media Type";
199 0           case 416: return "Requested Range Not Satisfiable";
200 9           case 417: return "Expectation Failed";
201 0           case 418: return "I'm a teapot";
202 0           case 421: return "Misdirected Request"; // RFC 9110
203 0           case 422: return "Unprocessable Entity"; // RFC 4918
204 0           case 423: return "Locked"; // RFC 4918
205 0           case 424: return "Failed Dependency"; // RFC 4918
206 0           case 425: return "Unordered Collection"; // RFC 3648
207 0           case 426: return "Upgrade Required"; // RFC 2817
208 0           case 429: return "Too Many Requests"; // RFC 6585
209 2           case 431: return "Request Header Fields Too Large"; // RFC 6585
210 0           case 449: return "Retry With"; // Microsoft
211 0           case 450: return "Blocked by Parental Controls"; // Microsoft
212 15           case 500: return "Internal Server Error";
213 6           case 501: return "Not Implemented";
214 0           case 502: return "Bad Gateway";
215 0           case 503: return "Service Unavailable";
216 0           case 504: return "Gateway Timeout";
217 0           case 505: return "HTTP Version Not Supported";
218 0           case 506: return "Variant Also Negotiates"; // RFC 2295
219 0           case 507: return "Insufficient Storage"; // RFC 4918
220 0           case 509: return "Bandwidth Limit Exceeded"; // Apache mod
221 0           case 510: return "Not Extended"; // RFC 2774
222 0           case 530: return "User access denied"; // ??
223 0           default: break;
224             }
225              
226             // default to the Nxx group names in RFC 2616
227 0           switch (code / 100) {
228 0           case 1: return "Informational";
229 0           case 2: return "Success";
230 0           case 3: return "Redirection";
231 0           case 4: return "Client Error";
232 0           default: return "Error";
233             }
234             }
235              
236             static int
237 656           prep_socket(int fd, int is_tcp)
238             {
239             #ifdef HAS_ACCEPT4
240 656           int flags = 1;
241             #else
242             int flags;
243              
244             // make it non-blocking and close-on-exec
245             flags = fcntl(fd, F_GETFL);
246             if (unlikely(flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0))
247             return -1;
248             if (unlikely(fcntl(fd, F_SETFD, FD_CLOEXEC) < 0))
249             return -1;
250              
251             flags = 1;
252             #endif
253 656 50         if (likely(is_tcp)) {
254 656 50         if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, &flags, sizeof(int))))
255 0           return -1;
256             }
257              
258 656           return 0;
259             }
260              
261             // TCP cork/uncork for batching writes (Linux: TCP_CORK, BSD: TCP_NOPUSH)
262             #if defined(TCP_CORK)
263             # define FEERSUM_TCP_CORK TCP_CORK
264             #elif defined(TCP_NOPUSH)
265             # define FEERSUM_TCP_CORK TCP_NOPUSH
266             #endif
267              
268             #ifdef FEERSUM_TCP_CORK
269             INLINE_UNLESS_DEBUG static void
270 6           set_cork(struct feer_conn *c, int cork)
271             {
272 6 50         if (likely(c->cached_is_tcp)) {
273 6           setsockopt(c->fd, SOL_TCP, FEERSUM_TCP_CORK, &cork, sizeof(cork));
274             }
275 6           }
276             #else
277             # define set_cork(c, cork) ((void)0)
278             #endif
279              
280             static void
281 8           invoke_shutdown_cb(pTHX_ struct feer_server *server)
282             {
283 8           dSP;
284 8           SV *cb = server->shutdown_cb_cv;
285 8           server->shutdown_cb_cv = NULL;
286 8           ENTER;
287 8           SAVETMPS;
288 8 50         PUSHMARK(SP);
289 8           PUTBACK;
290 8           call_sv(cb, G_EVAL|G_VOID|G_DISCARD|G_NOARGS);
291 8           SPAGAIN;
292             trace3("called shutdown handler\n");
293 8 50         if (SvTRUE(ERRSV))
    100          
294 1 50         sv_setsv(ERRSV, &PL_sv_undef);
295 8           SvREFCNT_dec(cb);
296 8 50         FREETMPS;
297 8           LEAVE;
298 8           }
299              
300             static void
301 1265           safe_close_conn(struct feer_conn *c, const char *where)
302             {
303 1265 100         if (unlikely(c->fd < 0))
304 609           return;
305              
306             #ifdef FEERSUM_HAS_H2
307             if (c->is_h2_stream) {
308             /* Pseudo-conns share parent's fd — do NOT close or shutdown it.
309             * The parent connection owns the fd and will close it. */
310             c->fd = -1;
311             return;
312             }
313             #endif
314              
315 656 50         CLOSE_SENDFILE_FD(c);
    0          
316              
317             #ifdef FEERSUM_HAS_TLS
318             // Best-effort TLS close_notify before TCP shutdown
319 656 100         if (c->tls && c->tls_handshake_done) {
    100          
320             ptls_buffer_t closebuf;
321 51           ptls_buffer_init(&closebuf, "", 0);
322 51           ptls_send_alert(c->tls, &closebuf, PTLS_ALERT_LEVEL_WARNING, PTLS_ALERT_CLOSE_NOTIFY);
323 51 50         if (closebuf.off > 0) {
324             ssize_t wr PERL_UNUSED_DECL;
325 51           wr = write(c->fd, closebuf.base, closebuf.off);
326             }
327 51           ptls_buffer_dispose(&closebuf);
328             }
329             #endif
330              
331             // Graceful TCP shutdown: send FIN to peer before close
332             // This ensures client sees clean EOF instead of RST
333 656           shutdown(c->fd, SHUT_WR);
334              
335 656 50         if (unlikely(close(c->fd) < 0))
336 0           trouble("close(%s) fd=%d: %s\n", where, c->fd, strerror(errno));
337              
338 656           c->fd = -1;
339             }
340              
341             static struct feer_conn *
342 656           new_feer_conn (EV_P_ int conn_fd, struct sockaddr *sa, socklen_t sa_len,
343             struct feer_server *srvr, struct feer_listen *lsnr)
344             {
345 656           SV *self = newSV(0);
346 656 50         SvUPGRADE(self, SVt_PVMG); // ensures sv_bless doesn't reallocate
347 656 50         SvGROW(self, sizeof(struct feer_conn));
    50          
348 656           SvPOK_only(self);
349 656           SvIOK_on(self);
350 656           SvIV_set(self,conn_fd);
351              
352 656           struct feer_conn *c = (struct feer_conn *)SvPVX(self);
353 656           Zero(c, 1, struct feer_conn);
354              
355 656           c->self = self;
356 656           c->server = srvr;
357 656           c->listener = lsnr;
358 656           SvREFCNT_inc_void_NN(srvr->self); // prevent server GC while conn alive
359              
360             // Cache hot config fields to avoid c->server->/c->listener-> indirection
361 656           c->cached_read_timeout = srvr->read_timeout;
362 656           c->cached_write_timeout = srvr->write_timeout;
363 656           c->cached_max_conn_reqs = srvr->max_connection_reqs;
364 656           c->cached_is_tcp = lsnr->is_tcp;
365 656           c->cached_keepalive_default = srvr->is_keepalive;
366 656           c->cached_use_reverse_proxy = srvr->use_reverse_proxy;
367 656           c->cached_request_cb_is_psgi = srvr->request_cb_is_psgi;
368 656           c->cached_max_read_buf = srvr->max_read_buf;
369 656           c->cached_max_body_len = srvr->max_body_len;
370 656           c->cached_max_uri_len = srvr->max_uri_len;
371 656           c->cached_wbuf_low_water = srvr->wbuf_low_water;
372 656           c->fd = conn_fd;
373 656           memcpy(&c->sa, sa, sa_len); // copy into embedded storage
374 656 100         c->receiving = srvr->use_proxy_protocol ? RECEIVE_PROXY_HEADER : RECEIVE_HEADERS;
375 656           c->sendfile_fd = -1; // no sendfile pending
376              
377             #ifdef FEERSUM_HAS_TLS
378 656 100         if (lsnr->tls_ctx_ref) {
379 68           ev_io_init(&c->read_ev_io, try_tls_conn_read, conn_fd, EV_READ);
380 68           ev_io_init(&c->write_ev_io, try_tls_conn_write, conn_fd, EV_WRITE);
381 68           feer_tls_init_conn(c, lsnr->tls_ctx_ref);
382             } else
383             #endif
384             {
385 588           ev_io_init(&c->read_ev_io, try_conn_read, conn_fd, EV_READ);
386 588           ev_io_init(&c->write_ev_io, try_conn_write, conn_fd, EV_WRITE);
387             }
388 656           ev_set_priority(&c->read_ev_io, srvr->read_priority);
389 656           c->read_ev_io.data = (void *)c;
390              
391 656           ev_set_priority(&c->write_ev_io, srvr->write_priority);
392 656           c->write_ev_io.data = (void *)c;
393              
394 656           ev_init(&c->read_ev_timer, conn_read_timeout);
395 656           ev_set_priority(&c->read_ev_timer, srvr->read_priority);
396 656           c->read_ev_timer.data = (void *)c;
397              
398             // Slowloris protection: header deadline timer (non-resetting)
399 656           ev_init(&c->header_ev_timer, conn_header_timeout);
400 656           ev_set_priority(&c->header_ev_timer, srvr->read_priority);
401 656           c->header_ev_timer.data = (void *)c;
402              
403 656           ev_init(&c->write_ev_timer, conn_write_timeout);
404 656           ev_set_priority(&c->write_ev_timer, srvr->write_priority);
405 656           c->write_ev_timer.data = (void *)c;
406              
407             trace3("made conn fd=%d self=%p, c=%p, cur=%"Sz_uf", len=%"Sz_uf"\n",
408             c->fd, self, c, (Sz)SvCUR(self), (Sz)SvLEN(self));
409              
410             if (FEERSUM_CONN_NEW_ENABLED()) {
411             feersum_set_conn_remote_info(aTHX_ c);
412             FEERSUM_CONN_NEW(c->fd, SvPV_nolen(c->remote_addr), (int)SvIV(c->remote_port));
413             }
414              
415 656           SV *rv = newRV_inc(c->self);
416 656           sv_bless(rv, feer_conn_stash); // so DESTROY can get called on read errors
417 656           SvREFCNT_dec(rv);
418              
419 656           SvREADONLY_on(self);
420 656           srvr->active_conns++;
421 656           return c;
422             }
423              
424             INLINE_UNLESS_DEBUG
425             static struct feer_conn *
426 1530           sv_2feer_conn (SV *rv)
427             {
428 1530 50         if (unlikely(!sv_isa(rv,"Feersum::Connection")))
429 0           croak("object is not of type Feersum::Connection");
430 1530           return (struct feer_conn *)SvPVX(SvRV(rv));
431             }
432              
433             INLINE_UNLESS_DEBUG
434             static SV*
435 565           feer_conn_2sv (struct feer_conn *c)
436             {
437 565           return newRV_inc(c->self);
438             }
439              
440             static feer_conn_handle *
441 670           sv_2feer_conn_handle (SV *rv, bool can_croak)
442             {
443             trace3("sv 2 conn_handle\n");
444 670 50         if (unlikely(!SvROK(rv))) croak("Expected a reference");
445             // do not allow subclassing
446 670           SV *sv = SvRV(rv);
447 670 50         if (likely(
    100          
    50          
    50          
448             sv_isobject(rv) &&
449             (SvSTASH(sv) == feer_conn_writer_stash ||
450             SvSTASH(sv) == feer_conn_reader_stash)
451             )) {
452 670           UV uv = SvUV(sv);
453 670 100         if (uv == 0) {
454 87 100         if (can_croak) croak("Operation not allowed: Handle is closed.");
455 72           return NULL;
456             }
457 583           return INT2PTR(feer_conn_handle*,uv);
458             }
459              
460 0 0         if (can_croak)
461 0           croak("Expected a Feersum::Connection::Writer or ::Reader object");
462 0           return NULL;
463             }
464              
465             static SV *
466 388           new_feer_conn_handle (pTHX_ struct feer_conn *c, bool is_writer)
467             {
468             SV *sv;
469 388           SvREFCNT_inc_void_NN(c->self);
470 388           sv = newRV_noinc(newSVuv(PTR2UV(c)));
471 388 100         sv_bless(sv, is_writer ? feer_conn_writer_stash : feer_conn_reader_stash);
472 388           return sv;
473             }
474              
475             static void
476 214           init_feer_server (struct feer_server *s)
477             {
478 214           Zero(s, 1, struct feer_server);
479 214           s->read_timeout = READ_TIMEOUT;
480 214           s->header_timeout = HEADER_TIMEOUT;
481 214           s->write_timeout = WRITE_TIMEOUT;
482 214           s->max_accept_per_loop = DEFAULT_MAX_ACCEPT_PER_LOOP;
483 214           s->max_connections = 10000;
484 214           s->max_read_buf = MAX_READ_BUF;
485 214           s->max_body_len = MAX_BODY_LEN;
486 214           s->max_uri_len = MAX_URI_LEN;
487 214           s->psgix_io = true;
488             #ifdef FEERSUM_HAS_H2
489             s->max_h2_concurrent_streams = FEER_H2_MAX_CONCURRENT_STREAMS;
490             #endif
491 3638 100         for (int i = 0; i < FEER_MAX_LISTENERS; i++) {
492 3424           s->listeners[i].fd = -1;
493 3424           s->listeners[i].server = s;
494             #ifdef __linux__
495 3424           s->listeners[i].epoll_fd = -1;
496             #endif
497             }
498 214           }
499              
500             static struct feer_server *
501 214           new_feer_server (pTHX)
502             {
503 214           SV *self = newSV(0);
504 214 50         SvUPGRADE(self, SVt_PVMG);
505 214 50         SvGROW(self, sizeof(struct feer_server));
    50          
506 214           SvPOK_only(self);
507 214           SvIOK_on(self);
508              
509 214           struct feer_server *s = (struct feer_server *)SvPVX(self);
510 214           init_feer_server(s);
511 214           s->self = self;
512              
513 214           SV *rv = newRV_inc(self);
514 214           sv_bless(rv, feer_stash);
515 214           SvREFCNT_dec(rv);
516              
517 214           SvREADONLY_on(self);
518 214           return s;
519             }
520              
521             INLINE_UNLESS_DEBUG
522             static struct feer_server *
523 27494           sv_2feer_server (SV *rv)
524             {
525             // Accept both instance ($obj->method) and class (Feersum->method) calls
526 27494 100         if (sv_isa(rv, "Feersum")) {
527 27461           return (struct feer_server *)SvPVX(SvRV(rv));
528             }
529             // Class method call: "Feersum"->method() - return default server
530 33 50         if (SvPOK(rv) && strEQ(SvPV_nolen(rv), "Feersum")) {
    50          
531 33 50         if (unlikely(!default_server))
532 0           croak("Feersum: no server instance (call Feersum->new first)");
533 33           return default_server;
534             }
535 0           croak("object is not of type Feersum");
536             return NULL; // unreachable
537             }
538              
539             INLINE_UNLESS_DEBUG
540             static SV*
541 201           feer_server_2sv (struct feer_server *s)
542             {
543 201           return newRV_inc(s->self);
544             }
545              
546             INLINE_UNLESS_DEBUG static void
547 156           start_read_watcher(struct feer_conn *c) {
548             ASSERT_EV_LOOP_INITIALIZED();
549 156 100         if (unlikely(ev_is_active(&c->read_ev_io)))
550 12           return;
551             trace("start read watcher %d\n",c->fd);
552 144           ev_io_start(feersum_ev_loop, &c->read_ev_io);
553 144           SvREFCNT_inc_void_NN(c->self);
554             }
555              
556             INLINE_UNLESS_DEBUG static void
557 1018           stop_read_watcher(struct feer_conn *c) {
558 1018 100         if (unlikely(!ev_is_active(&c->read_ev_io)))
559 884           return;
560             trace("stop read watcher %d\n",c->fd);
561 134           ev_io_stop(feersum_ev_loop, &c->read_ev_io);
562 134           SvREFCNT_dec(c->self);
563             }
564              
565             INLINE_UNLESS_DEBUG static void
566 140           restart_read_timer(struct feer_conn *c) {
567 140 100         if (likely(!ev_is_active(&c->read_ev_timer))) {
568             trace("restart read timer %d\n",c->fd);
569 119           c->read_ev_timer.repeat = c->cached_read_timeout;
570 119           SvREFCNT_inc_void_NN(c->self);
571             }
572 140           ev_timer_again(feersum_ev_loop, &c->read_ev_timer);
573 140           }
574              
575             INLINE_UNLESS_DEBUG static void
576 1027           stop_read_timer(struct feer_conn *c) {
577 1027 100         if (unlikely(!ev_is_active(&c->read_ev_timer)))
578 913           return;
579             trace("stop read timer %d\n",c->fd);
580 114           ev_timer_stop(feersum_ev_loop, &c->read_ev_timer);
581 114           SvREFCNT_dec(c->self);
582             }
583              
584             INLINE_UNLESS_DEBUG static void
585 647           start_write_watcher(struct feer_conn *c) {
586             ASSERT_EV_LOOP_INITIALIZED();
587 647 100         if (unlikely(ev_is_active(&c->write_ev_io)))
588 121           return;
589             trace("start write watcher %d\n",c->fd);
590 526           ev_io_start(feersum_ev_loop, &c->write_ev_io);
591 526           SvREFCNT_inc_void_NN(c->self);
592             }
593              
594             INLINE_UNLESS_DEBUG static void
595 815           stop_write_watcher(struct feer_conn *c) {
596 815 100         if (unlikely(!ev_is_active(&c->write_ev_io)))
597 289           return;
598             trace("stop write watcher %d\n",c->fd);
599 526           ev_io_stop(feersum_ev_loop, &c->write_ev_io);
600 526           SvREFCNT_dec(c->self);
601             }
602              
603             INLINE_UNLESS_DEBUG static void
604 784           restart_write_timer(struct feer_conn *c) {
605 784 100         if (c->cached_write_timeout <= 0.0) return;
606 1 50         if (likely(!ev_is_active(&c->write_ev_timer))) {
607             trace("restart write timer %d\n",c->fd);
608 1           c->write_ev_timer.repeat = c->cached_write_timeout;
609 1           SvREFCNT_inc_void_NN(c->self);
610             }
611 1           ev_timer_again(feersum_ev_loop, &c->write_ev_timer);
612             }
613              
614             INLINE_UNLESS_DEBUG static void
615 836           stop_write_timer(struct feer_conn *c) {
616 836 100         if (unlikely(!ev_is_active(&c->write_ev_timer)))
617 835           return;
618             trace("stop write timer %d\n",c->fd);
619 1           ev_timer_stop(feersum_ev_loop, &c->write_ev_timer);
620 1           SvREFCNT_dec(c->self);
621             }
622              
623             INLINE_UNLESS_DEBUG static void
624 1778           stop_header_timer(struct feer_conn *c) {
625 1778 100         if (unlikely(!ev_is_active(&c->header_ev_timer)))
626 996           return;
627             trace("stop header timer %d\n", c->fd);
628 782           ev_timer_stop(feersum_ev_loop, &c->header_ev_timer);
629 782           SvREFCNT_dec(c->self);
630             }
631              
632             INLINE_UNLESS_DEBUG static void
633 145           restart_header_timer(struct feer_conn *c) {
634 145           double timeout = c->server->header_timeout;
635 145 50         if (timeout <= 0.0) return;
636 145           stop_header_timer(c);
637 145           ev_timer_set(&c->header_ev_timer, timeout, 0.0);
638 145           ev_timer_start(feersum_ev_loop, &c->header_ev_timer);
639 145           SvREFCNT_inc_void_NN(c->self);
640             }
641              
642             INLINE_UNLESS_DEBUG static void
643 52           stop_all_watchers(struct feer_conn *c) {
644 52           stop_read_watcher(c);
645 52           stop_read_timer(c);
646 52           stop_header_timer(c);
647 52           stop_write_watcher(c);
648 52           stop_write_timer(c);
649 52           }
650              
651             /* Common shutdown sequence: stop watchers, close fd, mark for cleanup.
652             * Used by error/EOF/timeout paths across H1, H2, and TLS code. */
653             INLINE_UNLESS_DEBUG static void
654 13           feer_shutdown_conn(struct feer_conn *c, const char *where) {
655 13           stop_all_watchers(c);
656 13           safe_close_conn(c, where);
657 13           change_responding_state(c, RESPOND_SHUTDOWN);
658 13           }
659              
660             static void
661 1752           feer_conn_set_busy(struct feer_conn *c)
662             {
663 1752 100         if (c->idle_rinq_node) {
664 34           rinq_remove(&c->server->idle_keepalive_rinq, c->idle_rinq_node);
665 34           c->idle_rinq_node = NULL;
666             }
667 1752           }
668              
669             static void
670 36           feer_conn_set_idle(struct feer_conn *c)
671             {
672 36 50         if (c->idle_rinq_node) return; // already idle
673              
674 36           c->idle_rinq_node = rinq_push(&c->server->idle_keepalive_rinq, c);
675             trace("conn fd=%d is now idle (added to MRU)\n", c->fd);
676             }
677              
678             static int
679 11           feer_server_recycle_idle_conn(struct feer_server *srvr)
680             {
681 11 100         if (!srvr->idle_keepalive_rinq) return 0;
682              
683 2           struct feer_conn *c = (struct feer_conn *)rinq_shift(&srvr->idle_keepalive_rinq);
684 2 50         if (unlikely(!c)) return 0;
685              
686 2           c->idle_rinq_node = NULL; // node was shifted
687              
688             trace("recycling idle keepalive conn fd=%d to make room for new accept\n", c->fd);
689              
690             // Gracefully shut down the idle connection.
691             // Guard: after setup_accepted_conn drops the base refcount, connections
692             // are alive only via watcher refcounts. stop_all_watchers can drop
693             // refcount to 0 → DESTROY fires before safe_close_conn.
694 2           SvREFCNT_inc_void_NN(c->self);
695 2           feer_shutdown_conn(c, "recycled for new connection");
696 2           SvREFCNT_dec(c->self);
697              
698             // active_conns will be decremented in DESTROY when refcount drops.
699 2           return 1;
700             }
701              
702              
703             static void
704 385           process_request_ready_rinq (struct feer_server *server)
705             {
706 933 100         while (server->request_ready_rinq) {
707             struct feer_conn *c =
708 548           (struct feer_conn *)rinq_shift(&server->request_ready_rinq);
709 548 50         if (unlikely(!c)) break;
710              
711 548           call_request_callback(c);
712              
713 548 100         if (likely(c->wbuf_rinq)) {
714             // this was deferred until after the perl callback
715 520           conn_write_ready(c);
716             }
717             #ifdef FEERSUM_HAS_H2
718             else if (c->is_h2_stream) {
719             // H2 pseudo-conns don't use wbuf_rinq; flush deferred session_send
720             dTHX;
721             struct feer_h2_stream *stream = H2_STREAM_FROM_PC(c);
722             if (stream && stream->parent)
723             h2_session_send_and_poll(aTHX_ stream->parent);
724             }
725             #endif
726 548           SvREFCNT_dec(c->self); // for the rinq
727             }
728 385           }
729              
730             static void
731 160           prepare_cb (EV_P_ ev_prepare *w, int revents)
732             {
733 160           struct feer_server *srvr = (struct feer_server *)w->data;
734              
735 160 50         if (unlikely(revents & EV_ERROR)) {
736 0           trouble("EV error in prepare, revents=0x%08x\n", revents);
737 0           ev_break(EV_A, EVBREAK_ALL);
738 0           return;
739             }
740              
741 160 100         if (!srvr->shutting_down) {
742 403 100         for (int i = 0; i < srvr->n_listeners; i++) {
743 245           struct feer_listen *lsnr = &srvr->listeners[i];
744 245 100         if (!ev_is_active(&lsnr->accept_w) && !lsnr->pause_flags) {
    50          
745 166           ev_io_start(EV_A, &lsnr->accept_w);
746             }
747             }
748             }
749 160           ev_prepare_stop(EV_A, w);
750             }
751              
752             static void
753 5085           check_cb (EV_P_ ev_check *w, int revents)
754             {
755 5085           struct feer_server *server = (struct feer_server *)w->data;
756              
757 5085 50         if (unlikely(revents & EV_ERROR)) {
758 0           trouble("EV error in check, revents=0x%08x\n", revents);
759 0           ev_break(EV_A, EVBREAK_ALL);
760 0           return;
761             }
762              
763             trace3("check! head=%p\n", server->request_ready_rinq);
764 5085 100         if (server->request_ready_rinq)
765 385           process_request_ready_rinq(server);
766             }
767              
768             static void
769 382           idle_cb (EV_P_ ev_idle *w, int revents)
770             {
771 382           struct feer_server *server = (struct feer_server *)w->data;
772              
773             trace("idle_cb called, revents=0x%08x\n", revents);
774 382 50         if (unlikely(revents & EV_ERROR)) {
775 0           trouble("EV error in idle, revents=0x%08x\n", revents);
776 0           ev_break(EV_A, EVBREAK_ALL);
777 0           return;
778             }
779             trace3("idle! head=%p\n", server->request_ready_rinq);
780 382 50         if (server->request_ready_rinq)
781 0           process_request_ready_rinq(server);
782 382           ev_idle_stop(EV_A, w);
783             }
784              
785             /*
786             * Shared keepalive-or-close logic for both plain and TLS write paths.
787             * read_cb is try_conn_read (plain) or try_tls_conn_read (TLS).
788             */
789             static void
790 727           handle_keepalive_or_close(struct feer_conn *c, conn_read_cb_t read_cb)
791             {
792 727           stop_write_watcher(c);
793 727           stop_write_timer(c);
794              
795             if (FEERSUM_RESP_DONE_ENABLED()) {
796             FEERSUM_RESP_DONE(c->fd, 0);
797             }
798              
799             /* If the request had a body the app didn't fully consume, strip the
800             * remaining body bytes from rbuf so they don't get parsed as the next
801             * HTTP request. Any pipelined data after the body is preserved.
802             *
803             * For Content-Length bodies: rbuf starts with body data (headers already
804             * stripped by picohttpparser). consumed = bytes the app read via
805             * $input->read (which does sv_chop). remaining = body bytes still at
806             * the start of rbuf.
807             *
808             * For chunked bodies: the chunked parser decoded in-place. rbuf has
809             * decoded body (received_cl bytes) followed by any pipelined data.
810             * consumed works the same way (sv_chop by $input->read). */
811 727 100         if (c->is_keepalive && c->rbuf) {
    100          
812             /* expected_cl is set by both Content-Length and chunked paths
813             * (try_parse_chunked sets expected_cl = decoded body size). */
814 136           ssize_t body_total = (c->expected_cl > 0) ? c->expected_cl : 0;
815 136 100         if (body_total > 0) {
816 14           ssize_t consumed = c->received_cl - (ssize_t)SvCUR(c->rbuf);
817 14           ssize_t remaining = body_total - consumed;
818 14 100         if (remaining > 0 && remaining <= (ssize_t)SvCUR(c->rbuf)) {
    50          
819 5           sv_chop(c->rbuf, SvPVX(c->rbuf) + remaining);
820             trace("drained body fd=%d stripped=%"Ssz_df" pipeline=%"Sz_uf"\n",
821             c->fd, (Ssz)remaining, (Sz)SvCUR(c->rbuf));
822             }
823             }
824             }
825              
826 727 100         if (c->is_keepalive) {
827 142           change_responding_state(c, RESPOND_NOT_STARTED);
828 142           change_receiving_state(c, RECEIVE_WAIT);
829 142           STRLEN pipelined = 0;
830 142 100         if (c->rbuf) { pipelined = SvCUR(c->rbuf); }
831 142 50         if (likely(c->req)) {
832 172 100         if (likely(pipelined == 0) && c->req->buf && c->rbuf) {
    50          
    100          
833 30           SV *tmp = c->rbuf;
834 30           c->rbuf = c->req->buf;
835 30           c->req->buf = NULL;
836 30           SvCUR_set(c->rbuf, 0);
837             // Shrink oversized buffers from large bodies to avoid
838             // holding max_body_len per keepalive connection
839 30 50         if (SvLEN(c->rbuf) > READ_BUFSZ * 4)
840 0           SvPV_renew(c->rbuf, READ_BUFSZ + 1);
841 30           SvREFCNT_dec(tmp);
842 112 50         } else if (c->req->buf) {
843 112           SvREFCNT_dec(c->req->buf);
844 112           c->req->buf = NULL;
845             }
846 142           free_request(c);
847             }
848 142 100         if (unlikely(pipelined > 0 && c->is_http11)) {
    50          
849 106           c->pipelined = pipelined;
850 106 50         if (c->pipeline_depth <= MAX_PIPELINE_DEPTH) {
851 106           c->pipeline_depth++;
852 106           restart_header_timer(c);
853 106           read_cb(feersum_ev_loop, &c->read_ev_io, 0);
854 106           c->pipeline_depth--;
855 106           return;
856             }
857             trace("pipeline depth limit reached on %d\n", c->fd);
858             } else {
859 36           c->pipelined = 0;
860             }
861 36           start_read_watcher(c);
862 36           restart_read_timer(c);
863 36           restart_header_timer(c);
864 36           feer_conn_set_idle(c);
865             } else {
866 585 50         if (c->responding != RESPOND_SHUTDOWN)
867 0           change_responding_state(c, RESPOND_SHUTDOWN);
868 585           safe_close_conn(c, "close at write shutdown");
869             }
870             }
871              
872             static void
873 727           try_conn_write(EV_P_ struct ev_io *w, int revents)
874             {
875 727           dCONN;
876             unsigned i;
877             struct iomatrix *m;
878              
879 727           SvREFCNT_inc_void_NN(c->self);
880              
881             // if it's marked writeable EV suggests we simply try write to it.
882             // Otherwise it is stopped and we should ditch this connection.
883 727 50         if (unlikely(revents & EV_ERROR && !(revents & EV_WRITE))) {
    0          
884             trace("EV error on write, fd=%d revents=0x%08x\n", w->fd, revents);
885 0           change_responding_state(c, RESPOND_SHUTDOWN);
886 0           goto try_write_finished;
887             }
888              
889 727 100         if (unlikely(!c->wbuf_rinq)) {
890 23 100         if (unlikely(c->responding >= RESPOND_SHUTDOWN))
891 3           goto try_write_finished;
892              
893             #ifdef __linux__
894             // Check for sendfile pending (headers already sent)
895 20 50         if (c->sendfile_fd >= 0)
896 0           goto try_sendfile;
897             #endif
898              
899 20 50         if (!c->poll_write_cb) {
900             // no callback and no data: wait for app to push to us.
901 0 0         if (c->responding == RESPOND_STREAMING)
902 0           goto try_write_paused;
903              
904             trace("tried to write with an empty buffer %d resp=%d\n",w->fd,c->responding);
905 0           change_responding_state(c, RESPOND_SHUTDOWN);
906 0           goto try_write_finished;
907             }
908              
909 20 100         if (c->poll_write_cb_is_io_handle)
910 11           pump_io_handle(c);
911             else
912 9           call_poll_callback(c, 1);
913              
914             // callback didn't write anything:
915 20 50         if (unlikely(!c->wbuf_rinq)) goto try_write_again;
916             }
917             // Low-water-mark: buffer not empty but below threshold — refill before writing
918 704 100         else if (c->cached_wbuf_low_water > 0
919 1 50         && c->wbuf_len <= c->cached_wbuf_low_water
920 1 50         && c->responding == RESPOND_STREAMING && c->poll_write_cb) {
    50          
921 1 50         if (c->poll_write_cb_is_io_handle)
922 0           pump_io_handle(c);
923             else
924 1           call_poll_callback(c, 1);
925             }
926              
927 724           try_write_again_immediately:
928             #if defined(__linux__) && defined(FEERSUM_TCP_CORK)
929             // Cork socket when writing headers before sendfile for optimal packet framing
930 724 100         if (c->sendfile_fd >= 0)
931 3           set_cork(c, 1);
932             #endif
933 724           m = (struct iomatrix *)c->wbuf_rinq->ref;
934             #if DEBUG >= 2
935             warn("going to write to %d:\n",c->fd);
936             for (i=0; i < m->count; i++) {
937             fprintf(stderr,"%.*s",
938             (int)m->iov[i].iov_len, (char*)m->iov[i].iov_base);
939             }
940             #endif
941              
942             trace("going to write %d off=%d count=%d\n", w->fd, m->offset, m->count);
943 724           errno = 0;
944 724           int iov_count = m->count - m->offset;
945             #ifdef IOV_MAX
946 724 50         if (iov_count > IOV_MAX) iov_count = IOV_MAX;
947             #endif
948             ssize_t wrote;
949 724 100         if (iov_count == 1) {
950             // Single element: write() is slightly faster than writev()
951 647           wrote = write(w->fd, m->iov[m->offset].iov_base, m->iov[m->offset].iov_len);
952             } else {
953 77           wrote = writev(w->fd, &m->iov[m->offset], iov_count);
954             }
955             trace("wrote %"Ssz_df" bytes to %d, errno=%d\n", (Ssz)wrote, w->fd, errno);
956              
957 724 50         if (unlikely(wrote <= 0)) {
958 0 0         if (likely(errno == EAGAIN || errno == EINTR))
    0          
959 0           goto try_write_again;
960 0           trouble("try_conn_write fd=%d: %s\n", w->fd, strerror(errno));
961 0 0         CLOSE_SENDFILE_FD(c);
    0          
962 0           set_cork(c, 0);
963 0           stop_write_timer(c);
964 0           change_responding_state(c, RESPOND_SHUTDOWN);
965 0           goto try_write_finished;
966             }
967              
968 724           c->wbuf_len -= wrote;
969 724           restart_write_timer(c);
970              
971 724           bool consume = 1;
972 1687 100         for (i = m->offset; i < m->count && consume; i++) {
    50          
973 963           struct iovec *v = &m->iov[i];
974 963 50         if (unlikely(v->iov_len > wrote)) {
975             trace3("offset vector %d base=%p len=%"Sz_uf"\n",
976             w->fd, v->iov_base, (Sz)v->iov_len);
977 0           v->iov_base = (char*)v->iov_base + wrote;
978 0           v->iov_len -= wrote;
979             // don't consume any more:
980 0           consume = 0;
981             }
982             else {
983             trace3("consume vector %d base=%p len=%"Sz_uf" sv=%p\n",
984             w->fd, v->iov_base, (Sz)v->iov_len, m->sv[i]);
985 963           wrote -= v->iov_len;
986 963           m->offset++;
987 963 100         if (m->sv[i]) {
988 860           SvREFCNT_dec(m->sv[i]);
989 860           m->sv[i] = NULL;
990             }
991             }
992             }
993              
994 724 50         if (likely(m->offset >= m->count)) {
995             trace2("all done with iomatrix %d state=%d\n",w->fd,c->responding);
996 724           rinq_shift(&c->wbuf_rinq);
997 724 50         IOMATRIX_FREE(m);
998 724 50         if (!c->wbuf_rinq) {
999             #ifdef __linux__
1000             // sendfile pending? do zero-copy file transfer
1001 724 100         if (c->sendfile_fd >= 0)
1002 3           goto try_sendfile;
1003             #endif
1004 721           goto try_write_finished;
1005             }
1006             // Low-water-mark: yield to event loop so poll_cb can fire
1007 0 0         if (c->cached_wbuf_low_water > 0
1008 0 0         && c->wbuf_len <= c->cached_wbuf_low_water
1009 0 0         && c->responding == RESPOND_STREAMING && c->poll_write_cb) {
    0          
1010 0           goto try_write_again;
1011             }
1012             trace2("write again immediately %d state=%d\n",w->fd,c->responding);
1013 0           goto try_write_again_immediately;
1014             }
1015             // else, fallthrough:
1016             trace2("write fallthrough %d state=%d\n",w->fd,c->responding);
1017 0           goto try_write_again;
1018              
1019             #ifdef __linux__
1020 3           try_sendfile:
1021             {
1022             trace("sendfile %d: fd=%d off=%ld remain=%zu\n",
1023             w->fd, c->sendfile_fd, (long)c->sendfile_off, c->sendfile_remain);
1024 3           ssize_t sent = sendfile(w->fd, c->sendfile_fd,
1025 3           &c->sendfile_off, c->sendfile_remain);
1026 3 50         if (sent > 0) {
1027 3           c->sendfile_remain -= sent;
1028             trace("sendfile sent %zd, remain=%zu\n", sent, c->sendfile_remain);
1029 3 50         if (c->sendfile_remain == 0) {
1030 3 50         CLOSE_SENDFILE_FD(c);
    50          
1031 3           set_cork(c, 0);
1032 3           change_responding_state(c, RESPOND_SHUTDOWN);
1033 3           goto try_write_finished;
1034             }
1035             // More to send, wait for socket to be writable again
1036 0           goto try_write_again;
1037             }
1038 0 0         else if (sent == 0) {
1039             // EOF on file (shouldn't happen if sendfile_remain was correct)
1040 0 0         CLOSE_SENDFILE_FD(c);
    0          
1041 0           set_cork(c, 0);
1042 0 0         if (c->responding == RESPOND_STREAMING) {
1043 0           change_responding_state(c, RESPOND_SHUTDOWN);
1044             }
1045 0           goto try_write_finished;
1046             }
1047             else {
1048             // sent < 0, error
1049 0 0         if (errno == EAGAIN || errno == EINTR) {
    0          
1050             // Socket not ready, wait
1051 0           goto try_write_again;
1052             }
1053             // Real error
1054 0           trouble("sendfile fd=%d: %s\n", c->fd, strerror(errno));
1055 0 0         CLOSE_SENDFILE_FD(c);
    0          
1056 0           set_cork(c, 0);
1057 0           change_responding_state(c, RESPOND_SHUTDOWN);
1058 0           goto try_write_finished;
1059             }
1060             }
1061             #endif
1062              
1063 14           try_write_again:
1064             trace("write again %d state=%d\n",w->fd,c->responding);
1065 14           start_write_watcher(c);
1066 14           goto try_write_cleanup;
1067              
1068 727           try_write_finished:
1069             // should always be responding, but just in case
1070 727           switch(c->responding) {
1071 0           case RESPOND_NOT_STARTED:
1072             // the write watcher shouldn't ever get called before starting to
1073             // respond. Shut it down if it does.
1074             trace("unexpected try_write when response not started %d\n",c->fd);
1075 0           goto try_write_shutdown;
1076 0           case RESPOND_NORMAL:
1077 0           goto try_write_shutdown;
1078 50           case RESPOND_STREAMING:
1079 50 100         if (c->poll_write_cb) goto try_write_again;
1080 36           else goto try_write_paused;
1081 677           case RESPOND_SHUTDOWN:
1082 677           goto try_write_shutdown;
1083 0           default:
1084 0           goto try_write_cleanup;
1085             }
1086              
1087 36           try_write_paused:
1088             trace3("write PAUSED %d, refcnt=%d, state=%d\n", c->fd, SvREFCNT(c->self), c->responding);
1089 36           stop_write_watcher(c);
1090 36           stop_write_timer(c);
1091 36           goto try_write_cleanup;
1092              
1093 677           try_write_shutdown:
1094 677           handle_keepalive_or_close(c, try_conn_read);
1095              
1096 727           try_write_cleanup:
1097 727           SvREFCNT_dec(c->self);
1098 727           return;
1099             }
1100              
1101             // Parse PROXY protocol v1 text header
1102             // Format: "PROXY TCP4|TCP6|UNKNOWN src_addr dst_addr src_port dst_port\r\n"
1103             // Returns: bytes consumed on success, -1 on error, -2 if need more data
1104             static int
1105 154           parse_proxy_v1(struct feer_conn *c)
1106             {
1107 154           char *buf = SvPVX(c->rbuf);
1108 154           STRLEN len = SvCUR(c->rbuf);
1109              
1110             // Need at least "PROXY \r\n" (minimum valid line)
1111 154 100         if (len < 8)
1112 21           return -2; // need more data
1113              
1114             // Verify prefix
1115 133 50         if (memcmp(buf, PROXY_V1_PREFIX, PROXY_V1_PREFIX_LEN) != 0)
1116 0           return -1; // invalid
1117              
1118             // Find CRLF (max 108 bytes total)
1119 133           char *crlf = NULL;
1120 133           STRLEN search_len = len > PROXY_V1_MAX_LINE ? PROXY_V1_MAX_LINE : len;
1121 3052 100         for (STRLEN i = PROXY_V1_PREFIX_LEN; i < search_len - 1; i++) {
1122 2949 100         if (buf[i] == '\r' && buf[i+1] == '\n') {
    50          
1123 30           crlf = buf + i;
1124 30           break;
1125             }
1126             }
1127              
1128 133 100         if (!crlf) {
1129 103 100         if (len >= PROXY_V1_MAX_LINE)
1130 1           return -1; // line too long, invalid
1131 102           return -2; // need more data
1132             }
1133              
1134 30           size_t header_len = (crlf - buf) + 2; // include CRLF
1135              
1136             // Null-terminate the line for parsing (temporarily)
1137 30           char saved = *crlf;
1138 30           *crlf = '\0';
1139              
1140             // Parse protocol family: TCP4, TCP6, or UNKNOWN
1141 30           char *p = buf + PROXY_V1_PREFIX_LEN;
1142              
1143 30 100         if (strncmp(p, "UNKNOWN", 7) == 0 && (p[7] == '\0' || p[7] == ' ')) {
    50          
    0          
1144             // UNKNOWN - keep original address (used for health checks)
1145 1           *crlf = saved;
1146 1           c->proxy_proto_version = 1;
1147             trace("PROXY v1 UNKNOWN, keeping original address\n");
1148 1           return (int)header_len;
1149             }
1150              
1151 29           int is_ipv6 = 0;
1152 29 100         if (strncmp(p, "TCP4 ", 5) == 0) {
1153 26           p += 5;
1154 3 100         } else if (strncmp(p, "TCP6 ", 5) == 0) {
1155 2           p += 5;
1156 2           is_ipv6 = 1;
1157             } else {
1158 1           *crlf = saved;
1159 1           return -1; // unknown protocol
1160             }
1161              
1162             // Parse: src_addr dst_addr src_port dst_port
1163             char src_addr[46], dst_addr[46]; // max IPv6 length
1164             int src_port, dst_port;
1165              
1166             // Use sscanf to parse the addresses and ports
1167 28 50         if (sscanf(p, "%45s %45s %d %d", src_addr, dst_addr, &src_port, &dst_port) != 4) {
1168 0           *crlf = saved;
1169 0           return -1; // parse error
1170             }
1171              
1172             // Validate port ranges
1173 28 50         if (src_port < 0 || src_port > 65535 || dst_port < 0 || dst_port > 65535) {
    100          
    50          
    50          
1174 1           *crlf = saved;
1175 1           return -1;
1176             }
1177              
1178 27           *crlf = saved; // restore
1179              
1180             // Update connection's source address
1181 27 100         if (is_ipv6) {
1182 2           struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&c->sa;
1183 2           sa6->sin6_family = AF_INET6;
1184 2 50         if (inet_pton(AF_INET6, src_addr, &sa6->sin6_addr) != 1) {
1185 0           return -1; // invalid address
1186             }
1187 2           sa6->sin6_port = htons((uint16_t)src_port);
1188             } else {
1189 25           struct sockaddr_in *sa4 = (struct sockaddr_in *)&c->sa;
1190 25           sa4->sin_family = AF_INET;
1191 25 100         if (inet_pton(AF_INET, src_addr, &sa4->sin_addr) != 1) {
1192 1           return -1; // invalid address
1193             }
1194 24           sa4->sin_port = htons((uint16_t)src_port);
1195             }
1196              
1197 26           c->proxy_proto_version = 1;
1198 26           c->proxy_dst_port = (uint16_t)dst_port;
1199             trace("PROXY v1 %s src=%s:%d dst_port=%d\n", is_ipv6 ? "TCP6" : "TCP4", src_addr, src_port, dst_port);
1200 26           return (int)header_len;
1201             }
1202              
1203             // Parse PROXY protocol v2 binary header
1204             // Returns: bytes consumed on success, -1 on error, -2 if need more data
1205             static int
1206 113           parse_proxy_v2(struct feer_conn *c)
1207             {
1208 113           unsigned char *buf = (unsigned char *)SvPVX(c->rbuf);
1209 113           STRLEN len = SvCUR(c->rbuf);
1210              
1211             // Need at least minimum header (16 bytes)
1212 113 100         if (len < PROXY_V2_HDR_MIN)
1213 3           return -2;
1214              
1215             // Verify signature
1216 110 100         if (memcmp(buf, PROXY_V2_SIG, PROXY_V2_SIG_LEN) != 0)
1217 20           return -1;
1218              
1219             // Parse version and command (byte 12)
1220 90           unsigned char ver_cmd = buf[12];
1221 90           unsigned char version = ver_cmd & 0xF0;
1222 90           unsigned char command = ver_cmd & 0x0F;
1223              
1224 90 100         if (version != PROXY_V2_VERSION)
1225 41           return -1; // unsupported version
1226              
1227             // Parse family and protocol (byte 13)
1228 49           unsigned char fam_proto = buf[13];
1229 49           unsigned char family = fam_proto & 0xF0;
1230              
1231             // Parse address length (bytes 14-15, big-endian)
1232 49           uint16_t addr_len = (buf[14] << 8) | buf[15];
1233 49 50         if (unlikely(addr_len > 4096)) { /* spec allows 65535, cap for sanity */
1234 0           trouble("PROXY v2 addr_len too large: %u\n", addr_len);
1235 0           return -1;
1236             }
1237              
1238             // Total header length
1239 49           size_t total_len = PROXY_V2_HDR_MIN + addr_len;
1240 49 100         if (len < total_len)
1241 3           return -2; // need more data
1242              
1243             // Handle command
1244 46 100         if (command == PROXY_V2_CMD_LOCAL) {
1245             // LOCAL command - keep original address (health checks, etc.)
1246 1           c->proxy_proto_version = 2;
1247             trace("PROXY v2 LOCAL, keeping original address\n");
1248 1           return (int)total_len;
1249             }
1250              
1251 45 50         if (command != PROXY_V2_CMD_PROXY) {
1252 0           return -1; // unknown command
1253             }
1254              
1255             // PROXY command - update source address
1256 45           unsigned char *addr_data = buf + PROXY_V2_HDR_MIN;
1257              
1258 45 100         if (family == PROXY_V2_FAM_INET) {
1259             // IPv4 - need 12 bytes: src_addr(4) + dst_addr(4) + src_port(2) + dst_port(2)
1260 43 50         if (addr_len < PROXY_V2_ADDR_V4_LEN)
1261 0           return -1;
1262              
1263 43           struct sockaddr_in *sa4 = (struct sockaddr_in *)&c->sa;
1264 43           sa4->sin_family = AF_INET;
1265 43           memcpy(&sa4->sin_addr, addr_data, 4); // src addr
1266 43           memcpy(&sa4->sin_port, addr_data + 8, 2); // src port (already network order)
1267              
1268             // Extract dst_port for scheme inference (offset 10, network byte order)
1269             uint16_t dst_port_n;
1270 43           memcpy(&dst_port_n, addr_data + 10, 2);
1271 43           c->proxy_dst_port = ntohs(dst_port_n);
1272              
1273             trace("PROXY v2 TCP4 src=%d.%d.%d.%d:%d dst_port=%d\n",
1274             addr_data[0], addr_data[1], addr_data[2], addr_data[3],
1275             ntohs(sa4->sin_port), c->proxy_dst_port);
1276 2 100         } else if (family == PROXY_V2_FAM_INET6) {
1277             // IPv6 - need 36 bytes: src_addr(16) + dst_addr(16) + src_port(2) + dst_port(2)
1278 1 50         if (addr_len < PROXY_V2_ADDR_V6_LEN)
1279 0           return -1;
1280              
1281 1           struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&c->sa;
1282 1           sa6->sin6_family = AF_INET6;
1283 1           memcpy(&sa6->sin6_addr, addr_data, 16); // src addr
1284 1           memcpy(&sa6->sin6_port, addr_data + 32, 2); // src port (already network order)
1285              
1286             // Extract dst_port for scheme inference (offset 34, network byte order)
1287             uint16_t dst_port_n;
1288 1           memcpy(&dst_port_n, addr_data + 34, 2);
1289 1           c->proxy_dst_port = ntohs(dst_port_n);
1290              
1291             trace("PROXY v2 TCP6 port=%d dst_port=%d\n", ntohs(sa6->sin6_port), c->proxy_dst_port);
1292 1 50         } else if (family == PROXY_V2_FAM_UNSPEC) {
1293             // Unspecified - keep original address
1294             trace("PROXY v2 UNSPEC, keeping original address\n");
1295             } else {
1296 0           return -1; // unsupported family
1297             }
1298              
1299             // Parse TLVs if present
1300 45           size_t addr_size = 0;
1301 45 100         if (family == PROXY_V2_FAM_INET) addr_size = PROXY_V2_ADDR_V4_LEN;
1302 2 100         else if (family == PROXY_V2_FAM_INET6) addr_size = PROXY_V2_ADDR_V6_LEN;
1303              
1304 45 100         if (addr_len > addr_size) {
1305             dTHX; /* Perl API calls below (newHV, newSVpvn, hv_store, etc.) */
1306             // TLVs are present
1307 21           unsigned char *tlv_start = addr_data + addr_size;
1308 21           size_t tlv_remaining = addr_len - addr_size;
1309              
1310             // Create hash for TLVs
1311 21           HV *tlv_hv = newHV();
1312 21           unsigned int tlv_count = 0;
1313              
1314 25 100         while (tlv_remaining >= 3) { // minimum TLV: 1 type + 2 length
1315             // Bound iteration: a malicious sender can pack ~1365 zero-length
1316             // TLVs into a 4096-byte payload. 64 covers all real-world headers.
1317 21 50         if (++tlv_count > 64) {
1318             trace("PROXY v2 too many TLVs (>64), rejecting\n");
1319 0           SvREFCNT_dec((SV *)tlv_hv);
1320 0           return -1;
1321             }
1322 21           unsigned char tlv_type = tlv_start[0];
1323 21           uint16_t tlv_len = (tlv_start[1] << 8) | tlv_start[2];
1324              
1325 21 100         if (tlv_remaining < 3 + (size_t)tlv_len) {
1326             // Malformed TLV - reject the whole PROXY header per spec
1327             trace("PROXY v2 malformed TLV: need %u bytes, have %zu\n",
1328             tlv_len, tlv_remaining - 3);
1329 17           SvREFCNT_dec((SV *)tlv_hv);
1330 17           return -1;
1331             }
1332              
1333             // Check for SSL TLV (indicates connection was over SSL/TLS)
1334             // PP2_TYPE_SSL requires minimum 5 bytes (client flags + verify)
1335 4 100         if (tlv_type == PP2_TYPE_SSL && tlv_len >= 5) {
    50          
1336 2           c->proxy_ssl = 1;
1337             trace("PROXY v2 TLV PP2_TYPE_SSL detected\n");
1338             }
1339              
1340             // Store TLV value (skip NOOP type)
1341 4 50         if (tlv_type != PP2_TYPE_NOOP) {
1342 4           SV *val = newSVpvn((char *)(tlv_start + 3), tlv_len);
1343             char key[8];
1344 4           int key_len = snprintf(key, sizeof(key), "%u", tlv_type);
1345 4           hv_store(tlv_hv, key, key_len, val, 0);
1346             trace("PROXY v2 TLV type=%u len=%u\n", tlv_type, tlv_len);
1347             }
1348              
1349 4           tlv_start += 3 + (size_t)tlv_len;
1350 4           tlv_remaining -= 3 + (size_t)tlv_len;
1351             }
1352              
1353             // Store hash in connection if non-empty
1354 4 50         if (HvKEYS(tlv_hv) > 0) {
    100          
1355 3           c->proxy_tlvs = newRV_noinc((SV *)tlv_hv);
1356             } else {
1357 1           SvREFCNT_dec((SV *)tlv_hv);
1358             }
1359             }
1360              
1361 28           c->proxy_proto_version = 2;
1362 28           return (int)total_len;
1363             }
1364              
1365             // Try to parse PROXY protocol header (auto-detect v1 or v2)
1366             // Returns: bytes consumed on success, -1 on error, -2 if need more data
1367             static int
1368 288           try_parse_proxy_header(struct feer_conn *c)
1369             {
1370 288 50         if (SvCUR(c->rbuf) == 0)
1371 0           return -2; // need data
1372              
1373 288           unsigned char first = ((unsigned char *)SvPVX(c->rbuf))[0];
1374              
1375 288 100         if (first == 'P') {
1376 154           return parse_proxy_v1(c);
1377 134 100         } else if (first == 0x0D) {
1378 113           return parse_proxy_v2(c);
1379             } else {
1380 21           return -1; // neither v1 nor v2
1381             }
1382             }
1383