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>
49 #define MINIMUM(a, b) ((a) < (b) ? (a) : (b))
52 # define G_TOUT(t) ((t).tv_sec)
54 # define G_TOUT(t) (t)
57 /* provided by OpenBSD' base libevent but not in any header? */
58 extern void bufferevent_read_pressure_cb(struct evbuffer *, size_t,
61 void proxy_init(struct privsep *, struct privsep_proc *, void *);
62 int proxy_launch(struct galileo *);
63 void proxy_inflight_dec(const char *);
64 int proxy_dispatch_parent(int, struct privsep_proc *, struct imsg *);
65 void proxy_translate_gemtext(struct client *);
66 void proxy_resolved(struct asr_result *, void *);
67 void proxy_connect(int, short, void *);
68 int proxy_start_reply(struct client *, int, const char *);
69 void proxy_read(struct bufferevent *, void *);
70 void proxy_write(struct bufferevent *, void *);
71 void proxy_error(struct bufferevent *, short, void *);
72 int proxy_bufferevent_add(struct event *, int);
73 void proxy_tls_writecb(int, short, void *);
74 void proxy_tls_readcb(int, short, void *);
76 static struct privsep_proc procs[] = {
77 { "parent", PROC_PARENT, proxy_dispatch_parent },
80 volatile int proxy_clients;
81 volatile int proxy_inflight;
82 uint32_t proxy_fcg_id;
85 proxy(struct privsep *ps, struct privsep_proc *p)
87 proc_run(ps, p, procs, nitems(procs), proxy_init, NULL);
91 proxy_init(struct privsep *ps, struct privsep_proc *p, void *arg)
93 if (config_init(ps->ps_env) == -1)
94 fatal("failed to initialize configuration");
96 /* We use a custom shutdown callback */
97 /* p->p_shutdown = proxy_shutdown */
99 if (pledge("stdio recvfd unix inet dns", NULL) == -1)
104 proxy_launch(struct galileo *env)
106 event_add(&env->sc_evsock, NULL);
111 proxy_purge(struct proxy *pr)
117 proxy_inflight_dec(const char *why)
120 log_debug("%s: inflight decremented, now %d, %s",
121 __func__, proxy_inflight, why);
125 proxy_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
127 struct privsep *ps = p->p_ps;
128 struct galileo *env = ps->ps_env;
130 switch (imsg->hdr.type) {
132 if (config_getproxy(env, imsg) == -1)
133 fatal("config_getproxy");
138 env->sc_sock_fd = config_getsock(env, imsg);
139 if (env->sc_sock_fd == -1)
140 fatal("config_getsock");
142 event_set(&env->sc_evsock, env->sc_sock_fd,
143 EV_READ | EV_PERSIST, fcgi_accept, env);
144 evtimer_set(&env->sc_evpause, fcgi_accept, env);
147 config_getcfg(env, imsg);
153 config_getreset(env, imsg);
163 gemtext_translate_line(struct client *clt, char *line)
165 /* preformatted line / closing */
166 if (clt->clt_translate & TR_PRE) {
167 if (!strncmp(line, "```", 3)) {
168 clt->clt_translate &= ~TR_PRE;
169 return (clt_puts(clt, "</pre>"));
172 if (tp_htmlescape(clt->clt_tp, line) == -1)
174 return (clt_putc(clt, '\n'));
178 if (!strncmp(line, "* ", 2)) {
179 if (clt->clt_translate & TR_NAV) {
180 if (clt_puts(clt, "</ul></nav>") == -1)
182 clt->clt_translate &= ~TR_NAV;
185 if (!(clt->clt_translate & TR_LIST)) {
186 if (clt_puts(clt, "<ul>") == -1)
188 clt->clt_translate |= TR_LIST;
191 if (clt_puts(clt, "<li>") == -1 ||
192 tp_htmlescape(clt->clt_tp, line + 2) == -1 ||
193 clt_puts(clt, "</li>") == -1)
198 if (clt->clt_translate & TR_LIST) {
199 if (clt_puts(clt, "</ul>") == -1)
201 clt->clt_translate &= ~TR_LIST;
204 /* link -- TODO: relativify from SCRIPT_NAME */
205 if (!strncmp(line, "=>", 2)) {
209 line += strspn(line, " \t");
211 label = line + strcspn(line, " \t");
217 if (fnmatch("*.jpg", line, 0) == 0 ||
218 fnmatch("*.jpeg", line, 0) == 0 ||
219 fnmatch("*.gif", line, 0) == 0 ||
220 fnmatch("*.png", line, 0) == 0 ||
221 fnmatch("*.svg", line, 0) == 0 ||
222 fnmatch("*.webp", line, 0) == 0) {
223 if (clt->clt_translate & TR_NAV) {
224 if (clt_puts(clt, "</ul></nav>") == -1)
226 clt->clt_translate &= ~TR_NAV;
229 if (tp_figure(clt->clt_tp, line, label) == -1)
235 if (!(clt->clt_translate & TR_NAV)) {
236 if (clt_puts(clt, "<nav><ul>") == -1)
238 clt->clt_translate |= TR_NAV;
241 if (clt_puts(clt, "<li><a href='") == -1)
244 /* XXX: do proper parsing */
245 if (*line == '/' || strstr(line, "//") == NULL) {
246 if (tp_urlescape(clt->clt_tp,
247 clt->clt_script_name) == -1)
250 /* skip the first / */
254 if (tp_urlescape(clt->clt_tp, line) == -1 ||
255 clt_puts(clt, "'>") == -1 ||
256 tp_htmlescape(clt->clt_tp, label) == -1 ||
257 clt_puts(clt, "</a></li>") == -1)
263 if (clt->clt_translate & TR_NAV) {
264 if (clt_puts(clt, "</ul></nav>") == -1)
266 clt->clt_translate &= ~TR_NAV;
270 if (!strncmp(line, "```", 3)) {
271 clt->clt_translate |= TR_PRE;
272 return (clt_puts(clt, "<pre>"));
277 if (clt_puts(clt, "<blockquote>") == -1 ||
278 tp_htmlescape(clt->clt_tp, line + 1) == -1 ||
279 clt_puts(clt, "</blockquote>") == -1)
285 if (!strncmp(line, "###", 3)) {
286 if (clt_puts(clt, "<h3>") == -1 ||
287 tp_htmlescape(clt->clt_tp, line + 3) == -1 ||
288 clt_puts(clt, "</h3>") == -1)
292 if (!strncmp(line, "##", 2)) {
293 if (clt_puts(clt, "<h2>") == -1 ||
294 tp_htmlescape(clt->clt_tp, line + 2) == -1 ||
295 clt_puts(clt, "</h2>") == -1)
299 if (!strncmp(line, "#", 1)) {
300 if (clt_puts(clt, "<h1>") == -1 ||
301 tp_htmlescape(clt->clt_tp, line + 1) == -1 ||
302 clt_puts(clt, "</h1>") == -1)
307 /* Not following strictly the gemini specification... */
312 if (clt_puts(clt, "<p>") == -1 ||
313 tp_htmlescape(clt->clt_tp, line) == -1 ||
314 clt_puts(clt, "</p>") == -1)
321 proxy_translate_gemtext(struct client *clt)
323 struct bufferevent *bev = clt->clt_bev;
324 struct evbuffer *src = EVBUFFER_INPUT(bev);
330 line = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF);
334 r = gemtext_translate_line(clt, line);
341 struct proxy_config *
342 proxy_match(struct galileo *env, const char *name)
349 TAILQ_FOREACH(pr, &env->sc_proxies, pr_entry) {
350 if (!strcmp(name, pr->pr_conf.host))
351 return (&pr->pr_conf);
358 proxy_start_request(struct galileo *env, struct client *clt)
360 struct addrinfo hints;
361 struct asr_query *query;
365 if ((clt->clt_pc = proxy_match(env, clt->clt_server_name)) == NULL) {
366 if (proxy_start_reply(clt, 501, "text/html") == -1)
368 if (tp_error(clt->clt_tp, -1, "unknown server") == -1)
370 return (fcgi_end_request(clt, 1));
373 if (clt->clt_bodylen != 0 && clt->clt_body == NULL) {
374 if (proxy_start_reply(clt, 400, "text/html") == -1)
376 if (tp_error(clt->clt_tp, -1, "bad request") == -1)
378 return (fcgi_end_request(clt, 1));
382 r = asprintf(&url, "%s%s?%s", clt->clt_script_name,
383 clt->clt_path_info + 1, clt->clt_body);
385 return (fcgi_end_request(clt, 1));
387 if (proxy_start_reply(clt, 302, url) == -1 ||
388 fcgi_end_request(clt, 1) == -1) {
396 memset(&hints, 0, sizeof(hints));
397 hints.ai_family = AF_UNSPEC;
398 hints.ai_socktype = SOCK_STREAM;
400 query = getaddrinfo_async(clt->clt_pc->proxy_addr,
401 clt->clt_pc->proxy_port, &hints, NULL);
403 log_warn("getaddrinfo_async");
404 return (fcgi_abort_request(clt));
407 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
408 if (clt->clt_evasr == NULL) {
409 log_warn("event_asr_run");
411 return (fcgi_abort_request(clt));
418 proxy_resolved(struct asr_result *res, void *d)
420 struct client *clt = d;
421 struct proxy_config *pc = clt->clt_pc;
423 clt->clt_evasr = NULL;
425 if (res->ar_gai_errno != 0) {
426 log_warnx("failed to resolve %s:%s: %s",
427 pc->proxy_addr, pc->proxy_port,
428 gai_strerror(res->ar_gai_errno));
429 if (proxy_start_reply(clt, 501, "text/html") == -1)
431 if (tp_error(clt->clt_tp, -1, "Can't resolve host") == -1)
433 fcgi_end_request(clt, 1);
437 clt->clt_addrinfo = res->ar_addrinfo;
438 clt->clt_p = clt->clt_addrinfo;
439 proxy_connect(-1, 0, clt);
443 proxy_connect(int fd, short ev, void *d)
445 struct client *clt = d;
446 struct evbuffer *out;
448 struct tls_config *conf;
449 struct timeval conntv = {5, 0};
451 socklen_t len = sizeof(err);
454 if (clt->clt_p == NULL)
457 if (clt->clt_fd != -1) {
458 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
469 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
471 if (clt->clt_fd == -1) {
472 clt->clt_p = clt->clt_p->ai_next;
476 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
479 clt->clt_evconn_live = 1;
480 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
481 event_add(&clt->clt_evconn, &conntv);
485 clt->clt_evconn_live = 0;
486 freeaddrinfo(clt->clt_addrinfo);
487 clt->clt_addrinfo = clt->clt_p = NULL;
489 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
491 if (clt->clt_bev == NULL) {
492 log_warn("bufferevent_new");
496 if (!clt->clt_pc->no_tls) {
497 /* initialize TLS for Gemini */
498 if ((conf = tls_config_new()) == NULL) {
499 log_warn("tls_config_new failed");
503 tls_config_insecure_noverifycert(conf);
505 if ((clt->clt_ctx = tls_client()) == NULL) {
506 log_warnx("tls_client failed");
507 tls_config_free(conf);
511 if (tls_configure(clt->clt_ctx, conf) == -1) {
512 log_warnx("tls_configure failed");
513 tls_config_free(conf);
517 tls_config_free(conf);
519 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
520 clt->clt_pc->proxy_name) == -1) {
521 log_warnx("tls_connect_socket failed");
525 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
526 proxy_tls_readcb, clt->clt_bev);
527 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
528 proxy_tls_writecb, clt->clt_bev);
531 evbuffer_unfreeze(clt->clt_bev->input, 0);
532 evbuffer_unfreeze(clt->clt_bev->output, 1);
536 /* bufferevent_settimeout(); */
537 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
539 /* TODO: compute the URL */
540 out = EVBUFFER_OUTPUT(clt->clt_bev);
541 if (evbuffer_add_printf(out, "gemini://%s/%s",
542 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
543 log_warn("bufferevent_printf failed");
547 if (clt->clt_query &&
548 evbuffer_add_printf(out, "?%s", clt->clt_query) == -1) {
549 log_warn("bufferevent_printf failed");
553 if (evbuffer_add(out, "\r\n", 2) == -1) {
554 log_warn("bufferevent_add failed");
561 log_warn("failed to connect to %s:%s",
562 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
563 if (proxy_start_reply(clt, 501, "text/html") == -1)
565 if (tp_error(clt->clt_tp, -1, "Can't connect") == -1)
567 fcgi_end_request(clt, 1);
571 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
575 if (strncmp(mime, "text/gemini", 11) != 0)
578 clt->clt_translate = TR_ENABLED;
580 if ((mime = strchr(mime, ';')) == NULL)
584 while ((t = strsep(&mime, ";")) != NULL) {
585 if (!strncmp(t, "charset=", 8)) {
587 if (!strncasecmp(t, "utf8", 4) ||
588 !strncasecmp(t, "utf-8", 5) ||
589 !strncasecmp(t, "ascii", 5)) {
590 log_debug("unknown charset %s", t);
596 if (!strncmp(t, "lang=", 5)) {
598 if ((semi = strchr(t, ';')) != NULL)
601 if (strlcpy(lang, t, len) >= len) {
602 log_debug("lang too long: %s", t);
616 proxy_start_reply(struct client *clt, int status, const char *ctype)
620 csp = "Content-Security-Policy: default-src 'self'; "
621 "script-src 'none'; object-src 'none';\r\n";
624 clt_printf(clt, "Status: %d\r\n", status) == -1)
627 if (clt_puts(clt, csp) == -1)
631 /* use "ctype" as redirect target */
632 if (clt_printf(clt, "Location: %s\r\n", ctype) == -1)
634 if (clt_puts(clt, "\r\n") == -1)
640 if (!strcmp(ctype, "text/html"))
641 ctype = "text/html;charset=utf-8";
642 if (clt_printf(clt, "Content-Type: %s\r\n", ctype)
647 if (clt_puts(clt, "\r\n") == -1)
654 proxy_read(struct bufferevent *bev, void *d)
656 struct client *clt = d;
657 struct evbuffer *src = EVBUFFER_INPUT(bev);
664 if (clt->clt_headersdone) {
665 if (clt->clt_translate)
666 proxy_translate_gemtext(clt);
668 clt_write_bufferevent(clt, bev);
672 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
674 if (EVBUFFER_LENGTH(src) >= 1026)
675 proxy_error(bev, EV_READ, clt);
680 !isdigit((unsigned char)hdr[0]) ||
681 !isdigit((unsigned char)hdr[1]) ||
683 log_warnx("invalid ");
684 proxy_error(bev, EV_READ, clt);
688 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
692 if (proxy_start_reply(clt, 200, "text/html") == -1)
694 if (tp_inputpage(clt->clt_tp, &hdr[3]) == -1)
696 fcgi_end_request(clt, 0);
702 /* XXX: do proper parsing */
703 if (hdr[3] == '/' || strstr(&hdr[3], "//") == NULL) {
706 if (asprintf(&url, "%s%s", clt->clt_script_name,
710 if (proxy_start_reply(clt, 302, url)) {
715 fcgi_end_request(clt, 0);
720 if (proxy_start_reply(clt, 501, "text/html") == -1)
722 if (tp_error(clt->clt_tp, code, &hdr[3]) == -1)
724 fcgi_end_request(clt, 1);
728 mime = hdr + 2 + strspn(hdr + 2, " \t");
729 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
730 if (proxy_start_reply(clt, 501, "text/html") == -1)
732 if (tp_error(clt->clt_tp, -1, "Bad response") == -1)
734 fcgi_end_request(clt, 1);
738 if (clt->clt_translate)
739 ctype = "text/html;charset=utf-8";
743 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
746 clt->clt_headersdone = 1;
748 if (clt->clt_translate &&
749 tp_head(clt->clt_tp, lang, NULL) == -1)
753 * Trigger the read again so we proceed with the response
765 proxy_write(struct bufferevent *bev, void *d)
771 proxy_error(struct bufferevent *bev, short err, void *d)
773 struct client *clt = d;
774 int status = !(err & EVBUFFER_EOF);
776 log_debug("proxy error, shutting down the connection (err: %x)",
779 if (!clt->clt_headersdone) {
780 if (proxy_start_reply(clt, 501, "text/html") == -1)
782 if (tp_error(clt->clt_tp, -1, "Proxy error") == -1)
784 } else if (status == 0) {
785 if (clt->clt_translate & TR_PRE) {
786 if (clt_puts(clt, "</pre>"))
788 clt->clt_translate &= ~TR_PRE;
791 if (clt->clt_translate & TR_LIST) {
792 if (clt_puts(clt, "</ul>") == -1)
794 clt->clt_translate &= ~TR_LIST;
797 if (clt->clt_translate & TR_NAV) {
798 if (clt_puts(clt, "</ul></nav>") == -1)
800 clt->clt_translate &= ~TR_NAV;
803 if (clt->clt_translate &&
804 tp_foot(clt->clt_tp) == -1)
808 fcgi_end_request(clt, status);
812 proxy_tls_readcb(int fd, short event, void *arg)
814 struct bufferevent *bufev = arg;
815 struct client *clt = bufev->cbarg;
816 char rbuf[IBUF_READ_SIZE];
817 int what = EVBUFFER_READ;
818 int howmuch = IBUF_READ_SIZE;
822 if (event == EV_TIMEOUT) {
823 what |= EVBUFFER_TIMEOUT;
827 if (bufev->wm_read.high != 0)
828 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
830 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
831 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
833 } else if (ret == -1) {
834 what |= EVBUFFER_ERROR;
840 what |= EVBUFFER_EOF;
844 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
845 what |= EVBUFFER_ERROR;
849 proxy_bufferevent_add(&bufev->ev_read, G_TOUT(bufev->timeout_read));
851 len = EVBUFFER_LENGTH(bufev->input);
852 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
854 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
855 struct evbuffer *buf = bufev->input;
856 event_del(&bufev->ev_read);
857 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
861 if (bufev->readcb != NULL)
862 (*bufev->readcb)(bufev, bufev->cbarg);
866 proxy_bufferevent_add(&bufev->ev_read, G_TOUT(bufev->timeout_read));
870 (*bufev->errorcb)(bufev, what, bufev->cbarg);
874 proxy_bufferevent_add(struct event *ev, int timeout)
876 struct timeval tv, *ptv = NULL;
884 return (event_add(ev, ptv));
888 proxy_tls_writecb(int fd, short event, void *arg)
890 struct bufferevent *bufev = arg;
891 struct client *clt = bufev->cbarg;
893 short what = EVBUFFER_WRITE;
896 if (event == EV_TIMEOUT) {
897 what |= EVBUFFER_TIMEOUT;
901 if (EVBUFFER_LENGTH(bufev->output)) {
902 ret = tls_write(clt->clt_ctx,
903 EVBUFFER_DATA(bufev->output),
904 EVBUFFER_LENGTH(bufev->output));
905 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
907 } else if (ret == -1) {
908 what |= EVBUFFER_ERROR;
912 evbuffer_drain(bufev->output, len);
915 if (EVBUFFER_LENGTH(bufev->output) != 0)
916 proxy_bufferevent_add(&bufev->ev_write,
917 G_TOUT(bufev->timeout_write));
919 if (bufev->writecb != NULL &&
920 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
921 (*bufev->writecb)(bufev, bufev->cbarg);
925 proxy_bufferevent_add(&bufev->ev_write, G_TOUT(bufev->timeout_write));
929 (*bufev->errorcb)(bufev, what, bufev->cbarg);
933 proxy_client_free(struct client *clt)
936 event_asr_abort(clt->clt_evasr);
938 if (clt->clt_addrinfo)
939 freeaddrinfo(clt->clt_addrinfo);
941 if (clt->clt_evconn_live)
942 event_del(&clt->clt_evconn);
944 if (clt->clt_fd != -1)
948 tls_free(clt->clt_ctx);
951 bufferevent_free(clt->clt_bev);
955 free(clt->clt_server_name);
956 free(clt->clt_script_name);
957 free(clt->clt_path_info);
958 free(clt->clt_query);