2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
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.
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.
17 #include <sys/queue.h>
19 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
39 #define MIN(a, b) ((a) < (b) ? (a) : (b))
42 unsigned char version;
44 unsigned char req_id1;
45 unsigned char req_id0;
46 unsigned char content_len1;
47 unsigned char content_len0;
48 unsigned char padding;
49 unsigned char reserved;
50 } __attribute__((packed));
53 * number of bytes in a FCGI_HEADER. Future version of the protocol
54 * will not reduce this number.
56 #define FCGI_HEADER_LEN 8
59 * values for the version component
61 #define FCGI_VERSION_1 1
64 * values for the type component
66 #define FCGI_BEGIN_REQUEST 1
67 #define FCGI_ABORT_REQUEST 2
68 #define FCGI_END_REQUEST 3
74 #define FCGI_GET_VALUES 9
75 #define FCGI_GET_VALUES_RESULT 10
76 #define FCGI_UNKNOWN_TYPE 11
77 #define FCGI_MAXTYPE (FCGI_UNKNOWN_TYPE)
79 struct fcgi_begin_req {
83 unsigned char reserved[5];
86 struct fcgi_begin_req_record {
87 struct fcgi_header header;
88 struct fcgi_begin_req body;
94 #define FCGI_KEEP_CONN 1
99 #define FCGI_RESPONDER 1
100 #define FCGI_AUTHORIZER 2
101 #define FCGI_FILTER 3
103 struct fcgi_end_req_body {
104 unsigned char app_status3;
105 unsigned char app_status2;
106 unsigned char app_status1;
107 unsigned char app_status0;
108 unsigned char proto_status;
109 unsigned char reserved[3];
113 * values for proto_status
115 #define FCGI_REQUEST_COMPLETE 0
116 #define FCGI_CANT_MPX_CONN 1
117 #define FCGI_OVERLOADED 2
118 #define FCGI_UNKNOWN_ROLE 3
121 * Variable names for FCGI_GET_VALUES / FCGI_GET_VALUES_RESULT
124 #define FCGI_MAX_CONNS "FCGI_MAX_CONNS"
125 #define FCGI_MAX_REQS "FCGI_MAX_REQS"
126 #define FCGI_MPXS_CONNS "FCGI_MPXS_CONNS"
128 #define CAT(f0, f1) ((f0) + ((f1) << 8))
135 volatile int fcgi_inflight;
138 fcgi_send_end_req(struct fcgi *fcgi, int id, int as, int ps)
140 struct bufferevent *bev = fcgi->fcg_bev;
141 struct fcgi_header hdr;
142 struct fcgi_end_req_body end;
144 memset(&hdr, 0, sizeof(hdr));
145 memset(&end, 0, sizeof(end));
147 hdr.version = FCGI_VERSION_1;
148 hdr.type = FCGI_END_REQUEST;
149 hdr.req_id0 = (id & 0xFF);
150 hdr.req_id1 = (id >> 8);
151 hdr.content_len0 = sizeof(end);
153 end.app_status0 = (unsigned char)as;
154 end.proto_status = (unsigned char)ps;
156 if (bufferevent_write(bev, &hdr, sizeof(hdr)) == -1)
158 if (bufferevent_write(bev, &end, sizeof(end)) == -1)
164 end_request(struct client *clt, int status, int proto_status)
166 struct fcgi *fcgi = clt->clt_fcgi;
169 if (clt_flush(clt) == -1)
172 r = fcgi_send_end_req(fcgi, clt->clt_id, status,
175 fcgi_error(fcgi->fcg_bev, EV_WRITE, fcgi);
179 SPLAY_REMOVE(client_tree, &fcgi->fcg_clients, clt);
180 proxy_client_free(clt);
182 if (!fcgi->fcg_keep_conn)
189 fcgi_end_request(struct client *clt, int status)
191 return (end_request(clt, status, FCGI_REQUEST_COMPLETE));
195 fcgi_abort_request(struct client *clt)
197 return (end_request(clt, 1, FCGI_OVERLOADED));
201 fcgi_inflight_dec(const char *why)
204 log_debug("%s: fcgi inflight decremented, now %d, %s",
205 __func__, fcgi_inflight, why);
209 fcgi_accept(int fd, short event, void *arg)
211 struct galileo *env = arg;
212 struct fcgi *fcgi = NULL;
214 struct sockaddr_storage ss;
217 event_add(&env->sc_evpause, NULL);
218 if ((event & EV_TIMEOUT))
222 if ((s = accept_reserve(env->sc_sock_fd, (struct sockaddr *)&ss,
223 &slen, FD_RESERVE, &fcgi_inflight)) == -1) {
225 * Pause accept if we are out of file descriptors, or
226 * libevent will haunt us here too.
228 if (errno == ENFILE || errno == EMFILE) {
229 struct timeval evtpause = { 1, 0 };
231 event_del(&env->sc_evsock);
232 evtimer_add(&env->sc_evpause, &evtpause);
233 log_debug("%s: deferring connections", __func__);
238 if ((fcgi = calloc(1, sizeof(*fcgi))) == NULL)
241 fcgi->fcg_id = ++proxy_fcg_id;
244 fcgi->fcg_want = FCGI_RECORD_HEADER;
245 fcgi->fcg_toread = sizeof(struct fcgi_header);
246 SPLAY_INIT(&fcgi->fcg_clients);
248 /* assume it's enabled until we get a FCGI_BEGIN_REQUEST */
249 fcgi->fcg_keep_conn = 1;
251 fcgi->fcg_bev = bufferevent_new(fcgi->fcg_s, fcgi_read, fcgi_write,
253 if (fcgi->fcg_bev == NULL)
256 bufferevent_enable(fcgi->fcg_bev, EV_READ | EV_WRITE);
263 fcgi_inflight_dec(__func__);
268 parse_len(struct fcgi *fcgi, struct evbuffer *src)
270 unsigned char c, x[3];
273 evbuffer_remove(src, &c, 1);
277 if (fcgi->fcg_toread < 3)
280 fcgi->fcg_toread -= 3;
281 evbuffer_remove(src, x, sizeof(x));
282 return (((c & 0x7F) << 24) | (x[0] << 16) | (x[1] << 8) | x[2]);
286 fcgi_parse_params(struct fcgi *fcgi, struct evbuffer *src, struct client *clt)
289 char server[HOST_NAME_MAX + 1];
291 char query[GEMINI_MAXLEN];
295 while (fcgi->fcg_toread > 0) {
296 if ((nlen = parse_len(fcgi, src)) < 0 ||
297 (vlen = parse_len(fcgi, src)) < 0)
300 if (fcgi->fcg_toread < nlen + vlen)
303 if ((size_t)nlen > sizeof(pname) - 1) {
304 /* ignore this parameter */
305 fcgi->fcg_toread -= nlen - vlen;
306 evbuffer_drain(src, nlen + vlen);
310 fcgi->fcg_toread -= nlen;
311 evbuffer_remove(src, &pname, nlen);
314 if (!strcmp(pname, "SERVER_NAME") &&
315 (size_t)vlen < sizeof(server)) {
316 fcgi->fcg_toread -= vlen;
317 evbuffer_remove(src, &server, vlen);
320 free(clt->clt_server_name);
321 if ((clt->clt_server_name = strdup(server)) == NULL)
323 DPRINTF("clt %d: server_name: %s", clt->clt_id,
324 clt->clt_server_name);
328 if (!strcmp(pname, "SCRIPT_NAME") &&
329 (size_t)vlen < sizeof(path)) {
330 fcgi->fcg_toread -= vlen;
331 evbuffer_remove(src, &path, vlen);
334 free(clt->clt_script_name);
335 clt->clt_script_name = NULL;
337 if (vlen == 0 || path[vlen - 1] != '/')
338 asprintf(&clt->clt_script_name, "%s/", path);
340 clt->clt_script_name = strdup(path);
342 if (clt->clt_script_name == NULL)
345 DPRINTF("clt %d: script_name: %s", clt->clt_id,
346 clt->clt_script_name);
350 if (!strcmp(pname, "PATH_INFO") &&
351 (size_t)vlen < sizeof(path)) {
352 fcgi->fcg_toread -= vlen;
353 evbuffer_remove(src, &path, vlen);
356 free(clt->clt_path_info);
357 clt->clt_path_info = NULL;
360 asprintf(&clt->clt_path_info, "/%s", path);
362 clt->clt_path_info = strdup(path);
364 if (clt->clt_path_info == NULL)
367 DPRINTF("clt %d: path_info: %s", clt->clt_id,
372 if (!strcmp(pname, "QUERY_STRING") &&
373 (size_t)vlen < sizeof(query) &&
375 fcgi->fcg_toread -= vlen;
376 evbuffer_remove(src, &query, vlen);
379 free(clt->clt_query);
380 if ((clt->clt_query = strdup(query)) == NULL)
383 DPRINTF("clt %d: query: %s", clt->clt_id,
388 if (!strcmp(pname, "REQUEST_METHOD") &&
389 (size_t)vlen < sizeof(method)) {
390 fcgi->fcg_toread -= vlen;
391 evbuffer_remove(src, &method, vlen);
394 if (!strcasecmp(method, "GET"))
395 clt->clt_method = METHOD_GET;
396 if (!strcasecmp(method, "POST"))
397 clt->clt_method = METHOD_POST;
402 fcgi->fcg_toread -= vlen;
403 evbuffer_drain(src, vlen);
410 fcgi_parse_form(struct fcgi *fcgi, struct client *clt, struct evbuffer *src)
416 if (fcgi->fcg_toread == 0) {
417 clt->clt_bodydone = 1;
418 return (proxy_start_request(fcgi->fcg_env, clt));
421 len = sizeof(tmp) - 1;
422 if (len > (size_t)fcgi->fcg_toread)
423 len = fcgi->fcg_toread;
425 fcgi->fcg_toread -= len;
426 evbuffer_remove(src, &tmp, len);
429 if (clt->clt_bodydone)
432 if (clt->clt_bodylen > GEMINI_MAXLEN) {
434 clt->clt_body = NULL;
438 if (clt->clt_body != NULL) {
439 if ((a = strchr(tmp, '&')) != NULL ||
440 (a = strchr(tmp, '\r')) != NULL) {
442 clt->clt_bodydone = 1;
446 if (asprintf(&clt->clt_body, "%s%s", a, tmp) == -1) {
448 clt->clt_body = NULL;
451 clt->clt_bodylen += strlen(tmp);
455 if (clt->clt_bodylen != 0)
456 return (0); /* EOM situation */
458 if ((s = strstr(tmp, "q=")) == NULL)
462 if ((a = strchr(s, '&')) != NULL ||
463 (a = strchr(s, '\r')) != NULL) {
465 clt->clt_bodydone = 1;
468 clt->clt_bodylen = strlen(s);
469 if ((clt->clt_body = strdup(s)) == NULL)
476 fcgi_read(struct bufferevent *bev, void *d)
478 struct fcgi *fcgi = d;
479 struct galileo *env = fcgi->fcg_env;
480 struct evbuffer *src = EVBUFFER_INPUT(bev);
481 struct fcgi_header hdr;
482 struct fcgi_begin_req breq;
483 struct client *clt, q;
486 memset(&q, 0, sizeof(q));
489 if (EVBUFFER_LENGTH(src) < (size_t)fcgi->fcg_toread)
492 if (fcgi->fcg_want == FCGI_RECORD_HEADER) {
493 fcgi->fcg_want = FCGI_RECORD_BODY;
494 bufferevent_read(bev, &hdr, sizeof(hdr));
496 DPRINTF("header: v=%d t=%d id=%d len=%d p=%d",
497 hdr.version, hdr.type,
498 CAT(hdr.req_id0, hdr.req_id1),
499 CAT(hdr.content_len0, hdr.content_len1),
502 if (hdr.version != FCGI_VERSION_1) {
503 log_warnx("unknown fastcgi version: %d",
505 fcgi_error(bev, EV_READ, d);
509 fcgi->fcg_toread = CAT(hdr.content_len0,
511 if (fcgi->fcg_toread < 0) {
512 log_warnx("invalid record length: %d",
514 fcgi_error(bev, EV_READ, d);
518 fcgi->fcg_padding = hdr.padding;
519 if (fcgi->fcg_padding < 0) {
520 log_warnx("invalid padding: %d",
522 fcgi_error(bev, EV_READ, d);
526 fcgi->fcg_type = hdr.type;
527 fcgi->fcg_rec_id = CAT(hdr.req_id0, hdr.req_id1);
531 q.clt_id = fcgi->fcg_rec_id;
532 clt = SPLAY_FIND(client_tree, &fcgi->fcg_clients, &q);
534 switch (fcgi->fcg_type) {
535 case FCGI_BEGIN_REQUEST:
536 if (sizeof(breq) != fcgi->fcg_toread) {
537 log_warnx("unexpected size for "
538 "FCGI_BEGIN_REQUEST");
539 fcgi_error(bev, EV_READ, d);
543 evbuffer_remove(src, &breq, sizeof(breq));
545 role = CAT(breq.role0, breq.role1);
546 if (role != FCGI_RESPONDER) {
547 log_warnx("unknown fastcgi role: %d",
549 if (fcgi_send_end_req(fcgi, fcgi->fcg_rec_id,
550 1, FCGI_UNKNOWN_ROLE) == -1) {
551 fcgi_error(bev, EV_READ, d);
557 if (!fcgi->fcg_keep_conn) {
558 log_warnx("trying to reuse the fastcgi "
559 "socket without marking it as so.");
560 fcgi_error(bev, EV_READ, d);
563 fcgi->fcg_keep_conn = breq.flags & FCGI_KEEP_CONN;
566 log_warnx("ignoring attemp to re-use an "
567 "active request id (%d)",
572 if ((clt = calloc(1, sizeof(*clt))) == NULL) {
577 clt->clt_tp = template(clt, clt_tp_puts, clt_tp_putc);
578 if (clt->clt_tp == NULL) {
580 log_warn("template");
584 clt->clt_id = fcgi->fcg_rec_id;
586 clt->clt_fcgi = fcgi;
587 SPLAY_INSERT(client_tree, &fcgi->fcg_clients, clt);
591 log_warnx("got FCGI_PARAMS for inactive id "
592 "(%d)", fcgi->fcg_rec_id);
593 evbuffer_drain(src, fcgi->fcg_toread);
596 if (fcgi->fcg_toread == 0) {
597 evbuffer_drain(src, fcgi->fcg_toread);
598 if (clt->clt_method == METHOD_GET) {
599 if (proxy_start_request(env, clt)
605 if (fcgi_parse_params(fcgi, src, clt) == -1) {
606 log_warnx("fcgi_parse_params failed");
607 fcgi_error(bev, EV_READ, d);
613 clt->clt_method != METHOD_POST) {
614 evbuffer_drain(src, fcgi->fcg_toread);
617 if (fcgi_parse_form(fcgi, clt, src) == -1)
620 case FCGI_ABORT_REQUEST:
622 log_warnx("got FCGI_ABORT_REQUEST for inactive"
623 " id (%d)", fcgi->fcg_rec_id);
624 evbuffer_drain(src, fcgi->fcg_toread);
627 if (fcgi_end_request(clt, 1) == -1) {
628 /* calls fcgi_error on failure */
633 log_warnx("unknown fastcgi record type %d",
635 evbuffer_drain(src, fcgi->fcg_toread);
639 /* Prepare for the next record. */
640 evbuffer_drain(src, fcgi->fcg_padding);
641 fcgi->fcg_want = FCGI_RECORD_HEADER;
642 fcgi->fcg_toread = sizeof(struct fcgi_header);
647 fcgi_write(struct bufferevent *bev, void *d)
649 struct fcgi *fcgi = d;
650 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
652 if (fcgi->fcg_done && EVBUFFER_LENGTH(out) == 0)
653 fcgi_error(bev, EVBUFFER_EOF, fcgi);
657 fcgi_error(struct bufferevent *bev, short event, void *d)
659 struct fcgi *fcgi = d;
660 struct galileo *env = fcgi->fcg_env;
663 log_debug("fcgi failure, shutting down connection (ev: %x)",
665 fcgi_inflight_dec(__func__);
667 while ((clt = SPLAY_MIN(client_tree, &fcgi->fcg_clients)) != NULL) {
668 SPLAY_REMOVE(client_tree, &fcgi->fcg_clients, clt);
669 proxy_client_free(clt);
672 SPLAY_REMOVE(fcgi_tree, &env->sc_fcgi_socks, fcgi);
679 fcgi_free(struct fcgi *fcgi)
682 bufferevent_free(fcgi->fcg_bev);
687 clt_flush(struct client *clt)
689 struct fcgi *fcgi = clt->clt_fcgi;
690 struct bufferevent *bev = fcgi->fcg_bev;
691 struct fcgi_header hdr;
693 if (clt->clt_buflen == 0)
696 memset(&hdr, 0, sizeof(hdr));
697 hdr.version = FCGI_VERSION_1;
698 hdr.type = FCGI_STDOUT;
699 hdr.req_id0 = (clt->clt_id & 0xFF);
700 hdr.req_id1 = (clt->clt_id >> 8);
701 hdr.content_len0 = (clt->clt_buflen & 0xFF);
702 hdr.content_len1 = (clt->clt_buflen >> 8);
704 if (bufferevent_write(bev, &hdr, sizeof(hdr)) == -1 ||
705 bufferevent_write(bev, clt->clt_buf, clt->clt_buflen) == -1) {
706 fcgi_error(bev, EV_WRITE, fcgi);
716 clt_write(struct client *clt, const uint8_t *buf, size_t len)
721 left = sizeof(clt->clt_buf) - clt->clt_buflen;
723 if (clt_flush(clt) == -1)
725 left = sizeof(clt->clt_buf);
728 copy = MIN(left, len);
730 memcpy(&clt->clt_buf[clt->clt_buflen], buf, copy);
731 clt->clt_buflen += copy;
740 clt_putc(struct client *clt, char ch)
742 return (clt_write(clt, &ch, 1));
746 clt_puts(struct client *clt, const char *str)
748 return (clt_write(clt, str, strlen(str)));
752 clt_write_bufferevent(struct client *clt, struct bufferevent *bev)
754 struct evbuffer *src = EVBUFFER_INPUT(bev);
755 size_t len, left, copy;
757 len = EVBUFFER_LENGTH(src);
759 left = sizeof(clt->clt_buf) - clt->clt_buflen;
761 if (clt_flush(clt) == -1)
763 left = sizeof(clt->clt_buf);
766 copy = bufferevent_read(bev, &clt->clt_buf[clt->clt_buflen],
768 clt->clt_buflen += copy;
770 len = EVBUFFER_LENGTH(src);
777 clt_printf(struct client *clt, const char *fmt, ...)
779 struct fcgi *fcgi = clt->clt_fcgi;
780 struct bufferevent *bev = fcgi->fcg_bev;
786 r = vasprintf(&str, fmt, ap);
789 fcgi_error(bev, EV_WRITE, fcgi);
793 r = clt_write(clt, str, r);
799 clt_tp_puts(struct template *tp, const char *str)
801 struct client *clt = tp->tp_arg;
803 if (clt_puts(clt, str) == -1)
810 clt_tp_putc(struct template *tp, int c)
812 struct client *clt = tp->tp_arg;
814 if (clt_putc(clt, c) == -1)
821 fcgi_cmp(struct fcgi *a, struct fcgi *b)
823 return ((int)a->fcg_id - b->fcg_id);
827 fcgi_client_cmp(struct client *a, struct client *b)
829 return ((int)a->clt_id - b->clt_id);
832 SPLAY_GENERATE(fcgi_tree, fcgi, fcg_nodes, fcgi_cmp);
833 SPLAY_GENERATE(client_tree, client, clt_nodes, fcgi_client_cmp);