File Coverage

feersum_core.c.inc
Criterion Covered Total %
statement 577 727 79.3
branch 247 392 63.0
condition n/a
subroutine n/a
pod n/a
total 824 1119 73.6


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