File Coverage

feersum_core.c.inc
Criterion Covered Total %
statement 583 733 79.5
branch 252 398 63.3
condition n/a
subroutine n/a
pod n/a
total 835 1131 73.8


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 1008           next_iomatrix (struct feer_conn *c)
19             {
20 1008           bool add_iomatrix = 0;
21             struct iomatrix *m;
22              
23 1008 100         if (!c->wbuf_rinq) {
24             trace3("next_iomatrix(%d): head\n", c->fd);
25 767           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 1008 100         if (add_iomatrix) {
38             trace3("next_iomatrix(%d): alloc\n", c->fd);
39 767 100         IOMATRIX_ALLOC(m);
40 767           m->offset = m->count = 0;
41 767           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 1008           return m;
47             }
48              
49             INLINE_UNLESS_DEBUG
50             static STRLEN
51 321           add_sv_to_wbuf(struct feer_conn *c, SV *sv)
52             {
53 321           struct iomatrix *m = next_iomatrix(c);
54 321           unsigned idx = m->count++;
55             STRLEN cur;
56 321 100         if (unlikely(SvMAGICAL(sv))) {
57 1           sv = newSVsv(sv); // copy to force it to be normal.
58             }
59 320 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 320           sv = SvREFCNT_inc(sv);
92             }
93              
94 321           m->iov[idx].iov_base = SvPV(sv, cur);
95 321           m->iov[idx].iov_len = cur;
96 321           m->sv[idx] = sv;
97              
98 321           c->wbuf_len += cur;
99 321           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 198           http_code_to_msg (int code) {
164 198           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 156           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 1225           safe_close_conn(struct feer_conn *c, const char *where)
310             {
311 1225 100         if (unlikely(c->fd < 0))
312 589           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             #ifdef FEERSUM_HAS_H2
499             s->max_h2_concurrent_streams = FEER_H2_MAX_CONCURRENT_STREAMS;
500             #endif
501 3536 100         for (i = 0; i < FEER_MAX_LISTENERS; i++) {
502 3328           s->listeners[i].fd = -1;
503 3328           s->listeners[i].server = s;
504             #ifdef __linux__
505 3328           s->listeners[i].epoll_fd = -1;
506             #endif
507             }
508 208           }
509              
510             static struct feer_server *
511 208           new_feer_server (pTHX)
512             {
513 208           SV *self = newSV(0);
514 208 50         SvUPGRADE(self, SVt_PVMG);
515 208 50         SvGROW(self, sizeof(struct feer_server));
    50          
516 208           SvPOK_only(self);
517 208           SvIOK_on(self);
518              
519 208           struct feer_server *s = (struct feer_server *)SvPVX(self);
520 208           init_feer_server(s);
521 208           s->self = self;
522              
523 208           SV *rv = newRV_inc(self);
524 208           sv_bless(rv, feer_stash);
525 208           SvREFCNT_dec(rv);
526              
527 208           SvREADONLY_on(self);
528 208           return s;
529             }
530              
531             INLINE_UNLESS_DEBUG
532             static struct feer_server *
533 27399           sv_2feer_server (SV *rv)
534             {
535             // Accept both instance ($obj->method) and class (Feersum->method) calls
536 27399 100         if (sv_isa(rv, "Feersum")) {
537 27366           return (struct feer_server *)SvPVX(SvRV(rv));
538             }
539             // Class method call: "Feersum"->method() - return default server
540 33 50         if (SvPOK(rv) && strEQ(SvPV_nolen(rv), "Feersum")) {
    50          
541 33 50         if (unlikely(!default_server))
542 0           croak("Feersum: no server instance (call Feersum->new first)");
543 33           return default_server;
544             }
545 0           croak("object is not of type Feersum");
546             return NULL; // unreachable
547             }
548              
549             INLINE_UNLESS_DEBUG
550             static SV*
551 195           feer_server_2sv (struct feer_server *s)
552             {
553 195           return newRV_inc(s->self);
554             }
555              
556             INLINE_UNLESS_DEBUG static void
557 156           start_read_watcher(struct feer_conn *c) {
558             ASSERT_EV_LOOP_INITIALIZED();
559 156 100         if (unlikely(ev_is_active(&c->read_ev_io)))
560 12           return;
561             trace("start read watcher %d\n",c->fd);
562 144           ev_io_start(feersum_ev_loop, &c->read_ev_io);
563 144           SvREFCNT_inc_void_NN(c->self);
564             }
565              
566             INLINE_UNLESS_DEBUG static void
567 982           stop_read_watcher(struct feer_conn *c) {
568 982 100         if (unlikely(!ev_is_active(&c->read_ev_io)))
569 847           return;
570             trace("stop read watcher %d\n",c->fd);
571 135           ev_io_stop(feersum_ev_loop, &c->read_ev_io);
572 135           SvREFCNT_dec(c->self);
573             }
574              
575             INLINE_UNLESS_DEBUG static void
576 140           restart_read_timer(struct feer_conn *c) {
577 140 100         if (likely(!ev_is_active(&c->read_ev_timer))) {
578             trace("restart read timer %d\n",c->fd);
579 119           c->read_ev_timer.repeat = c->cached_read_timeout;
580 119           SvREFCNT_inc_void_NN(c->self);
581             }
582 140           ev_timer_again(feersum_ev_loop, &c->read_ev_timer);
583 140           }
584              
585             INLINE_UNLESS_DEBUG static void
586 991           stop_read_timer(struct feer_conn *c) {
587 991 100         if (unlikely(!ev_is_active(&c->read_ev_timer)))
588 876           return;
589             trace("stop read timer %d\n",c->fd);
590 115           ev_timer_stop(feersum_ev_loop, &c->read_ev_timer);
591 115           SvREFCNT_dec(c->self);
592             }
593              
594             INLINE_UNLESS_DEBUG static void
595 631           start_write_watcher(struct feer_conn *c) {
596             ASSERT_EV_LOOP_INITIALIZED();
597 631 100         if (unlikely(ev_is_active(&c->write_ev_io)))
598 121           return;
599             trace("start write watcher %d\n",c->fd);
600 510           ev_io_start(feersum_ev_loop, &c->write_ev_io);
601 510           SvREFCNT_inc_void_NN(c->self);
602             }
603              
604             INLINE_UNLESS_DEBUG static void
605 796           stop_write_watcher(struct feer_conn *c) {
606 796 100         if (unlikely(!ev_is_active(&c->write_ev_io)))
607 286           return;
608             trace("stop write watcher %d\n",c->fd);
609 510           ev_io_stop(feersum_ev_loop, &c->write_ev_io);
610 510           SvREFCNT_dec(c->self);
611             }
612              
613             INLINE_UNLESS_DEBUG static void
614 764           restart_write_timer(struct feer_conn *c) {
615 764 100         if (c->cached_write_timeout <= 0.0) return;
616 1 50         if (likely(!ev_is_active(&c->write_ev_timer))) {
617             trace("restart write timer %d\n",c->fd);
618 1           c->write_ev_timer.repeat = c->cached_write_timeout;
619 1           SvREFCNT_inc_void_NN(c->self);
620             }
621 1           ev_timer_again(feersum_ev_loop, &c->write_ev_timer);
622             }
623              
624             INLINE_UNLESS_DEBUG static void
625 817           stop_write_timer(struct feer_conn *c) {
626 817 100         if (unlikely(!ev_is_active(&c->write_ev_timer)))
627 816           return;
628             trace("stop write timer %d\n",c->fd);
629 1           ev_timer_stop(feersum_ev_loop, &c->write_ev_timer);
630 1           SvREFCNT_dec(c->self);
631             }
632              
633             INLINE_UNLESS_DEBUG static void
634 1722           stop_header_timer(struct feer_conn *c) {
635 1722 100         if (unlikely(!ev_is_active(&c->header_ev_timer)))
636 959           return;
637             trace("stop header timer %d\n", c->fd);
638 763           ev_timer_stop(feersum_ev_loop, &c->header_ev_timer);
639 763           SvREFCNT_dec(c->self);
640             }
641              
642             INLINE_UNLESS_DEBUG static void
643 145           restart_header_timer(struct feer_conn *c) {
644 145           double timeout = c->server->header_timeout;
645 145 50         if (timeout <= 0.0) return;
646 145           stop_header_timer(c);
647 145           ev_timer_set(&c->header_ev_timer, timeout, 0.0);
648 145           ev_timer_start(feersum_ev_loop, &c->header_ev_timer);
649 145           SvREFCNT_inc_void_NN(c->self);
650             }
651              
652             INLINE_UNLESS_DEBUG static void
653 53           stop_all_watchers(struct feer_conn *c) {
654 53           stop_read_watcher(c);
655 53           stop_read_timer(c);
656 53           stop_header_timer(c);
657 53           stop_write_watcher(c);
658 53           stop_write_timer(c);
659 53           }
660              
661             static void
662 1713           feer_conn_set_busy(struct feer_conn *c)
663             {
664 1713 100         if (c->idle_rinq_node) {
665 34           rinq_remove(&c->server->idle_keepalive_rinq, c->idle_rinq_node);
666 34           c->idle_rinq_node = NULL;
667             }
668 1713           }
669              
670             static void
671 36           feer_conn_set_idle(struct feer_conn *c)
672             {
673 36 50         if (c->idle_rinq_node) return; // already idle
674              
675             struct rinq *node;
676 36 50         RINQ_NEW(node, c);
    0          
677              
678 36           struct rinq **head = &c->server->idle_keepalive_rinq;
679 36 100         if (*head == NULL) {
680 31           *head = node;
681             } else {
682 5           node->next = *head;
683 5           node->prev = (*head)->prev;
684 5           node->next->prev = node->prev->next = node;
685             }
686 36           c->idle_rinq_node = node;
687             trace("conn fd=%d is now idle (added to MRU)\n", c->fd);
688             }
689              
690             static int
691 11           feer_server_recycle_idle_conn(struct feer_server *srvr)
692             {
693 11 100         if (!srvr->idle_keepalive_rinq) return 0;
694              
695 2           struct feer_conn *c = (struct feer_conn *)rinq_shift(&srvr->idle_keepalive_rinq);
696 2 50         if (unlikely(!c)) return 0;
697              
698 2           c->idle_rinq_node = NULL; // node was shifted
699              
700             trace("recycling idle keepalive conn fd=%d to make room for new accept\n", c->fd);
701              
702             // Gracefully shut down the idle connection.
703             // Guard: after setup_accepted_conn drops the base refcount, connections
704             // are alive only via watcher refcounts. stop_all_watchers can drop
705             // refcount to 0 → DESTROY fires before safe_close_conn.
706 2           SvREFCNT_inc_void_NN(c->self);
707 2           stop_all_watchers(c);
708 2           safe_close_conn(c, "recycled for new connection");
709 2           change_responding_state(c, RESPOND_SHUTDOWN);
710 2           SvREFCNT_dec(c->self);
711              
712             // active_conns will be decremented in DESTROY when refcount drops.
713 2           return 1;
714             }
715              
716              
717             static void
718 369           process_request_ready_rinq (struct feer_server *server)
719             {
720 901 100         while (server->request_ready_rinq) {
721             struct feer_conn *c =
722 532           (struct feer_conn *)rinq_shift(&server->request_ready_rinq);
723 532 50         if (unlikely(!c)) break;
724              
725 532           call_request_callback(c);
726              
727 532 100         if (likely(c->wbuf_rinq)) {
728             // this was deferred until after the perl callback
729 504           conn_write_ready(c);
730             }
731             #ifdef FEERSUM_HAS_H2
732             else if (c->is_h2_stream) {
733             // H2 pseudo-conns don't use wbuf_rinq; flush deferred session_send
734             dTHX;
735             struct feer_h2_stream *stream =
736             (struct feer_h2_stream *)c->read_ev_timer.data;
737             if (stream && stream->parent) {
738             struct feer_conn *parent = stream->parent;
739             SvREFCNT_inc_void_NN(parent->self);
740             feer_h2_session_send(parent);
741             h2_check_stream_poll_cbs(aTHX_ parent);
742             SvREFCNT_dec(parent->self);
743             }
744             }
745             #endif
746 532           SvREFCNT_dec(c->self); // for the rinq
747             }
748 369           }
749              
750             static void
751 158           prepare_cb (EV_P_ ev_prepare *w, int revents)
752             {
753 158           struct feer_server *srvr = (struct feer_server *)w->data;
754             int i;
755              
756 158 50         if (unlikely(revents & EV_ERROR)) {
757 0           trouble("EV error in prepare, revents=0x%08x\n", revents);
758 0           ev_break(EV_A, EVBREAK_ALL);
759 0           return;
760             }
761              
762 158 100         if (!srvr->shutting_down) {
763 399 100         for (i = 0; i < srvr->n_listeners; i++) {
764 243           struct feer_listen *lsnr = &srvr->listeners[i];
765 243 100         if (!ev_is_active(&lsnr->accept_w) && !lsnr->paused) {
    50          
766 164           ev_io_start(EV_A, &lsnr->accept_w);
767             }
768             }
769             }
770 158           ev_prepare_stop(EV_A, w);
771             }
772              
773             static void
774 4894           check_cb (EV_P_ ev_check *w, int revents)
775             {
776 4894           struct feer_server *server = (struct feer_server *)w->data;
777              
778 4894 50         if (unlikely(revents & EV_ERROR)) {
779 0           trouble("EV error in check, revents=0x%08x\n", revents);
780 0           ev_break(EV_A, EVBREAK_ALL);
781 0           return;
782             }
783              
784             trace3("check! head=%p\n", server->request_ready_rinq);
785 4894 100         if (server->request_ready_rinq)
786 369           process_request_ready_rinq(server);
787             }
788              
789             static void
790 366           idle_cb (EV_P_ ev_idle *w, int revents)
791             {
792 366           struct feer_server *server = (struct feer_server *)w->data;
793              
794             trace("idle_cb called, revents=0x%08x\n", revents);
795 366 50         if (unlikely(revents & EV_ERROR)) {
796 0           trouble("EV error in idle, revents=0x%08x\n", revents);
797 0           ev_break(EV_A, EVBREAK_ALL);
798 0           return;
799             }
800             trace3("idle! head=%p\n", server->request_ready_rinq);
801 366 50         if (server->request_ready_rinq)
802 0           process_request_ready_rinq(server);
803 366           ev_idle_stop(EV_A, w);
804             }
805              
806             /*
807             * Shared keepalive-or-close logic for both plain and TLS write paths.
808             * read_cb is try_conn_read (plain) or try_tls_conn_read (TLS).
809             */
810             static void
811 707           handle_keepalive_or_close(struct feer_conn *c, conn_read_cb_t read_cb)
812             {
813 707           stop_write_watcher(c);
814 707           stop_write_timer(c);
815              
816             if (FEERSUM_RESP_DONE_ENABLED()) {
817             FEERSUM_RESP_DONE(c->fd, 0);
818             }
819              
820             /* If the request had a body the app didn't fully consume, strip the
821             * remaining body bytes from rbuf so they don't get parsed as the next
822             * HTTP request. Any pipelined data after the body is preserved.
823             *
824             * For Content-Length bodies: rbuf starts with body data (headers already
825             * stripped by picohttpparser). consumed = bytes the app read via
826             * $input->read (which does sv_chop). remaining = body bytes still at
827             * the start of rbuf.
828             *
829             * For chunked bodies: the chunked parser decoded in-place. rbuf has
830             * decoded body (received_cl bytes) followed by any pipelined data.
831             * consumed works the same way (sv_chop by $input->read). */
832 707 100         if (c->is_keepalive && c->rbuf) {
    100          
833             /* expected_cl is set by both Content-Length and chunked paths
834             * (try_parse_chunked sets expected_cl = decoded body size). */
835 136           ssize_t body_total = (c->expected_cl > 0) ? c->expected_cl : 0;
836 136 100         if (body_total > 0) {
837 14           ssize_t consumed = c->received_cl - (ssize_t)SvCUR(c->rbuf);
838 14           ssize_t remaining = body_total - consumed;
839 14 100         if (remaining > 0 && remaining <= (ssize_t)SvCUR(c->rbuf)) {
    50          
840 5           sv_chop(c->rbuf, SvPVX(c->rbuf) + remaining);
841             trace("drained body fd=%d stripped=%"Ssz_df" pipeline=%"Sz_uf"\n",
842             c->fd, (Ssz)remaining, (Sz)SvCUR(c->rbuf));
843             }
844             }
845             }
846              
847 707 100         if (c->is_keepalive) {
848 142           change_responding_state(c, RESPOND_NOT_STARTED);
849 142           change_receiving_state(c, RECEIVE_WAIT);
850 142           STRLEN pipelined = 0;
851 142 100         if (c->rbuf) { pipelined = SvCUR(c->rbuf); }
852 142 50         if (likely(c->req)) {
853 172 100         if (likely(pipelined == 0) && c->req->buf && c->rbuf) {
    50          
    100          
854 30           SV *tmp = c->rbuf;
855 30           c->rbuf = c->req->buf;
856 30           c->req->buf = NULL;
857 30           SvCUR_set(c->rbuf, 0);
858             // Shrink oversized buffers from large bodies to avoid
859             // holding max_body_len per keepalive connection
860 30 50         if (SvLEN(c->rbuf) > READ_BUFSZ * 4)
861 0           SvPV_renew(c->rbuf, READ_BUFSZ + 1);
862 30           SvREFCNT_dec(tmp);
863 112 50         } else if (c->req->buf) {
864 112           SvREFCNT_dec(c->req->buf);
865 112           c->req->buf = NULL;
866             }
867 142           free_request(c);
868             }
869 142 100         if (unlikely(pipelined > 0 && c->is_http11)) {
    50          
870 106           c->pipelined = pipelined;
871 106 50         if (c->pipeline_depth <= MAX_PIPELINE_DEPTH) {
872 106           c->pipeline_depth++;
873 106           restart_header_timer(c);
874 106           read_cb(feersum_ev_loop, &c->read_ev_io, 0);
875 106           c->pipeline_depth--;
876             } else {
877             trace("pipeline depth limit reached on %d\n", c->fd);
878 0           start_read_watcher(c);
879 0           restart_read_timer(c);
880 0           restart_header_timer(c);
881 0           feer_conn_set_idle(c);
882             }
883             } else {
884 36           c->pipelined = 0;
885 36           start_read_watcher(c);
886 36           restart_read_timer(c);
887 36           restart_header_timer(c);
888 36           feer_conn_set_idle(c);
889             }
890             } else {
891 565 50         if (c->responding != RESPOND_SHUTDOWN)
892 0           change_responding_state(c, RESPOND_SHUTDOWN);
893 565           safe_close_conn(c, "close at write shutdown");
894             }
895 707           }
896              
897             static void
898 707           try_conn_write(EV_P_ struct ev_io *w, int revents)
899             {
900 707           dCONN;
901             unsigned i;
902             struct iomatrix *m;
903              
904 707           SvREFCNT_inc_void_NN(c->self);
905              
906             // if it's marked writeable EV suggests we simply try write to it.
907             // Otherwise it is stopped and we should ditch this connection.
908 707 50         if (unlikely(revents & EV_ERROR && !(revents & EV_WRITE))) {
    0          
909             trace("EV error on write, fd=%d revents=0x%08x\n", w->fd, revents);
910 0           change_responding_state(c, RESPOND_SHUTDOWN);
911 0           goto try_write_finished;
912             }
913              
914 707 100         if (unlikely(!c->wbuf_rinq)) {
915 23 100         if (unlikely(c->responding >= RESPOND_SHUTDOWN))
916 3           goto try_write_finished;
917              
918             #ifdef __linux__
919             // Check for sendfile pending (headers already sent)
920 20 50         if (c->sendfile_fd >= 0)
921 0           goto try_sendfile;
922             #endif
923              
924 20 50         if (!c->poll_write_cb) {
925             // no callback and no data: wait for app to push to us.
926 0 0         if (c->responding == RESPOND_STREAMING)
927 0           goto try_write_paused;
928              
929             trace("tried to write with an empty buffer %d resp=%d\n",w->fd,c->responding);
930 0           change_responding_state(c, RESPOND_SHUTDOWN);
931 0           goto try_write_finished;
932             }
933              
934 20 100         if (c->poll_write_cb_is_io_handle)
935 11           pump_io_handle(c);
936             else
937 9           call_poll_callback(c, 1);
938              
939             // callback didn't write anything:
940 20 50         if (unlikely(!c->wbuf_rinq)) goto try_write_again;
941             }
942             // Low-water-mark: buffer not empty but below threshold — refill before writing
943 684 100         else if (c->cached_wbuf_low_water > 0
944 1 50         && c->wbuf_len <= c->cached_wbuf_low_water
945 1 50         && c->responding == RESPOND_STREAMING && c->poll_write_cb) {
    50          
946 1 50         if (c->poll_write_cb_is_io_handle)
947 0           pump_io_handle(c);
948             else
949 1           call_poll_callback(c, 1);
950             }
951              
952 704           try_write_again_immediately:
953             #if defined(__linux__) && defined(FEERSUM_TCP_CORK)
954             // Cork socket when writing headers before sendfile for optimal packet framing
955 704 100         if (c->sendfile_fd >= 0)
956 3           set_cork(c, 1);
957             #endif
958 704           m = (struct iomatrix *)c->wbuf_rinq->ref;
959             #if DEBUG >= 2
960             warn("going to write to %d:\n",c->fd);
961             for (i=0; i < m->count; i++) {
962             fprintf(stderr,"%.*s",
963             (int)m->iov[i].iov_len, (char*)m->iov[i].iov_base);
964             }
965             #endif
966              
967             trace("going to write %d off=%d count=%d\n", w->fd, m->offset, m->count);
968 704           errno = 0;
969 704           int iov_count = m->count - m->offset;
970             #ifdef IOV_MAX
971 704 50         if (iov_count > IOV_MAX) iov_count = IOV_MAX;
972             #endif
973             ssize_t wrote;
974 704 100         if (iov_count == 1) {
975             // Single element: write() is slightly faster than writev()
976 627           wrote = write(w->fd, m->iov[m->offset].iov_base, m->iov[m->offset].iov_len);
977             } else {
978 77           wrote = writev(w->fd, &m->iov[m->offset], iov_count);
979             }
980             trace("wrote %"Ssz_df" bytes to %d, errno=%d\n", (Ssz)wrote, w->fd, errno);
981              
982 704 50         if (unlikely(wrote <= 0)) {
983 0 0         if (likely(errno == EAGAIN || errno == EINTR))
    0          
984 0           goto try_write_again;
985 0           trouble("try_conn_write fd=%d: %s\n", w->fd, strerror(errno));
986 0 0         CLOSE_SENDFILE_FD(c);
    0          
987 0           set_cork(c, 0);
988 0           stop_write_timer(c);
989 0           change_responding_state(c, RESPOND_SHUTDOWN);
990 0           goto try_write_finished;
991             }
992              
993 704           c->wbuf_len -= wrote;
994 704           restart_write_timer(c);
995              
996 704           bool consume = 1;
997 1647 100         for (i = m->offset; i < m->count && consume; i++) {
    50          
998 943           struct iovec *v = &m->iov[i];
999 943 50         if (unlikely(v->iov_len > wrote)) {
1000             trace3("offset vector %d base=%p len=%"Sz_uf"\n",
1001             w->fd, v->iov_base, (Sz)v->iov_len);
1002 0           v->iov_base = (char*)v->iov_base + wrote;
1003 0           v->iov_len -= wrote;
1004             // don't consume any more:
1005 0           consume = 0;
1006             }
1007             else {
1008             trace3("consume vector %d base=%p len=%"Sz_uf" sv=%p\n",
1009             w->fd, v->iov_base, (Sz)v->iov_len, m->sv[i]);
1010 943           wrote -= v->iov_len;
1011 943           m->offset++;
1012 943 100         if (m->sv[i]) {
1013 840           SvREFCNT_dec(m->sv[i]);
1014 840           m->sv[i] = NULL;
1015             }
1016             }
1017             }
1018              
1019 704 50         if (likely(m->offset >= m->count)) {
1020             trace2("all done with iomatrix %d state=%d\n",w->fd,c->responding);
1021 704           rinq_shift(&c->wbuf_rinq);
1022 704 50         IOMATRIX_FREE(m);
1023 704 50         if (!c->wbuf_rinq) {
1024             #ifdef __linux__
1025             // sendfile pending? do zero-copy file transfer
1026 704 100         if (c->sendfile_fd >= 0)
1027 3           goto try_sendfile;
1028             #endif
1029 701           goto try_write_finished;
1030             }
1031             // Low-water-mark: yield to event loop so poll_cb can fire
1032 0 0         if (c->cached_wbuf_low_water > 0
1033 0 0         && c->wbuf_len <= c->cached_wbuf_low_water
1034 0 0         && c->responding == RESPOND_STREAMING && c->poll_write_cb) {
    0          
1035 0           goto try_write_again;
1036             }
1037             trace2("write again immediately %d state=%d\n",w->fd,c->responding);
1038 0           goto try_write_again_immediately;
1039             }
1040             // else, fallthrough:
1041             trace2("write fallthrough %d state=%d\n",w->fd,c->responding);
1042 0           goto try_write_again;
1043              
1044             #ifdef __linux__
1045 3           try_sendfile:
1046             {
1047             trace("sendfile %d: fd=%d off=%ld remain=%zu\n",
1048             w->fd, c->sendfile_fd, (long)c->sendfile_off, c->sendfile_remain);
1049 3           ssize_t sent = sendfile(w->fd, c->sendfile_fd,
1050 3           &c->sendfile_off, c->sendfile_remain);
1051 3 50         if (sent > 0) {
1052 3           c->sendfile_remain -= sent;
1053             trace("sendfile sent %zd, remain=%zu\n", sent, c->sendfile_remain);
1054 3 50         if (c->sendfile_remain == 0) {
1055 3 50         CLOSE_SENDFILE_FD(c);
    50          
1056 3           set_cork(c, 0);
1057 3           change_responding_state(c, RESPOND_SHUTDOWN);
1058 3           goto try_write_finished;
1059             }
1060             // More to send, wait for socket to be writable again
1061 0           goto try_write_again;
1062             }
1063 0 0         else if (sent == 0) {
1064             // EOF on file (shouldn't happen if sendfile_remain was correct)
1065 0 0         CLOSE_SENDFILE_FD(c);
    0          
1066 0           set_cork(c, 0);
1067 0 0         if (c->responding == RESPOND_STREAMING) {
1068 0           change_responding_state(c, RESPOND_SHUTDOWN);
1069             }
1070 0           goto try_write_finished;
1071             }
1072             else {
1073             // sent < 0, error
1074 0 0         if (errno == EAGAIN || errno == EINTR) {
    0          
1075             // Socket not ready, wait
1076 0           goto try_write_again;
1077             }
1078             // Real error
1079 0           trouble("sendfile fd=%d: %s\n", c->fd, strerror(errno));
1080 0 0         CLOSE_SENDFILE_FD(c);
    0          
1081 0           set_cork(c, 0);
1082 0           change_responding_state(c, RESPOND_SHUTDOWN);
1083 0           goto try_write_finished;
1084             }
1085             }
1086             #endif
1087              
1088 14           try_write_again:
1089             trace("write again %d state=%d\n",w->fd,c->responding);
1090 14           start_write_watcher(c);
1091 14           goto try_write_cleanup;
1092              
1093 707           try_write_finished:
1094             // should always be responding, but just in case
1095 707           switch(c->responding) {
1096 0           case RESPOND_NOT_STARTED:
1097             // the write watcher shouldn't ever get called before starting to
1098             // respond. Shut it down if it does.
1099             trace("unexpected try_write when response not started %d\n",c->fd);
1100 0           goto try_write_shutdown;
1101 0           case RESPOND_NORMAL:
1102 0           goto try_write_shutdown;
1103 50           case RESPOND_STREAMING:
1104 50 100         if (c->poll_write_cb) goto try_write_again;
1105 36           else goto try_write_paused;
1106 657           case RESPOND_SHUTDOWN:
1107 657           goto try_write_shutdown;
1108 0           default:
1109 0           goto try_write_cleanup;
1110             }
1111              
1112 36           try_write_paused:
1113             trace3("write PAUSED %d, refcnt=%d, state=%d\n", c->fd, SvREFCNT(c->self), c->responding);
1114 36           stop_write_watcher(c);
1115 36           stop_write_timer(c);
1116 36           goto try_write_cleanup;
1117              
1118 657           try_write_shutdown:
1119 657           handle_keepalive_or_close(c, try_conn_read);
1120              
1121 707           try_write_cleanup:
1122 707           SvREFCNT_dec(c->self);
1123 707           return;
1124             }
1125              
1126             // Parse PROXY protocol v1 text header
1127             // Format: "PROXY TCP4|TCP6|UNKNOWN src_addr dst_addr src_port dst_port\r\n"
1128             // Returns: bytes consumed on success, -1 on error, -2 if need more data
1129             static int
1130 155           parse_proxy_v1(struct feer_conn *c)
1131             {
1132 155           char *buf = SvPVX(c->rbuf);
1133 155           STRLEN len = SvCUR(c->rbuf);
1134              
1135             // Need at least "PROXY \r\n" (minimum valid line)
1136 155 100         if (len < 8)
1137 21           return -2; // need more data
1138              
1139             // Verify prefix
1140 134 100         if (memcmp(buf, PROXY_V1_PREFIX, PROXY_V1_PREFIX_LEN) != 0)
1141 1           return -1; // invalid
1142              
1143             // Find CRLF (max 108 bytes total)
1144 133           char *crlf = NULL;
1145 133           STRLEN search_len = len > PROXY_V1_MAX_LINE ? PROXY_V1_MAX_LINE : len;
1146             STRLEN i;
1147 3052 100         for (i = PROXY_V1_PREFIX_LEN; i < search_len - 1; i++) {
1148 2949 100         if (buf[i] == '\r' && buf[i+1] == '\n') {
    50          
1149 30           crlf = buf + i;
1150 30           break;
1151             }
1152             }
1153              
1154 133 100         if (!crlf) {
1155 103 100         if (len >= PROXY_V1_MAX_LINE)
1156 1           return -1; // line too long, invalid
1157 102           return -2; // need more data
1158             }
1159              
1160 30           size_t header_len = (crlf - buf) + 2; // include CRLF
1161              
1162             // Null-terminate the line for parsing (temporarily)
1163 30           char saved = *crlf;
1164 30           *crlf = '\0';
1165              
1166             // Parse protocol family: TCP4, TCP6, or UNKNOWN
1167 30           char *p = buf + PROXY_V1_PREFIX_LEN;
1168              
1169 30 100         if (strncmp(p, "UNKNOWN", 7) == 0 && (p[7] == '\0' || p[7] == ' ')) {
    50          
    0          
1170             // UNKNOWN - keep original address (used for health checks)
1171 1           *crlf = saved;
1172 1           c->proxy_proto_version = 1;
1173             trace("PROXY v1 UNKNOWN, keeping original address\n");
1174 1           return (int)header_len;
1175             }
1176              
1177 29           int is_ipv6 = 0;
1178 29 100         if (strncmp(p, "TCP4 ", 5) == 0) {
1179 26           p += 5;
1180 3 100         } else if (strncmp(p, "TCP6 ", 5) == 0) {
1181 2           p += 5;
1182 2           is_ipv6 = 1;
1183             } else {
1184 1           *crlf = saved;
1185 1           return -1; // unknown protocol
1186             }
1187              
1188             // Parse: src_addr dst_addr src_port dst_port
1189             char src_addr[46], dst_addr[46]; // max IPv6 length
1190             int src_port, dst_port;
1191              
1192             // Use sscanf to parse the addresses and ports
1193 28 50         if (sscanf(p, "%45s %45s %d %d", src_addr, dst_addr, &src_port, &dst_port) != 4) {
1194 0           *crlf = saved;
1195 0           return -1; // parse error
1196             }
1197              
1198             // Validate port ranges
1199 28 50         if (src_port < 0 || src_port > 65535 || dst_port < 0 || dst_port > 65535) {
    100          
    50          
    50          
1200 1           *crlf = saved;
1201 1           return -1;
1202             }
1203              
1204 27           *crlf = saved; // restore
1205              
1206             // Update connection's source address
1207 27 100         if (is_ipv6) {
1208 2           struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&c->sa;
1209 2           sa6->sin6_family = AF_INET6;
1210 2 50         if (inet_pton(AF_INET6, src_addr, &sa6->sin6_addr) != 1) {
1211 0           return -1; // invalid address
1212             }
1213 2           sa6->sin6_port = htons((uint16_t)src_port);
1214             } else {
1215 25           struct sockaddr_in *sa4 = (struct sockaddr_in *)&c->sa;
1216 25           sa4->sin_family = AF_INET;
1217 25 100         if (inet_pton(AF_INET, src_addr, &sa4->sin_addr) != 1) {
1218 1           return -1; // invalid address
1219             }
1220 24           sa4->sin_port = htons((uint16_t)src_port);
1221             }
1222              
1223 26           c->proxy_proto_version = 1;
1224 26           c->proxy_dst_port = (uint16_t)dst_port;
1225             trace("PROXY v1 %s src=%s:%d dst_port=%d\n", is_ipv6 ? "TCP6" : "TCP4", src_addr, src_port, dst_port);
1226 26           return (int)header_len;
1227             }
1228              
1229             // Parse PROXY protocol v2 binary header
1230             // Returns: bytes consumed on success, -1 on error, -2 if need more data
1231             static int
1232 107           parse_proxy_v2(struct feer_conn *c)
1233             {
1234 107           unsigned char *buf = (unsigned char *)SvPVX(c->rbuf);
1235 107           STRLEN len = SvCUR(c->rbuf);
1236              
1237             // Need at least minimum header (16 bytes)
1238 107 100         if (len < PROXY_V2_HDR_MIN)
1239 3           return -2;
1240              
1241             // Verify signature
1242 104 100         if (memcmp(buf, PROXY_V2_SIG, PROXY_V2_SIG_LEN) != 0)
1243 26           return -1;
1244              
1245             // Parse version and command (byte 12)
1246 78           unsigned char ver_cmd = buf[12];
1247 78           unsigned char version = ver_cmd & 0xF0;
1248 78           unsigned char command = ver_cmd & 0x0F;
1249              
1250 78 100         if (version != PROXY_V2_VERSION)
1251 30           return -1; // unsupported version
1252              
1253             // Parse family and protocol (byte 13)
1254 48           unsigned char fam_proto = buf[13];
1255 48           unsigned char family = fam_proto & 0xF0;
1256              
1257             // Parse address length (bytes 14-15, big-endian)
1258 48           uint16_t addr_len = (buf[14] << 8) | buf[15];
1259 48 100         if (unlikely(addr_len > 4096)) { /* spec allows 65535, cap for sanity */
1260 3           trouble("PROXY v2 addr_len too large: %u\n", addr_len);
1261 3           return -1;
1262             }
1263              
1264             // Total header length
1265 45           size_t total_len = PROXY_V2_HDR_MIN + addr_len;
1266 45 100         if (len < total_len)
1267 3           return -2; // need more data
1268              
1269             // Handle command
1270 42 100         if (command == PROXY_V2_CMD_LOCAL) {
1271             // LOCAL command - keep original address (health checks, etc.)
1272 1           c->proxy_proto_version = 2;
1273             trace("PROXY v2 LOCAL, keeping original address\n");
1274 1           return (int)total_len;
1275             }
1276              
1277 41 50         if (command != PROXY_V2_CMD_PROXY) {
1278 0           return -1; // unknown command
1279             }
1280              
1281             // PROXY command - update source address
1282 41           unsigned char *addr_data = buf + PROXY_V2_HDR_MIN;
1283              
1284 41 100         if (family == PROXY_V2_FAM_INET) {
1285             // IPv4 - need 12 bytes: src_addr(4) + dst_addr(4) + src_port(2) + dst_port(2)
1286 39 50         if (addr_len < PROXY_V2_ADDR_V4_LEN)
1287 0           return -1;
1288              
1289 39           struct sockaddr_in *sa4 = (struct sockaddr_in *)&c->sa;
1290 39           sa4->sin_family = AF_INET;
1291 39           memcpy(&sa4->sin_addr, addr_data, 4); // src addr
1292 39           memcpy(&sa4->sin_port, addr_data + 8, 2); // src port (already network order)
1293              
1294             // Extract dst_port for scheme inference (offset 10, network byte order)
1295             uint16_t dst_port_n;
1296 39           memcpy(&dst_port_n, addr_data + 10, 2);
1297 39           c->proxy_dst_port = ntohs(dst_port_n);
1298              
1299             trace("PROXY v2 TCP4 src=%d.%d.%d.%d:%d dst_port=%d\n",
1300             addr_data[0], addr_data[1], addr_data[2], addr_data[3],
1301             ntohs(sa4->sin_port), c->proxy_dst_port);
1302 2 100         } else if (family == PROXY_V2_FAM_INET6) {
1303             // IPv6 - need 36 bytes: src_addr(16) + dst_addr(16) + src_port(2) + dst_port(2)
1304 1 50         if (addr_len < PROXY_V2_ADDR_V6_LEN)
1305 0           return -1;
1306              
1307 1           struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)&c->sa;
1308 1           sa6->sin6_family = AF_INET6;
1309 1           memcpy(&sa6->sin6_addr, addr_data, 16); // src addr
1310 1           memcpy(&sa6->sin6_port, addr_data + 32, 2); // src port (already network order)
1311              
1312             // Extract dst_port for scheme inference (offset 34, network byte order)
1313             uint16_t dst_port_n;
1314 1           memcpy(&dst_port_n, addr_data + 34, 2);
1315 1           c->proxy_dst_port = ntohs(dst_port_n);
1316              
1317             trace("PROXY v2 TCP6 port=%d dst_port=%d\n", ntohs(sa6->sin6_port), c->proxy_dst_port);
1318 1 50         } else if (family == PROXY_V2_FAM_UNSPEC) {
1319             // Unspecified - keep original address
1320             trace("PROXY v2 UNSPEC, keeping original address\n");
1321             } else {
1322 0           return -1; // unsupported family
1323             }
1324              
1325             // Parse TLVs if present
1326 41           size_t addr_size = 0;
1327 41 100         if (family == PROXY_V2_FAM_INET) addr_size = PROXY_V2_ADDR_V4_LEN;
1328 2 100         else if (family == PROXY_V2_FAM_INET6) addr_size = PROXY_V2_ADDR_V6_LEN;
1329              
1330 41 100         if (addr_len > addr_size) {
1331             dTHX; /* Perl API calls below (newHV, newSVpvn, hv_store, etc.) */
1332             // TLVs are present
1333 18           unsigned char *tlv_start = addr_data + addr_size;
1334 18           size_t tlv_remaining = addr_len - addr_size;
1335              
1336             // Create hash for TLVs
1337 18           HV *tlv_hv = newHV();
1338              
1339 22 100         while (tlv_remaining >= 3) { // minimum TLV: 1 type + 2 length
1340 19           unsigned char tlv_type = tlv_start[0];
1341 19           uint16_t tlv_len = (tlv_start[1] << 8) | tlv_start[2];
1342              
1343 19 100         if (tlv_remaining < 3 + (size_t)tlv_len) {
1344             // Malformed TLV - reject the whole PROXY header per spec
1345             trace("PROXY v2 malformed TLV: need %u bytes, have %zu\n",
1346             tlv_len, tlv_remaining - 3);
1347 15           SvREFCNT_dec((SV *)tlv_hv);
1348 15           return -1;
1349             }
1350              
1351             // Check for SSL TLV (indicates connection was over SSL/TLS)
1352             // PP2_TYPE_SSL requires minimum 5 bytes (client flags + verify)
1353 4 100         if (tlv_type == PP2_TYPE_SSL && tlv_len >= 5) {
    50          
1354 2           c->proxy_ssl = 1;
1355             trace("PROXY v2 TLV PP2_TYPE_SSL detected\n");
1356             }
1357              
1358             // Store TLV value (skip NOOP type)
1359 4 50         if (tlv_type != PP2_TYPE_NOOP) {
1360 4           SV *val = newSVpvn((char *)(tlv_start + 3), tlv_len);
1361             char key[8];
1362 4           int key_len = snprintf(key, sizeof(key), "%u", tlv_type);
1363 4           hv_store(tlv_hv, key, key_len, val, 0);
1364             trace("PROXY v2 TLV type=%u len=%u\n", tlv_type, tlv_len);
1365             }
1366              
1367 4           tlv_start += 3 + (size_t)tlv_len;
1368 4           tlv_remaining -= 3 + (size_t)tlv_len;
1369             }
1370              
1371             // Store hash in connection if non-empty
1372 3 50         if (HvKEYS(tlv_hv) > 0) {
    50          
1373 3           c->proxy_tlvs = newRV_noinc((SV *)tlv_hv);
1374             } else {
1375 0           SvREFCNT_dec((SV *)tlv_hv);
1376             }
1377             }
1378              
1379 26           c->proxy_proto_version = 2;
1380 26           return (int)total_len;
1381             }
1382              
1383             // Try to parse PROXY protocol header (auto-detect v1 or v2)
1384             // Returns: bytes consumed on success, -1 on error, -2 if need more data
1385             static int
1386 288           try_parse_proxy_header(struct feer_conn *c)
1387             {
1388 288 50         if (SvCUR(c->rbuf) == 0)
1389 0           return -2; // need data
1390              
1391 288           unsigned char first = ((unsigned char *)SvPVX(c->rbuf))[0];
1392              
1393 288 100         if (first == 'P') {
1394 155           return parse_proxy_v1(c);
1395 133 100         } else if (first == 0x0D) {
1396 107           return parse_proxy_v2(c);
1397             } else {
1398 26           return -1; // neither v1 nor v2
1399             }
1400             }
1401