2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2006 - 2015 Reyk Floeter <reyk@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #include <sys/types.h>
19 #include <sys/queue.h>
21 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
48 #define MINIMUM(a, b) ((a) < (b) ? (a) : (b))
50 /* provided by OpenBSD' base libevent but not in any header? */
51 extern void bufferevent_read_pressure_cb(struct evbuffer *, size_t,
54 void proxy_init(struct privsep *, struct privsep_proc *, void *);
55 int proxy_launch(struct galileo *);
56 void proxy_inflight_dec(const char *);
57 int proxy_dispatch_parent(int, struct privsep_proc *, struct imsg *);
58 void proxy_translate_gemtext(struct client *);
59 void proxy_resolved(struct asr_result *, void *);
60 void proxy_connect(int, short, void *);
61 int proxy_start_reply(struct client *, int, const char *);
62 void proxy_read(struct bufferevent *, void *);
63 void proxy_write(struct bufferevent *, void *);
64 void proxy_error(struct bufferevent *, short, void *);
65 int proxy_bufferevent_add(struct event *, int);
66 void proxy_tls_writecb(int, short, void *);
67 void proxy_tls_readcb(int, short, void *);
69 static struct privsep_proc procs[] = {
70 { "parent", PROC_PARENT, proxy_dispatch_parent },
73 volatile int proxy_clients;
74 volatile int proxy_inflight;
75 uint32_t proxy_fcg_id;
78 proxy(struct privsep *ps, struct privsep_proc *p)
80 proc_run(ps, p, procs, nitems(procs), proxy_init, NULL);
84 proxy_init(struct privsep *ps, struct privsep_proc *p, void *arg)
86 if (config_init(ps->ps_env) == -1)
87 fatal("failed to initialize configuration");
89 /* We use a custom shutdown callback */
90 /* p->p_shutdown = proxy_shutdown */
92 if (pledge("stdio recvfd unix inet dns", NULL) == -1)
97 proxy_launch(struct galileo *env)
99 event_add(&env->sc_evsock, NULL);
104 proxy_purge(struct proxy *pr)
110 proxy_inflight_dec(const char *why)
113 log_debug("%s: inflight decremented, now %d, %s",
114 __func__, proxy_inflight, why);
118 proxy_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
120 struct privsep *ps = p->p_ps;
121 struct galileo *env = ps->ps_env;
123 switch (imsg->hdr.type) {
125 if (config_getproxy(env, imsg) == -1)
126 fatal("config_getproxy");
131 env->sc_sock_fd = config_getsock(env, imsg);
132 if (env->sc_sock_fd == -1)
133 fatal("config_getsock");
135 event_set(&env->sc_evsock, env->sc_sock_fd,
136 EV_READ | EV_PERSIST, fcgi_accept, env);
137 evtimer_set(&env->sc_evpause, fcgi_accept, env);
140 config_getcfg(env, imsg);
146 config_getreset(env, imsg);
156 gemtext_translate_line(struct client *clt, char *line)
158 /* preformatted line / closing */
159 if (clt->clt_translate & TR_PRE) {
160 if (!strncmp(line, "```", 3)) {
161 clt->clt_translate &= ~TR_PRE;
162 return (clt_puts(clt, "</pre>"));
165 if (tp_htmlescape(clt->clt_tp, line) == -1)
167 return (clt_putc(clt, '\n'));
171 if (!strncmp(line, "* ", 2)) {
172 if (clt->clt_translate & TR_NAV) {
173 if (clt_puts(clt, "</ul></nav>") == -1)
175 clt->clt_translate &= ~TR_NAV;
178 if (!(clt->clt_translate & TR_LIST)) {
179 if (clt_puts(clt, "<ul>") == -1)
181 clt->clt_translate |= TR_LIST;
184 if (clt_puts(clt, "<li>") == -1 ||
185 tp_htmlescape(clt->clt_tp, line + 2) == -1 ||
186 clt_puts(clt, "</li>") == -1)
191 if (clt->clt_translate & TR_LIST) {
192 if (clt_puts(clt, "</ul>") == -1)
194 clt->clt_translate &= ~TR_LIST;
197 /* link -- TODO: relativify from SCRIPT_NAME */
198 if (!strncmp(line, "=>", 2)) {
202 line += strspn(line, " \t");
204 label = line + strcspn(line, " \t");
210 if (fnmatch("*.jpg", line, 0) == 0 ||
211 fnmatch("*.jpeg", line, 0) == 0 ||
212 fnmatch("*.gif", line, 0) == 0 ||
213 fnmatch("*.png", line, 0) == 0 ||
214 fnmatch("*.svg", line, 0) == 0 ||
215 fnmatch("*.webp", line, 0) == 0) {
216 if (clt->clt_translate & TR_NAV) {
217 if (clt_puts(clt, "</ul></nav>") == -1)
219 clt->clt_translate &= ~TR_NAV;
222 if (tp_figure(clt->clt_tp, line, label) == -1)
228 if (!(clt->clt_translate & TR_NAV)) {
229 if (clt_puts(clt, "<nav><ul>") == -1)
231 clt->clt_translate |= TR_NAV;
234 if (clt_puts(clt, "<li><a href='") == -1)
237 /* XXX: do proper parsing */
238 if (*line == '/' || strstr(line, "//") == NULL) {
239 if (tp_urlescape(clt->clt_tp,
240 clt->clt_script_name) == -1)
243 /* skip the first / */
247 if (tp_urlescape(clt->clt_tp, line) == -1 ||
248 clt_puts(clt, "'>") == -1 ||
249 tp_htmlescape(clt->clt_tp, label) == -1 ||
250 clt_puts(clt, "</a></li>") == -1)
256 if (clt->clt_translate & TR_NAV) {
257 if (clt_puts(clt, "</ul></nav>") == -1)
259 clt->clt_translate &= ~TR_NAV;
263 if (!strncmp(line, "```", 3)) {
264 clt->clt_translate |= TR_PRE;
265 return (clt_puts(clt, "<pre>"));
270 if (clt_puts(clt, "<blockquote>") == -1 ||
271 tp_htmlescape(clt->clt_tp, line + 1) == -1 ||
272 clt_puts(clt, "</blockquote>") == -1)
278 if (!strncmp(line, "###", 3)) {
279 if (clt_puts(clt, "<h3>") == -1 ||
280 tp_htmlescape(clt->clt_tp, line + 3) == -1 ||
281 clt_puts(clt, "</h3>") == -1)
285 if (!strncmp(line, "##", 2)) {
286 if (clt_puts(clt, "<h2>") == -1 ||
287 tp_htmlescape(clt->clt_tp, line + 2) == -1 ||
288 clt_puts(clt, "</h2>") == -1)
292 if (!strncmp(line, "#", 1)) {
293 if (clt_puts(clt, "<h1>") == -1 ||
294 tp_htmlescape(clt->clt_tp, line + 1) == -1 ||
295 clt_puts(clt, "</h1>") == -1)
300 /* Not following strictly the gemini specification... */
305 if (clt_puts(clt, "<p>") == -1 ||
306 tp_htmlescape(clt->clt_tp, line) == -1 ||
307 clt_puts(clt, "</p>") == -1)
314 proxy_translate_gemtext(struct client *clt)
316 struct bufferevent *bev = clt->clt_bev;
317 struct evbuffer *src = EVBUFFER_INPUT(bev);
323 line = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF);
327 r = gemtext_translate_line(clt, line);
334 struct proxy_config *
335 proxy_match(struct galileo *env, const char *name)
342 TAILQ_FOREACH(pr, &env->sc_proxies, pr_entry) {
343 if (!strcmp(name, pr->pr_conf.host))
351 proxy_start_request(struct galileo *env, struct client *clt)
353 struct addrinfo hints;
354 struct asr_query *query;
358 if ((clt->clt_pc = proxy_match(env, clt->clt_server_name)) == NULL) {
359 if (proxy_start_reply(clt, 501, "text/html") == -1)
361 if (tp_error(clt->clt_tp, -1, "unknown server") == -1)
363 return (fcgi_end_request(clt, 1));
366 if (clt->clt_bodylen != 0 && clt->clt_body == NULL) {
367 if (proxy_start_reply(clt, 400, "text/html") == -1)
369 if (tp_error(clt->clt_tp, -1, "bad request") == -1)
371 return (fcgi_end_request(clt, 1));
375 r = asprintf(&url, "%s%s?%s", clt->clt_script_name,
376 clt->clt_path_info + 1, clt->clt_body);
378 return (fcgi_end_request(clt, 1));
380 if (proxy_start_reply(clt, 302, url) == -1 ||
381 fcgi_end_request(clt, 1) == -1) {
389 memset(&hints, 0, sizeof(hints));
390 hints.ai_family = AF_UNSPEC;
391 hints.ai_socktype = SOCK_STREAM;
393 query = getaddrinfo_async(clt->clt_pc->proxy_addr,
394 clt->clt_pc->proxy_port, &hints, NULL);
396 log_warn("getaddrinfo_async");
397 return (fcgi_abort_request(clt));
400 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
401 if (clt->clt_evasr == NULL) {
402 log_warn("event_asr_run");
404 return (fcgi_abort_request(clt));
411 proxy_resolved(struct asr_result *res, void *d)
413 struct client *clt = d;
414 struct proxy_config *pc = clt->clt_pc;
416 clt->clt_evasr = NULL;
418 if (res->ar_gai_errno != 0) {
419 log_warnx("failed to resolve %s:%s: %s",
420 pc->proxy_addr, pc->proxy_port,
421 gai_strerror(res->ar_gai_errno));
422 if (proxy_start_reply(clt, 501, "text/html") == -1)
424 if (tp_error(clt->clt_tp, -1, "Can't resolve host") == -1)
426 fcgi_end_request(clt, 1);
430 clt->clt_addrinfo = res->ar_addrinfo;
431 clt->clt_p = clt->clt_addrinfo;
432 proxy_connect(-1, 0, clt);
436 proxy_connect(int fd, short ev, void *d)
438 struct client *clt = d;
439 struct evbuffer *out;
441 struct tls_config *conf;
442 struct timeval conntv = {5, 0};
444 socklen_t len = sizeof(err);
447 if (clt->clt_p == NULL)
450 if (clt->clt_fd != -1) {
451 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
462 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
464 if (clt->clt_fd == -1) {
465 clt->clt_p = clt->clt_p->ai_next;
469 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
472 clt->clt_evconn_live = 1;
473 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
474 event_add(&clt->clt_evconn, &conntv);
478 clt->clt_evconn_live = 0;
479 freeaddrinfo(clt->clt_addrinfo);
480 clt->clt_addrinfo = clt->clt_p = NULL;
482 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
484 if (clt->clt_bev == NULL) {
485 log_warn("bufferevent_new");
489 if (!clt->clt_pc->no_tls) {
490 /* initialize TLS for Gemini */
491 if ((conf = tls_config_new()) == NULL) {
492 log_warn("tls_config_new failed");
496 tls_config_insecure_noverifycert(conf);
498 if ((clt->clt_ctx = tls_client()) == NULL) {
499 log_warnx("tls_client failed");
500 tls_config_free(conf);
504 if (tls_configure(clt->clt_ctx, conf) == -1) {
505 log_warnx("tls_configure failed");
506 tls_config_free(conf);
510 tls_config_free(conf);
512 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
513 clt->clt_pc->proxy_name) == -1) {
514 log_warnx("tls_connect_socket failed");
518 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
519 proxy_tls_readcb, clt->clt_bev);
520 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
521 proxy_tls_writecb, clt->clt_bev);
524 /* bufferevent_settimeout(); */
525 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
527 /* TODO: compute the URL */
528 out = EVBUFFER_OUTPUT(clt->clt_bev);
529 if (evbuffer_add_printf(out, "gemini://%s/%s",
530 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
531 log_warn("bufferevent_printf failed");
535 if (clt->clt_query &&
536 evbuffer_add_printf(out, "?%s", clt->clt_query) == -1) {
537 log_warn("bufferevent_printf failed");
541 if (evbuffer_add(out, "\r\n", 2) == -1) {
542 log_warn("bufferevent_add failed");
549 log_warn("failed to connect to %s:%s",
550 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
551 if (proxy_start_reply(clt, 501, "text/html") == -1)
553 if (tp_error(clt->clt_tp, -1, "Can't connect") == -1)
555 fcgi_end_request(clt, 1);
559 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
563 if (strncmp(mime, "text/gemini", 11) != 0)
566 clt->clt_translate = TR_ENABLED;
568 if ((mime = strchr(mime, ';')) == NULL)
572 while ((t = strsep(&mime, ";")) != NULL) {
573 if (!strncmp(t, "charset=", 8)) {
575 if (!strncasecmp(t, "utf8", 4) ||
576 !strncasecmp(t, "utf-8", 5) ||
577 !strncasecmp(t, "ascii", 5)) {
578 log_debug("unknown charset %s", t);
584 if (!strncmp(t, "lang=", 5)) {
586 if ((semi = strchr(t, ';')) != NULL)
589 if (strlcpy(lang, t, len) >= len) {
590 log_debug("lang too long: %s", t);
604 proxy_start_reply(struct client *clt, int status, const char *ctype)
608 csp = "Content-Security-Policy: default-src 'self'; "
609 "script-src 'none'; object-src 'none';\r\n";
612 clt_printf(clt, "Status: %d\r\n", status) == -1)
615 if (clt_puts(clt, csp) == -1)
619 /* use "ctype" as redirect target */
620 if (clt_printf(clt, "Location: %s\r\n", ctype) == -1)
622 if (clt_puts(clt, "\r\n") == -1)
628 if (!strcmp(ctype, "text/html"))
629 ctype = "text/html;charset=utf-8";
630 if (clt_printf(clt, "Content-Type: %s\r\n", ctype)
635 if (clt_puts(clt, "\r\n") == -1)
642 proxy_read(struct bufferevent *bev, void *d)
644 struct client *clt = d;
645 struct evbuffer *src = EVBUFFER_INPUT(bev);
652 if (clt->clt_headersdone) {
653 if (clt->clt_translate)
654 proxy_translate_gemtext(clt);
656 clt_write_bufferevent(clt, bev);
660 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
662 if (EVBUFFER_LENGTH(src) >= 1026)
663 proxy_error(bev, EV_READ, clt);
668 !isdigit((unsigned char)hdr[0]) ||
669 !isdigit((unsigned char)hdr[1]) ||
671 log_warnx("invalid ");
672 proxy_error(bev, EV_READ, clt);
676 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
680 if (proxy_start_reply(clt, 200, "text/html") == -1)
682 if (tp_inputpage(clt->clt_tp, &hdr[3]) == -1)
684 fcgi_end_request(clt, 0);
690 /* XXX: do proper parsing */
691 if (hdr[3] == '/' || strstr(&hdr[3], "//") == NULL) {
694 if (asprintf(&url, "%s%s", clt->clt_script_name,
698 if (proxy_start_reply(clt, 302, url)) {
703 fcgi_end_request(clt, 0);
708 if (proxy_start_reply(clt, 501, "text/html") == -1)
710 if (tp_error(clt->clt_tp, code, &hdr[3]) == -1)
712 fcgi_end_request(clt, 1);
716 mime = hdr + 2 + strspn(hdr + 2, " \t");
717 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
718 if (proxy_start_reply(clt, 501, "text/html") == -1)
720 if (tp_error(clt->clt_tp, -1, "Bad response") == -1)
722 fcgi_end_request(clt, 1);
726 if (clt->clt_translate)
727 ctype = "text/html;charset=utf-8";
731 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
734 clt->clt_headersdone = 1;
736 if (clt->clt_translate &&
737 tp_head(clt->clt_tp, lang, NULL) == -1)
741 * Trigger the read again so we proceed with the response
753 proxy_write(struct bufferevent *bev, void *d)
759 proxy_error(struct bufferevent *bev, short err, void *d)
761 struct client *clt = d;
762 int status = !(err & EVBUFFER_EOF);
764 log_debug("proxy error, shutting down the connection (err: %x)",
767 if (!clt->clt_headersdone) {
768 if (proxy_start_reply(clt, 501, "text/html") == -1)
770 if (tp_error(clt->clt_tp, -1, "Proxy error") == -1)
772 } else if (status == 0) {
773 if (clt->clt_translate & TR_PRE) {
774 if (clt_puts(clt, "</pre>"))
776 clt->clt_translate &= ~TR_PRE;
779 if (clt->clt_translate & TR_LIST) {
780 if (clt_puts(clt, "</ul>") == -1)
782 clt->clt_translate &= ~TR_LIST;
785 if (clt->clt_translate & TR_NAV) {
786 if (clt_puts(clt, "</ul></nav>") == -1)
788 clt->clt_translate &= ~TR_NAV;
791 if (clt->clt_translate &&
792 tp_foot(clt->clt_tp) == -1)
796 fcgi_end_request(clt, status);
800 proxy_tls_readcb(int fd, short event, void *arg)
802 struct bufferevent *bufev = arg;
803 struct client *clt = bufev->cbarg;
804 char rbuf[IBUF_READ_SIZE];
805 int what = EVBUFFER_READ;
806 int howmuch = IBUF_READ_SIZE;
810 if (event == EV_TIMEOUT) {
811 what |= EVBUFFER_TIMEOUT;
815 if (bufev->wm_read.high != 0)
816 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
818 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
819 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
821 } else if (ret == -1) {
822 what |= EVBUFFER_ERROR;
828 what |= EVBUFFER_EOF;
832 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
833 what |= EVBUFFER_ERROR;
837 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
839 len = EVBUFFER_LENGTH(bufev->input);
840 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
842 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
843 struct evbuffer *buf = bufev->input;
844 event_del(&bufev->ev_read);
845 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
849 if (bufev->readcb != NULL)
850 (*bufev->readcb)(bufev, bufev->cbarg);
854 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
858 (*bufev->errorcb)(bufev, what, bufev->cbarg);
862 proxy_bufferevent_add(struct event *ev, int timeout)
864 struct timeval tv, *ptv = NULL;
872 return (event_add(ev, ptv));
876 proxy_tls_writecb(int fd, short event, void *arg)
878 struct bufferevent *bufev = arg;
879 struct client *clt = bufev->cbarg;
881 short what = EVBUFFER_WRITE;
884 if (event == EV_TIMEOUT) {
885 what |= EVBUFFER_TIMEOUT;
889 if (EVBUFFER_LENGTH(bufev->output)) {
890 ret = tls_write(clt->clt_ctx,
891 EVBUFFER_DATA(bufev->output),
892 EVBUFFER_LENGTH(bufev->output));
893 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
895 } else if (ret == -1) {
896 what |= EVBUFFER_ERROR;
900 evbuffer_drain(bufev->output, len);
903 if (EVBUFFER_LENGTH(bufev->output) != 0)
904 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
906 if (bufev->writecb != NULL &&
907 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
908 (*bufev->writecb)(bufev, bufev->cbarg);
912 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
916 (*bufev->errorcb)(bufev, what, bufev->cbarg);
920 proxy_client_free(struct client *clt)
923 event_asr_abort(clt->clt_evasr);
925 if (clt->clt_addrinfo)
926 freeaddrinfo(clt->clt_addrinfo);
928 if (clt->clt_evconn_live)
929 event_del(&clt->clt_evconn);
931 if (clt->clt_fd != -1)
935 tls_free(clt->clt_ctx);
938 bufferevent_free(clt->clt_bev);
942 free(clt->clt_server_name);
943 free(clt->clt_script_name);
944 free(clt->clt_path_info);
945 free(clt->clt_query);