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);
181 if (!fcgi->fcg_keep_conn)
182 fcgi->fcg_done = 1;
184 return (0);
187 int
188 fcgi_end_request(struct client *clt, int status)
190 return (end_request(clt, status, FCGI_REQUEST_COMPLETE));
193 int
194 fcgi_abort_request(struct client *clt)
196 return (end_request(clt, 1, FCGI_OVERLOADED));
199 static void
200 fcgi_inflight_dec(const char *why)
202 fcgi_inflight--;
203 log_debug("%s: fcgi inflight decremented, now %d, %s",
204 __func__, fcgi_inflight, why);
207 void
208 fcgi_accept(int fd, short event, void *arg)
210 struct galileo *env = arg;
211 struct fcgi *fcgi = NULL;
212 socklen_t slen;
213 struct sockaddr_storage ss;
214 int s = -1;
216 event_add(&env->sc_evpause, NULL);
217 if ((event & EV_TIMEOUT))
218 return;
220 slen = sizeof(ss);
221 if ((s = accept_reserve(env->sc_sock_fd, (struct sockaddr *)&ss,
222 &slen, FD_RESERVE, &fcgi_inflight)) == -1) {
223 /*
224 * Pause accept if we are out of file descriptors, or
225 * libevent will haunt us here too.
226 */
227 if (errno == ENFILE || errno == EMFILE) {
228 struct timeval evtpause = { 1, 0 };
230 event_del(&env->sc_evsock);
231 evtimer_add(&env->sc_evpause, &evtpause);
232 log_debug("%s: deferring connections", __func__);
234 return;
237 if ((fcgi = calloc(1, sizeof(*fcgi))) == NULL)
238 goto err;
240 fcgi->fcg_id = ++proxy_fcg_id;
241 fcgi->fcg_s = s;
242 fcgi->fcg_env = env;
243 fcgi->fcg_want = FCGI_RECORD_HEADER;
244 fcgi->fcg_toread = sizeof(struct fcgi_header);
245 SPLAY_INIT(&fcgi->fcg_clients);
247 /* assume it's enabled until we get a FCGI_BEGIN_REQUEST */
248 fcgi->fcg_keep_conn = 1;
250 fcgi->fcg_bev = bufferevent_new(fcgi->fcg_s, fcgi_read, fcgi_write,
251 fcgi_error, fcgi);
252 if (fcgi->fcg_bev == NULL)
253 goto err;
255 bufferevent_enable(fcgi->fcg_bev, EV_READ | EV_WRITE);
256 return;
258 err:
259 if (s != -1) {
260 close(s);
261 free(fcgi);
262 fcgi_inflight_dec(__func__);
266 static int
267 parse_len(struct fcgi *fcgi, struct evbuffer *src)
269 unsigned char c, x[3];
271 fcgi->fcg_toread--;
272 evbuffer_remove(src, &c, 1);
273 if (c >> 7 == 0)
274 return (c);
276 if (fcgi->fcg_toread < 3)
277 return (-1);
279 fcgi->fcg_toread -= 3;
280 evbuffer_remove(src, x, sizeof(x));
281 return (((c & 0x7F) << 24) | (x[0] << 16) | (x[1] << 8) | x[2]);
284 static int
285 fcgi_parse_params(struct fcgi *fcgi, struct evbuffer *src, struct client *clt)
287 char pname[32];
288 char server[HOST_NAME_MAX + 1];
289 char path[PATH_MAX];
290 int nlen, vlen;
292 while (fcgi->fcg_toread > 0) {
293 if ((nlen = parse_len(fcgi, src)) < 0 ||
294 (vlen = parse_len(fcgi, src)) < 0)
295 return (-1);
297 if (fcgi->fcg_toread < nlen + vlen)
298 return (-1);
300 if ((size_t)nlen > sizeof(pname) - 1) {
301 /* ignore this parameter */
302 fcgi->fcg_toread -= nlen - vlen;
303 evbuffer_drain(src, nlen + vlen);
304 continue;
307 fcgi->fcg_toread -= nlen;
308 evbuffer_remove(src, &pname, nlen);
309 pname[nlen] = '\0';
311 if (!strcmp(pname, "SERVER_NAME") &&
312 (size_t)vlen < sizeof(server)) {
313 fcgi->fcg_toread -= vlen;
314 evbuffer_remove(src, &server, vlen);
315 server[vlen] = '\0';
317 if ((clt->clt_server_name = strdup(server)) == NULL)
318 return (-1);
319 log_debug("clt %d: server_name: %s", clt->clt_id,
320 clt->clt_server_name);
321 continue;
324 if (!strcmp(pname, "SCRIPT_NAME") &&
325 (size_t)vlen < sizeof(path)) {
326 fcgi->fcg_toread -= vlen;
327 evbuffer_remove(src, &path, vlen);
328 path[vlen] = '\0';
330 if ((clt->clt_script_name = strdup(path)) == NULL)
331 return (-1);
332 log_debug("clt %d: script_name: %s", clt->clt_id,
333 clt->clt_script_name);
334 continue;
337 if (!strcmp(pname, "PATH_INFO") &&
338 (size_t)vlen < sizeof(path)) {
339 fcgi->fcg_toread -= vlen;
340 evbuffer_remove(src, &path, vlen);
341 path[vlen] = '\0';
343 if (vlen == 0)
344 (void) strlcpy(path, "/", sizeof(path));
346 if ((clt->clt_path_info = strdup(path)) == NULL)
347 return (-1);
348 log_debug("clt %d: path_info: %s", clt->clt_id,
349 clt->clt_path_info);
350 continue;
353 fcgi->fcg_toread -= vlen;
354 evbuffer_drain(src, vlen);
357 return (0);
360 void
361 fcgi_read(struct bufferevent *bev, void *d)
363 struct fcgi *fcgi = d;
364 struct galileo *env = fcgi->fcg_env;
365 struct evbuffer *src = EVBUFFER_INPUT(bev);
366 struct fcgi_header hdr;
367 struct fcgi_begin_req breq;
368 struct client *clt, q;
369 int role;
371 memset(&q, 0, sizeof(q));
373 for (;;) {
374 if (EVBUFFER_LENGTH(src) < (size_t)fcgi->fcg_toread)
375 return;
377 if (fcgi->fcg_want == FCGI_RECORD_HEADER) {
378 fcgi->fcg_want = FCGI_RECORD_BODY;
379 bufferevent_read(bev, &hdr, sizeof(hdr));
381 #ifdef DEBUG
382 log_warnx("header: v=%d t=%d id=%d len=%d p=%d",
383 hdr.version, hdr.type,
384 CAT(hdr.req_id0, hdr.req_id1),
385 CAT(hdr.content_len0, hdr.content_len1),
386 hdr.padding);
387 #endif
389 if (hdr.version != FCGI_VERSION_1) {
390 log_warnx("unknown fastcgi version: %d",
391 hdr.version);
392 fcgi_error(bev, EV_READ, d);
393 return;
396 fcgi->fcg_toread = CAT(hdr.content_len0,
397 hdr.content_len1);
398 if (fcgi->fcg_toread < 0) {
399 log_warnx("invalid record length: %d",
400 fcgi->fcg_toread);
401 fcgi_error(bev, EV_READ, d);
402 return;
405 fcgi->fcg_padding = hdr.padding;
406 if (fcgi->fcg_padding < 0) {
407 log_warnx("invalid padding: %d",
408 fcgi->fcg_padding);
409 fcgi_error(bev, EV_READ, d);
410 return;
413 fcgi->fcg_type = hdr.type;
414 fcgi->fcg_rec_id = CAT(hdr.req_id0, hdr.req_id1);
415 continue;
418 q.clt_id = fcgi->fcg_rec_id;
419 clt = SPLAY_FIND(client_tree, &fcgi->fcg_clients, &q);
421 switch (fcgi->fcg_type) {
422 case FCGI_BEGIN_REQUEST:
423 if (sizeof(breq) != fcgi->fcg_toread) {
424 log_warnx("unexpected size for "
425 "FCGI_BEGIN_REQUEST");
426 fcgi_error(bev, EV_READ, d);
427 return;
430 evbuffer_remove(src, &breq, sizeof(breq));
432 role = CAT(breq.role0, breq.role1);
433 if (role != FCGI_RESPONDER) {
434 log_warnx("unknown fastcgi role: %d",
435 role);
436 if (fcgi_send_end_req(fcgi, fcgi->fcg_rec_id,
437 1, FCGI_UNKNOWN_ROLE) == -1) {
438 fcgi_error(bev, EV_READ, d);
439 return;
441 break;
444 if (!fcgi->fcg_keep_conn) {
445 log_warnx("trying to reuse the fastcgi "
446 "socket without marking it as so.");
447 fcgi_error(bev, EV_READ, d);
448 return;
450 fcgi->fcg_keep_conn = breq.flags & FCGI_KEEP_CONN;
452 if (clt != NULL) {
453 log_warnx("ignoring attemp to re-use an "
454 "active request id (%d)",
455 fcgi->fcg_rec_id);
456 break;
459 if ((clt = calloc(1, sizeof(*clt))) == NULL) {
460 log_warnx("calloc");
461 break;
464 clt->clt_id = fcgi->fcg_rec_id;
465 clt->clt_fd = -1;
466 clt->clt_fcgi = fcgi;
467 SPLAY_INSERT(client_tree, &fcgi->fcg_clients, clt);
468 break;
469 case FCGI_PARAMS:
470 if (clt == NULL) {
471 log_warnx("got FCGI_PARAMS for inactive id "
472 "(%d)", fcgi->fcg_rec_id);
473 evbuffer_drain(src, fcgi->fcg_toread);
474 break;
476 if (fcgi->fcg_toread == 0) {
477 evbuffer_drain(src, fcgi->fcg_toread);
478 proxy_start_request(env, clt);
479 break;
481 if (fcgi_parse_params(fcgi, src, clt) == -1) {
482 log_warnx("fcgi_parse_params failed");
483 fcgi_error(bev, EV_READ, d);
484 return;
486 break;
487 case FCGI_STDIN:
488 /* ignore */
489 evbuffer_drain(src, fcgi->fcg_toread);
490 break;
491 case FCGI_ABORT_REQUEST:
492 if (clt == NULL) {
493 log_warnx("got FCGI_ABORT_REQUEST for inactive"
494 " id (%d)", fcgi->fcg_rec_id);
495 evbuffer_drain(src, fcgi->fcg_toread);
496 break;
498 if (fcgi_end_request(clt, 1) == -1) {
499 /* calls fcgi_error on failure */
500 return;
502 break;
503 default:
504 log_warnx("unknown fastcgi record type %d",
505 fcgi->fcg_type);
506 evbuffer_drain(src, fcgi->fcg_toread);
507 break;
510 /* Prepare for the next record. */
511 evbuffer_drain(src, fcgi->fcg_padding);
512 fcgi->fcg_want = FCGI_RECORD_HEADER;
513 fcgi->fcg_toread = sizeof(struct fcgi_header);
517 void
518 fcgi_write(struct bufferevent *bev, void *d)
520 struct fcgi *fcgi = d;
521 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
523 if (fcgi->fcg_done && EVBUFFER_LENGTH(out) == 0)
524 fcgi_error(bev, EVBUFFER_EOF, fcgi);
527 void
528 fcgi_error(struct bufferevent *bev, short event, void *d)
530 struct fcgi *fcgi = d;
531 struct galileo *env = fcgi->fcg_env;
532 struct client *clt;
534 log_debug("fcgi failure, shutting down connection (ev: %x)",
535 event);
536 fcgi_inflight_dec(__func__);
538 while ((clt = SPLAY_MIN(client_tree, &fcgi->fcg_clients)) != NULL) {
539 SPLAY_REMOVE(client_tree, &fcgi->fcg_clients, clt);
540 proxy_client_free(clt);
543 close(fcgi->fcg_s);
544 bufferevent_free(fcgi->fcg_bev);
545 SPLAY_REMOVE(fcgi_tree, &env->sc_fcgi_socks, fcgi);
546 free(fcgi);
548 return;
551 int
552 clt_flush(struct client *clt)
554 struct fcgi *fcgi = clt->clt_fcgi;
555 struct bufferevent *bev = fcgi->fcg_bev;
556 struct fcgi_header hdr;
558 if (clt->clt_buflen == 0)
559 return (0);
561 memset(&hdr, 0, sizeof(hdr));
562 hdr.version = FCGI_VERSION_1;
563 hdr.type = FCGI_STDOUT;
564 hdr.req_id0 = (clt->clt_id & 0xFF);
565 hdr.req_id1 = (clt->clt_id >> 8);
566 hdr.content_len0 = (clt->clt_buflen & 0xFF);
567 hdr.content_len1 = (clt->clt_buflen >> 8);
569 if (bufferevent_write(bev, &hdr, sizeof(hdr)) == -1 ||
570 bufferevent_write(bev, clt->clt_buf, clt->clt_buflen) == -1) {
571 fcgi_error(bev, EV_WRITE, fcgi);
572 return (-1);
575 clt->clt_buflen = 0;
577 return (0);
580 int
581 clt_write(struct client *clt, const uint8_t *buf, size_t len)
583 size_t left, copy;
585 while (len > 0) {
586 left = sizeof(clt->clt_buf) - clt->clt_buflen;
587 if (left == 0) {
588 if (clt_flush(clt) == -1)
589 return (-1);
590 left = sizeof(clt->clt_buf);
593 copy = MIN(left, len);
595 memcpy(&clt->clt_buf[clt->clt_buflen], buf, copy);
596 clt->clt_buflen += copy;
597 buf += copy;
598 len -= copy;
601 return (0);
604 int
605 clt_putc(struct client *clt, char ch)
607 return (clt_write(clt, &ch, 1));
610 int
611 clt_puts(struct client *clt, const char *str)
613 return (clt_write(clt, str, strlen(str)));
616 int
617 clt_write_bufferevent(struct client *clt, struct bufferevent *bev)
619 struct evbuffer *src = EVBUFFER_INPUT(bev);
620 size_t len, left, copy;
622 len = EVBUFFER_LENGTH(src);
623 while (len > 0) {
624 left = sizeof(clt->clt_buf) - clt->clt_buflen;
625 if (left == 0) {
626 if (clt_flush(clt) == -1)
627 return (-1);
628 left = sizeof(clt->clt_buf);
631 copy = bufferevent_read(bev, &clt->clt_buf[clt->clt_buflen],
632 MIN(left, len));
633 clt->clt_buflen += copy;
635 len = EVBUFFER_LENGTH(src);
638 return (0);
641 int
642 clt_printf(struct client *clt, const char *fmt, ...)
644 struct fcgi *fcgi = clt->clt_fcgi;
645 struct bufferevent *bev = fcgi->fcg_bev;
646 char *str;
647 va_list ap;
648 int r;
650 va_start(ap, fmt);
651 r = vasprintf(&str, fmt, ap);
652 va_end(ap);
653 if (r == -1) {
654 fcgi_error(bev, EV_WRITE, fcgi);
655 return (-1);
658 r = clt_write(clt, str, r);
659 free(str);
660 return (r);
663 int
664 fcgi_cmp(struct fcgi *a, struct fcgi *b)
666 return ((int)a->fcg_id - b->fcg_id);
669 int
670 fcgi_client_cmp(struct client *a, struct client *b)
672 return ((int)a->clt_id - b->clt_id);
675 SPLAY_GENERATE(fcgi_tree, fcgi, fcg_nodes, fcgi_cmp);
676 SPLAY_GENERATE(client_tree, client, clt_nodes, fcgi_client_cmp);