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 log_debug("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 log_debug("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 log_debug("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 log_debug("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));
497 log_warnx("header: v=%d t=%d id=%d len=%d p=%d",
498 hdr.version, hdr.type,
499 CAT(hdr.req_id0, hdr.req_id1),
500 CAT(hdr.content_len0, hdr.content_len1),
504 if (hdr.version != FCGI_VERSION_1) {
505 log_warnx("unknown fastcgi version: %d",
507 fcgi_error(bev, EV_READ, d);
511 fcgi->fcg_toread = CAT(hdr.content_len0,
513 if (fcgi->fcg_toread < 0) {
514 log_warnx("invalid record length: %d",
516 fcgi_error(bev, EV_READ, d);
520 fcgi->fcg_padding = hdr.padding;
521 if (fcgi->fcg_padding < 0) {
522 log_warnx("invalid padding: %d",
524 fcgi_error(bev, EV_READ, d);
528 fcgi->fcg_type = hdr.type;
529 fcgi->fcg_rec_id = CAT(hdr.req_id0, hdr.req_id1);
533 q.clt_id = fcgi->fcg_rec_id;
534 clt = SPLAY_FIND(client_tree, &fcgi->fcg_clients, &q);
536 switch (fcgi->fcg_type) {
537 case FCGI_BEGIN_REQUEST:
538 if (sizeof(breq) != fcgi->fcg_toread) {
539 log_warnx("unexpected size for "
540 "FCGI_BEGIN_REQUEST");
541 fcgi_error(bev, EV_READ, d);
545 evbuffer_remove(src, &breq, sizeof(breq));
547 role = CAT(breq.role0, breq.role1);
548 if (role != FCGI_RESPONDER) {
549 log_warnx("unknown fastcgi role: %d",
551 if (fcgi_send_end_req(fcgi, fcgi->fcg_rec_id,
552 1, FCGI_UNKNOWN_ROLE) == -1) {
553 fcgi_error(bev, EV_READ, d);
559 if (!fcgi->fcg_keep_conn) {
560 log_warnx("trying to reuse the fastcgi "
561 "socket without marking it as so.");
562 fcgi_error(bev, EV_READ, d);
565 fcgi->fcg_keep_conn = breq.flags & FCGI_KEEP_CONN;
568 log_warnx("ignoring attemp to re-use an "
569 "active request id (%d)",
574 if ((clt = calloc(1, sizeof(*clt))) == NULL) {
579 clt->clt_tp = template(clt, clt_tp_puts, clt_tp_putc);
580 if (clt->clt_tp == NULL) {
582 log_warn("template");
586 clt->clt_id = fcgi->fcg_rec_id;
588 clt->clt_fcgi = fcgi;
589 SPLAY_INSERT(client_tree, &fcgi->fcg_clients, clt);
593 log_warnx("got FCGI_PARAMS for inactive id "
594 "(%d)", fcgi->fcg_rec_id);
595 evbuffer_drain(src, fcgi->fcg_toread);
598 if (fcgi->fcg_toread == 0) {
599 evbuffer_drain(src, fcgi->fcg_toread);
600 if (clt->clt_method == METHOD_GET) {
601 if (proxy_start_request(env, clt)
607 if (fcgi_parse_params(fcgi, src, clt) == -1) {
608 log_warnx("fcgi_parse_params failed");
609 fcgi_error(bev, EV_READ, d);
615 clt->clt_method != METHOD_POST) {
616 evbuffer_drain(src, fcgi->fcg_toread);
619 if (fcgi_parse_form(fcgi, clt, src) == -1)
622 case FCGI_ABORT_REQUEST:
624 log_warnx("got FCGI_ABORT_REQUEST for inactive"
625 " id (%d)", fcgi->fcg_rec_id);
626 evbuffer_drain(src, fcgi->fcg_toread);
629 if (fcgi_end_request(clt, 1) == -1) {
630 /* calls fcgi_error on failure */
635 log_warnx("unknown fastcgi record type %d",
637 evbuffer_drain(src, fcgi->fcg_toread);
641 /* Prepare for the next record. */
642 evbuffer_drain(src, fcgi->fcg_padding);
643 fcgi->fcg_want = FCGI_RECORD_HEADER;
644 fcgi->fcg_toread = sizeof(struct fcgi_header);
649 fcgi_write(struct bufferevent *bev, void *d)
651 struct fcgi *fcgi = d;
652 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
654 if (fcgi->fcg_done && EVBUFFER_LENGTH(out) == 0)
655 fcgi_error(bev, EVBUFFER_EOF, fcgi);
659 fcgi_error(struct bufferevent *bev, short event, void *d)
661 struct fcgi *fcgi = d;
662 struct galileo *env = fcgi->fcg_env;
665 log_debug("fcgi failure, shutting down connection (ev: %x)",
667 fcgi_inflight_dec(__func__);
669 while ((clt = SPLAY_MIN(client_tree, &fcgi->fcg_clients)) != NULL) {
670 SPLAY_REMOVE(client_tree, &fcgi->fcg_clients, clt);
671 proxy_client_free(clt);
674 SPLAY_REMOVE(fcgi_tree, &env->sc_fcgi_socks, fcgi);
681 fcgi_free(struct fcgi *fcgi)
684 bufferevent_free(fcgi->fcg_bev);
689 clt_flush(struct client *clt)
691 struct fcgi *fcgi = clt->clt_fcgi;
692 struct bufferevent *bev = fcgi->fcg_bev;
693 struct fcgi_header hdr;
695 if (clt->clt_buflen == 0)
698 memset(&hdr, 0, sizeof(hdr));
699 hdr.version = FCGI_VERSION_1;
700 hdr.type = FCGI_STDOUT;
701 hdr.req_id0 = (clt->clt_id & 0xFF);
702 hdr.req_id1 = (clt->clt_id >> 8);
703 hdr.content_len0 = (clt->clt_buflen & 0xFF);
704 hdr.content_len1 = (clt->clt_buflen >> 8);
706 if (bufferevent_write(bev, &hdr, sizeof(hdr)) == -1 ||
707 bufferevent_write(bev, clt->clt_buf, clt->clt_buflen) == -1) {
708 fcgi_error(bev, EV_WRITE, fcgi);
718 clt_write(struct client *clt, const uint8_t *buf, size_t len)
723 left = sizeof(clt->clt_buf) - clt->clt_buflen;
725 if (clt_flush(clt) == -1)
727 left = sizeof(clt->clt_buf);
730 copy = MIN(left, len);
732 memcpy(&clt->clt_buf[clt->clt_buflen], buf, copy);
733 clt->clt_buflen += copy;
742 clt_putc(struct client *clt, char ch)
744 return (clt_write(clt, &ch, 1));
748 clt_puts(struct client *clt, const char *str)
750 return (clt_write(clt, str, strlen(str)));
754 clt_write_bufferevent(struct client *clt, struct bufferevent *bev)
756 struct evbuffer *src = EVBUFFER_INPUT(bev);
757 size_t len, left, copy;
759 len = EVBUFFER_LENGTH(src);
761 left = sizeof(clt->clt_buf) - clt->clt_buflen;
763 if (clt_flush(clt) == -1)
765 left = sizeof(clt->clt_buf);
768 copy = bufferevent_read(bev, &clt->clt_buf[clt->clt_buflen],
770 clt->clt_buflen += copy;
772 len = EVBUFFER_LENGTH(src);
779 clt_printf(struct client *clt, const char *fmt, ...)
781 struct fcgi *fcgi = clt->clt_fcgi;
782 struct bufferevent *bev = fcgi->fcg_bev;
788 r = vasprintf(&str, fmt, ap);
791 fcgi_error(bev, EV_WRITE, fcgi);
795 r = clt_write(clt, str, r);
801 clt_tp_puts(struct template *tp, const char *str)
803 struct client *clt = tp->tp_arg;
805 if (clt_puts(clt, str) == -1) {
814 clt_tp_putc(struct template *tp, int c)
816 struct client *clt = tp->tp_arg;
818 if (clt_putc(clt, c) == -1) {
827 fcgi_cmp(struct fcgi *a, struct fcgi *b)
829 return ((int)a->fcg_id - b->fcg_id);
833 fcgi_client_cmp(struct client *a, struct client *b)
835 return ((int)a->clt_id - b->clt_id);
838 SPLAY_GENERATE(fcgi_tree, fcgi, fcg_nodes, fcgi_cmp);
839 SPLAY_GENERATE(client_tree, client, clt_nodes, fcgi_client_cmp);