Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/tree.h>
19 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
24 #include <errno.h>
25 #include <event.h>
26 #include <limits.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <string.h>
32 #include <unistd.h>
34 #include "log.h"
36 #include "galileo.h"
38 #define MIN(a, b) ((a) < (b) ? (a) : (b))
40 struct fcgi_header {
41 unsigned char version;
42 unsigned char type;
43 unsigned char req_id1;
44 unsigned char req_id0;
45 unsigned char content_len1;
46 unsigned char content_len0;
47 unsigned char padding;
48 unsigned char reserved;
49 } __attribute__((packed));
51 /*
52 * number of bytes in a FCGI_HEADER. Future version of the protocol
53 * will not reduce this number.
54 */
55 #define FCGI_HEADER_LEN 8
57 /*
58 * values for the version component
59 */
60 #define FCGI_VERSION_1 1
62 /*
63 * values for the type component
64 */
65 #define FCGI_BEGIN_REQUEST 1
66 #define FCGI_ABORT_REQUEST 2
67 #define FCGI_END_REQUEST 3
68 #define FCGI_PARAMS 4
69 #define FCGI_STDIN 5
70 #define FCGI_STDOUT 6
71 #define FCGI_STDERR 7
72 #define FCGI_DATA 8
73 #define FCGI_GET_VALUES 9
74 #define FCGI_GET_VALUES_RESULT 10
75 #define FCGI_UNKNOWN_TYPE 11
76 #define FCGI_MAXTYPE (FCGI_UNKNOWN_TYPE)
78 struct fcgi_begin_req {
79 unsigned char role1;
80 unsigned char role0;
81 unsigned char flags;
82 unsigned char reserved[5];
83 };
85 struct fcgi_begin_req_record {
86 struct fcgi_header header;
87 struct fcgi_begin_req body;
88 };
90 /*
91 * mask for flags;
92 */
93 #define FCGI_KEEP_CONN 1
95 /*
96 * values for the role
97 */
98 #define FCGI_RESPONDER 1
99 #define FCGI_AUTHORIZER 2
100 #define FCGI_FILTER 3
102 struct fcgi_end_req_body {
103 unsigned char app_status3;
104 unsigned char app_status2;
105 unsigned char app_status1;
106 unsigned char app_status0;
107 unsigned char proto_status;
108 unsigned char reserved[3];
109 };
111 /*
112 * values for proto_status
113 */
114 #define FCGI_REQUEST_COMPLETE 0
115 #define FCGI_CANT_MPX_CONN 1
116 #define FCGI_OVERLOADED 2
117 #define FCGI_UNKNOWN_ROLE 3
119 /*
120 * Variable names for FCGI_GET_VALUES / FCGI_GET_VALUES_RESULT
121 * records.
122 */
123 #define FCGI_MAX_CONNS "FCGI_MAX_CONNS"
124 #define FCGI_MAX_REQS "FCGI_MAX_REQS"
125 #define FCGI_MPXS_CONNS "FCGI_MPXS_CONNS"
127 #define CAT(f0, f1) ((f0) + ((f1) << 8))
129 enum {
130 FCGI_RECORD_HEADER,
131 FCGI_RECORD_BODY,
132 };
134 volatile int fcgi_inflight;
136 static int
137 fcgi_send_end_req(struct fcgi *fcgi, int id, int as, int ps)
139 struct bufferevent *bev = fcgi->fcg_bev;
140 struct fcgi_header hdr;
141 struct fcgi_end_req_body end;
143 memset(&hdr, 0, sizeof(hdr));
144 memset(&end, 0, sizeof(end));
146 hdr.version = FCGI_VERSION_1;
147 hdr.type = FCGI_END_REQUEST;
148 hdr.req_id0 = (id & 0xFF);
149 hdr.req_id1 = (id >> 8);
150 hdr.content_len0 = sizeof(end);
152 end.app_status0 = (unsigned char)as;
153 end.proto_status = (unsigned char)ps;
155 if (bufferevent_write(bev, &hdr, sizeof(hdr)) == -1)
156 return (-1);
157 if (bufferevent_write(bev, &end, sizeof(end)) == -1)
158 return (-1);
159 return (0);
162 static int
163 end_request(struct client *clt, int status, int proto_status)
165 struct fcgi *fcgi = clt->clt_fcgi;
166 int r;
168 if (clt_flush(clt) == -1)
169 return (-1);
171 r = fcgi_send_end_req(fcgi, clt->clt_id, status,
172 proto_status);
173 if (r == -1) {
174 fcgi_error(fcgi->fcg_bev, EV_WRITE, fcgi);
175 return (-1);
178 SPLAY_REMOVE(client_tree, &fcgi->fcg_clients, clt);
179 proxy_client_free(clt);
180 return (0);
183 int
184 fcgi_end_request(struct client *clt, int status)
186 return (end_request(clt, status, FCGI_REQUEST_COMPLETE));
189 int
190 fcgi_abort_request(struct client *clt)
192 return (end_request(clt, 1, FCGI_OVERLOADED));
195 static void
196 fcgi_inflight_dec(const char *why)
198 fcgi_inflight--;
199 log_debug("%s: fcgi inflight decremented, now %d, %s",
200 __func__, fcgi_inflight, why);
203 void
204 fcgi_accept(int fd, short event, void *arg)
206 struct galileo *env = arg;
207 struct fcgi *fcgi = NULL;
208 socklen_t slen;
209 struct sockaddr_storage ss;
210 int s = -1;
212 event_add(&env->sc_evpause, NULL);
213 if ((event & EV_TIMEOUT))
214 return;
216 slen = sizeof(ss);
217 if ((s = accept_reserve(env->sc_sock_fd, (struct sockaddr *)&ss,
218 &slen, FD_RESERVE, &fcgi_inflight)) == -1) {
219 /*
220 * Pause accept if we are out of file descriptors, or
221 * libevent will haunt us here too.
222 */
223 if (errno == ENFILE || errno == EMFILE) {
224 struct timeval evtpause = { 1, 0 };
226 event_del(&env->sc_evsock);
227 evtimer_add(&env->sc_evpause, &evtpause);
228 log_debug("%s: deferring connections", __func__);
230 return;
233 if ((fcgi = calloc(1, sizeof(*fcgi))) == NULL)
234 goto err;
236 fcgi->fcg_id = ++proxy_fcg_id;
237 fcgi->fcg_s = s;
238 fcgi->fcg_env = env;
239 fcgi->fcg_want = FCGI_RECORD_HEADER;
240 fcgi->fcg_toread = sizeof(struct fcgi_header);
241 SPLAY_INIT(&fcgi->fcg_clients);
243 /* assume it's enabled until we get a FCGI_BEGIN_REQUEST */
244 fcgi->fcg_keep_conn = 1;
246 fcgi->fcg_bev = bufferevent_new(fcgi->fcg_s, fcgi_read, fcgi_write,
247 fcgi_error, fcgi);
248 if (fcgi->fcg_bev == NULL)
249 goto err;
251 bufferevent_enable(fcgi->fcg_bev, EV_READ | EV_WRITE);
252 return;
254 err:
255 if (s != -1) {
256 close(s);
257 free(fcgi);
258 fcgi_inflight_dec(__func__);
262 static int
263 parse_len(struct fcgi *fcgi, struct evbuffer *src)
265 unsigned char c, x[3];
267 fcgi->fcg_toread--;
268 evbuffer_remove(src, &c, 1);
269 if (c >> 7 == 0)
270 return (c);
272 if (fcgi->fcg_toread < 3)
273 return (-1);
275 fcgi->fcg_toread -= 3;
276 evbuffer_remove(src, x, sizeof(x));
277 return (((c & 0x7F) << 24) | (x[0] << 16) | (x[1] << 8) | x[2]);
280 static int
281 fcgi_parse_params(struct fcgi *fcgi, struct evbuffer *src, struct client *clt)
283 char pname[32];
284 char server[HOST_NAME_MAX + 1];
285 char path[PATH_MAX];
286 int nlen, vlen;
288 while (fcgi->fcg_toread > 0) {
289 if ((nlen = parse_len(fcgi, src)) < 0 ||
290 (vlen = parse_len(fcgi, src)) < 0)
291 return (-1);
293 if (fcgi->fcg_toread < nlen + vlen)
294 return (-1);
296 if ((size_t)nlen > sizeof(pname) - 1) {
297 /* ignore this parameter */
298 fcgi->fcg_toread -= nlen - vlen;
299 evbuffer_drain(src, nlen + vlen);
300 continue;
303 fcgi->fcg_toread -= nlen;
304 evbuffer_remove(src, &pname, nlen);
305 pname[nlen] = '\0';
307 if (!strcmp(pname, "SERVER_NAME") &&
308 (size_t)vlen < sizeof(server)) {
309 fcgi->fcg_toread -= vlen;
310 evbuffer_remove(src, &server, vlen);
311 server[vlen] = '\0';
313 if ((clt->clt_server_name = strdup(server)) == NULL)
314 return (-1);
315 log_debug("clt %d: server_name: %s", clt->clt_id,
316 clt->clt_server_name);
317 continue;
320 if (!strcmp(pname, "SCRIPT_NAME") &&
321 (size_t)vlen < sizeof(path)) {
322 fcgi->fcg_toread -= vlen;
323 evbuffer_remove(src, &path, vlen);
324 path[vlen] = '\0';
326 if ((clt->clt_script_name = strdup(path)) == NULL)
327 return (-1);
328 log_debug("clt %d: script_name: %s", clt->clt_id,
329 clt->clt_script_name);
330 continue;
333 if (!strcmp(pname, "PATH_INFO") &&
334 (size_t)vlen < sizeof(path)) {
335 fcgi->fcg_toread -= vlen;
336 evbuffer_remove(src, &path, vlen);
337 path[vlen] = '\0';
339 if ((clt->clt_path_info = strdup(path)) == NULL)
340 return (-1);
341 log_debug("clt %d: path_info: %s", clt->clt_id,
342 clt->clt_path_info);
343 continue;
346 fcgi->fcg_toread -= vlen;
347 evbuffer_drain(src, vlen);
350 return (0);
353 void
354 fcgi_read(struct bufferevent *bev, void *d)
356 struct fcgi *fcgi = d;
357 struct galileo *env = fcgi->fcg_env;
358 struct evbuffer *src = EVBUFFER_INPUT(bev);
359 struct fcgi_header hdr;
360 struct fcgi_begin_req breq;
361 struct client *clt, q;
362 int role;
364 memset(&q, 0, sizeof(q));
366 for (;;) {
367 if (EVBUFFER_LENGTH(src) < (size_t)fcgi->fcg_toread)
368 return;
370 if (fcgi->fcg_want == FCGI_RECORD_HEADER) {
371 fcgi->fcg_want = FCGI_RECORD_BODY;
372 bufferevent_read(bev, &hdr, sizeof(hdr));
374 #ifdef DEBUG
375 log_warnx("header: v=%d t=%d id=%d len=%d p=%d",
376 hdr.version, hdr.type,
377 CAT(hdr.req_id0, hdr.req_id1),
378 CAT(hdr.content_len0, hdr.content_len1),
379 hdr.padding);
380 #endif
382 if (hdr.version != FCGI_VERSION_1) {
383 log_warnx("unknown fastcgi version: %d",
384 hdr.version);
385 fcgi_error(bev, EV_READ, d);
386 return;
389 fcgi->fcg_toread = CAT(hdr.content_len0,
390 hdr.content_len1);
391 if (fcgi->fcg_toread < 0) {
392 log_warnx("invalid record length: %d",
393 fcgi->fcg_toread);
394 fcgi_error(bev, EV_READ, d);
395 return;
398 fcgi->fcg_padding = hdr.padding;
399 if (fcgi->fcg_padding < 0) {
400 log_warnx("invalid padding: %d",
401 fcgi->fcg_padding);
402 fcgi_error(bev, EV_READ, d);
403 return;
406 fcgi->fcg_type = hdr.type;
407 fcgi->fcg_rec_id = CAT(hdr.req_id0, hdr.req_id1);
408 continue;
411 q.clt_id = fcgi->fcg_rec_id;
412 clt = SPLAY_FIND(client_tree, &fcgi->fcg_clients, &q);
414 switch (fcgi->fcg_type) {
415 case FCGI_BEGIN_REQUEST:
416 if (sizeof(breq) != fcgi->fcg_toread) {
417 log_warnx("unexpected size for "
418 "FCGI_BEGIN_REQUEST");
419 fcgi_error(bev, EV_READ, d);
420 return;
423 evbuffer_remove(src, &breq, sizeof(breq));
425 role = CAT(breq.role0, breq.role1);
426 if (role != FCGI_RESPONDER) {
427 log_warnx("unknown fastcgi role: %d",
428 role);
429 if (fcgi_send_end_req(fcgi, fcgi->fcg_rec_id,
430 1, FCGI_UNKNOWN_ROLE) == -1) {
431 fcgi_error(bev, EV_READ, d);
432 return;
434 break;
437 if (!fcgi->fcg_keep_conn) {
438 log_warnx("trying to reuse the fastcgi "
439 "socket without marking it as so.");
440 fcgi_error(bev, EV_READ, d);
441 return;
443 fcgi->fcg_keep_conn = breq.flags & FCGI_KEEP_CONN;
445 if (clt != NULL) {
446 log_warnx("ignoring attemp to re-use an "
447 "active request id (%d)",
448 fcgi->fcg_rec_id);
449 break;
452 if ((clt = calloc(1, sizeof(*clt))) == NULL) {
453 log_warnx("calloc");
454 break;
457 clt->clt_id = fcgi->fcg_rec_id;
458 clt->clt_fd = -1;
459 clt->clt_fcgi = fcgi;
460 SPLAY_INSERT(client_tree, &fcgi->fcg_clients, clt);
461 break;
462 case FCGI_PARAMS:
463 if (clt == NULL) {
464 log_warnx("got FCGI_PARAMS for inactive id "
465 "(%d)", fcgi->fcg_rec_id);
466 evbuffer_drain(src, fcgi->fcg_toread);
467 break;
469 if (fcgi->fcg_toread == 0) {
470 evbuffer_drain(src, fcgi->fcg_toread);
471 proxy_start_request(env, clt);
472 break;
474 if (fcgi_parse_params(fcgi, src, clt) == -1) {
475 log_warnx("fcgi_parse_params failed");
476 fcgi_error(bev, EV_READ, d);
477 return;
479 break;
480 case FCGI_STDIN:
481 /* ignore */
482 evbuffer_drain(src, fcgi->fcg_toread);
483 break;
484 case FCGI_ABORT_REQUEST:
485 if (clt == NULL) {
486 log_warnx("got FCGI_ABORT_REQUEST for inactive"
487 " id (%d)", fcgi->fcg_rec_id);
488 evbuffer_drain(src, fcgi->fcg_toread);
489 break;
491 if (fcgi_end_request(clt, 1) == -1) {
492 /* calls fcgi_error on failure */
493 return;
495 break;
496 default:
497 log_warnx("unknown fastcgi record type %d",
498 fcgi->fcg_type);
499 evbuffer_drain(src, fcgi->fcg_toread);
500 break;
503 /* Prepare for the next record. */
504 evbuffer_drain(src, fcgi->fcg_padding);
505 fcgi->fcg_want = FCGI_RECORD_HEADER;
506 fcgi->fcg_toread = sizeof(struct fcgi_header);
510 void
511 fcgi_write(struct bufferevent *bev, void *d)
513 struct fcgi *fcgi = d;
515 (void)fcgi;
518 void
519 fcgi_error(struct bufferevent *bev, short event, void *d)
521 struct fcgi *fcgi = d;
522 struct galileo *env = fcgi->fcg_env;
523 struct client *clt;
525 log_debug("fcgi failure, shutting down connection (ev: %x)",
526 event);
527 fcgi_inflight_dec(__func__);
529 while ((clt = SPLAY_MIN(client_tree, &fcgi->fcg_clients)) != NULL) {
530 SPLAY_REMOVE(client_tree, &fcgi->fcg_clients, clt);
531 proxy_client_free(clt);
534 close(fcgi->fcg_s);
535 bufferevent_free(fcgi->fcg_bev);
536 SPLAY_REMOVE(fcgi_tree, &env->sc_fcgi_socks, fcgi);
537 free(fcgi);
539 return;
542 int
543 clt_flush(struct client *clt)
545 struct fcgi *fcgi = clt->clt_fcgi;
546 struct bufferevent *bev = fcgi->fcg_bev;
547 struct fcgi_header hdr;
549 if (clt->clt_buflen == 0)
550 return (0);
552 memset(&hdr, 0, sizeof(hdr));
553 hdr.version = FCGI_VERSION_1;
554 hdr.type = FCGI_STDOUT;
555 hdr.req_id0 = (clt->clt_id & 0xFF);
556 hdr.req_id1 = (clt->clt_id >> 8);
557 hdr.content_len0 = (clt->clt_buflen & 0xFF);
558 hdr.content_len1 = (clt->clt_buflen >> 8);
560 if (bufferevent_write(bev, &hdr, sizeof(hdr)) == -1 ||
561 bufferevent_write(bev, clt->clt_buf, clt->clt_buflen) == -1) {
562 fcgi_error(bev, EV_WRITE, fcgi);
563 return (-1);
566 clt->clt_buflen = 0;
568 return (0);
571 int
572 clt_write(struct client *clt, const uint8_t *buf, size_t len)
574 size_t left, copy;
576 while (len > 0) {
577 left = sizeof(clt->clt_buf) - clt->clt_buflen;
578 if (left == 0) {
579 if (clt_flush(clt) == -1)
580 return (-1);
581 left = sizeof(clt->clt_buf);
584 copy = MIN(left, len);
586 memcpy(&clt->clt_buf[clt->clt_buflen], buf, copy);
587 clt->clt_buflen += copy;
588 buf += copy;
589 len -= copy;
592 return (0);
595 int
596 clt_write_bufferevent(struct client *clt, struct bufferevent *bev)
598 struct evbuffer *src = EVBUFFER_INPUT(bev);
599 size_t len, left, copy;
601 len = EVBUFFER_LENGTH(src);
602 while (len > 0) {
603 left = sizeof(clt->clt_buf) - clt->clt_buflen;
604 if (left == 0) {
605 if (clt_flush(clt) == -1)
606 return (-1);
607 left = sizeof(clt->clt_buf);
610 copy = bufferevent_read(bev, &clt->clt_buf[clt->clt_buflen],
611 MIN(left, len));
612 clt->clt_buflen += copy;
614 len = EVBUFFER_LENGTH(src);
617 return (0);
620 int
621 clt_printf(struct client *clt, const char *fmt, ...)
623 struct fcgi *fcgi = clt->clt_fcgi;
624 struct bufferevent *bev = fcgi->fcg_bev;
625 char *str;
626 va_list ap;
627 int r;
629 va_start(ap, fmt);
630 r = vasprintf(&str, fmt, ap);
631 va_end(ap);
632 if (r == -1) {
633 fcgi_error(bev, EV_WRITE, fcgi);
634 return (-1);
637 r = clt_write(clt, str, r);
638 free(str);
639 return (r);
642 int
643 fcgi_cmp(struct fcgi *a, struct fcgi *b)
645 return ((int)a->fcg_id - b->fcg_id);
648 int
649 fcgi_client_cmp(struct client *a, struct client *b)
651 return ((int)a->clt_id - b->clt_id);
654 SPLAY_GENERATE(fcgi_tree, fcgi, fcg_nodes, fcgi_cmp);
655 SPLAY_GENERATE(client_tree, client, clt_nodes, fcgi_client_cmp);