File Coverage

feersum_core.c.inc
Criterion Covered Total %
statement 580 730 79.4
branch 249 394 63.2
condition n/a
subroutine n/a
pod n/a
total 829 1124 73.7


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