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 server *srv)
109 proxy_inflight_dec(const char *why)
112 log_debug("%s: inflight decremented, now %d, %s",
113 __func__, proxy_inflight, why);
117 proxy_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
119 struct privsep *ps = p->p_ps;
120 struct galileo *env = ps->ps_env;
122 switch (imsg->hdr.type) {
124 if (config_getserver(env, imsg) == -1)
125 fatal("config_getproxy");
130 if (env->sc_sock_fd != -1) {
131 event_del(&env->sc_evsock);
132 close(env->sc_sock_fd);
135 env->sc_sock_fd = config_getsock(env, imsg);
136 if (env->sc_sock_fd == -1)
137 fatal("config_getsock");
139 event_set(&env->sc_evsock, env->sc_sock_fd,
140 EV_READ | EV_PERSIST, fcgi_accept, env);
141 event_add(&env->sc_evsock, NULL);
142 evtimer_set(&env->sc_evpause, fcgi_accept, env);
145 log_debug("config done!");
151 log_warnx("unknown message %d", imsg->hdr.type);
159 gemtext_translate_line(struct client *clt, char *line)
161 /* preformatted line / closing */
162 if (clt->clt_translate & TR_PRE) {
163 if (!strncmp(line, "```", 3)) {
164 clt->clt_translate &= ~TR_PRE;
165 return (clt_puts(clt, "</pre>"));
168 if (tp_htmlescape(clt->clt_tp, line) == -1)
170 return (clt_putc(clt, '\n'));
174 if (!strncmp(line, "* ", 2)) {
175 if (clt->clt_translate & TR_NAV) {
176 if (clt_puts(clt, "</ul></nav>") == -1)
178 clt->clt_translate &= ~TR_NAV;
181 if (!(clt->clt_translate & TR_LIST)) {
182 if (clt_puts(clt, "<ul>") == -1)
184 clt->clt_translate |= TR_LIST;
187 if (clt_puts(clt, "<li>") == -1 ||
188 tp_htmlescape(clt->clt_tp, line + 2) == -1 ||
189 clt_puts(clt, "</li>") == -1)
194 if (clt->clt_translate & TR_LIST) {
195 if (clt_puts(clt, "</ul>") == -1)
197 clt->clt_translate &= ~TR_LIST;
200 /* link -- TODO: relativify from SCRIPT_NAME */
201 if (!strncmp(line, "=>", 2)) {
205 line += strspn(line, " \t");
207 label = line + strcspn(line, " \t");
213 if (fnmatch("*.jpg", line, 0) == 0 ||
214 fnmatch("*.jpeg", line, 0) == 0 ||
215 fnmatch("*.gif", line, 0) == 0 ||
216 fnmatch("*.png", line, 0) == 0 ||
217 fnmatch("*.svg", line, 0) == 0 ||
218 fnmatch("*.webp", line, 0) == 0) {
219 if (clt->clt_translate & TR_NAV) {
220 if (clt_puts(clt, "</ul></nav>") == -1)
222 clt->clt_translate &= ~TR_NAV;
225 if (tp_figure(clt->clt_tp, line, label) == -1)
231 if (!(clt->clt_translate & TR_NAV)) {
232 if (clt_puts(clt, "<nav><ul>") == -1)
234 clt->clt_translate |= TR_NAV;
237 if (clt_puts(clt, "<li><a href='") == -1)
240 /* XXX: do proper parsing */
241 if (*line == '/' || strstr(line, "//") == NULL) {
242 if (tp_urlescape(clt->clt_tp,
243 clt->clt_script_name) == -1)
246 /* skip the first / */
250 if (tp_urlescape(clt->clt_tp, line) == -1 ||
251 clt_puts(clt, "'>") == -1 ||
252 tp_htmlescape(clt->clt_tp, label) == -1 ||
253 clt_puts(clt, "</a></li>") == -1)
259 if (clt->clt_translate & TR_NAV) {
260 if (clt_puts(clt, "</ul></nav>") == -1)
262 clt->clt_translate &= ~TR_NAV;
266 if (!strncmp(line, "```", 3)) {
267 clt->clt_translate |= TR_PRE;
268 return (clt_puts(clt, "<pre>"));
273 if (clt_puts(clt, "<blockquote>") == -1 ||
274 tp_htmlescape(clt->clt_tp, line + 1) == -1 ||
275 clt_puts(clt, "</blockquote>") == -1)
281 if (!strncmp(line, "###", 3)) {
282 if (clt_puts(clt, "<h3>") == -1 ||
283 tp_htmlescape(clt->clt_tp, line + 3) == -1 ||
284 clt_puts(clt, "</h3>") == -1)
288 if (!strncmp(line, "##", 2)) {
289 if (clt_puts(clt, "<h2>") == -1 ||
290 tp_htmlescape(clt->clt_tp, line + 2) == -1 ||
291 clt_puts(clt, "</h2>") == -1)
295 if (!strncmp(line, "#", 1)) {
296 if (clt_puts(clt, "<h1>") == -1 ||
297 tp_htmlescape(clt->clt_tp, line + 1) == -1 ||
298 clt_puts(clt, "</h1>") == -1)
303 /* Not following strictly the gemini specification... */
308 if (clt_puts(clt, "<p>") == -1 ||
309 tp_htmlescape(clt->clt_tp, line) == -1 ||
310 clt_puts(clt, "</p>") == -1)
317 proxy_translate_gemtext(struct client *clt)
319 struct bufferevent *bev = clt->clt_bev;
320 struct evbuffer *src = EVBUFFER_INPUT(bev);
326 line = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF);
330 r = gemtext_translate_line(clt, line);
337 static struct proxy_config *
338 proxy_server_match(struct galileo *env, struct client *clt)
342 if (clt->clt_server_name == NULL)
345 TAILQ_FOREACH(srv, &env->sc_servers, srv_entry) {
346 if (!strcmp(clt->clt_server_name, srv->srv_conf.host))
347 return &srv->srv_conf;
354 proxy_start_request(struct galileo *env, struct client *clt)
356 struct addrinfo hints;
357 struct asr_query *query;
360 if ((clt->clt_pc = proxy_server_match(env, clt)) == NULL) {
361 if (proxy_start_reply(clt, 501, "text/html") == -1)
363 if (tp_error(clt->clt_tp, -1, "unknown server") == -1)
365 fcgi_end_request(clt, 1);
369 (void)snprintf(port, sizeof(port), "%d", clt->clt_pc->proxy_port);
371 memset(&hints, 0, sizeof(hints));
372 hints.ai_family = AF_UNSPEC;
373 hints.ai_socktype = SOCK_STREAM;
375 query = getaddrinfo_async(clt->clt_pc->proxy_addr, port, &hints, NULL);
377 log_warn("getaddrinfo_async");
378 fcgi_abort_request(clt);
382 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
383 if (clt->clt_evasr == NULL) {
384 log_warn("event_asr_run");
386 fcgi_abort_request(clt);
392 proxy_resolved(struct asr_result *res, void *d)
394 struct client *clt = d;
395 struct proxy_config *pc = clt->clt_pc;
397 clt->clt_evasr = NULL;
399 if (res->ar_gai_errno != 0) {
400 log_warnx("failed to resolve %s:%d: %s",
401 pc->proxy_addr, pc->proxy_port,
402 gai_strerror(res->ar_gai_errno));
403 if (proxy_start_reply(clt, 501, "text/html") == -1)
405 if (tp_error(clt->clt_tp, -1, "Can't resolve host") == -1)
407 fcgi_end_request(clt, 1);
411 clt->clt_addrinfo = res->ar_addrinfo;
412 clt->clt_p = clt->clt_addrinfo;
413 proxy_connect(-1, 0, clt);
417 proxy_connect(int fd, short ev, void *d)
419 struct client *clt = d;
420 struct evbuffer *out;
422 struct tls_config *conf;
423 struct timeval conntv = {5, 0};
425 socklen_t len = sizeof(err);
428 if (clt->clt_p == NULL)
431 if (clt->clt_fd != -1) {
432 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
443 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
445 if (clt->clt_fd == -1) {
446 clt->clt_p = clt->clt_p->ai_next;
450 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
453 clt->clt_evconn_live = 1;
454 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
455 event_add(&clt->clt_evconn, &conntv);
459 clt->clt_evconn_live = 0;
460 freeaddrinfo(clt->clt_addrinfo);
461 clt->clt_addrinfo = clt->clt_p = NULL;
463 /* initialize TLS for Gemini */
464 if ((conf = tls_config_new()) == NULL) {
465 log_warn("tls_config_new failed");
469 tls_config_insecure_noverifycert(conf);
471 if ((clt->clt_ctx = tls_client()) == NULL) {
472 log_warnx("tls_client failed");
473 tls_config_free(conf);
477 if (tls_configure(clt->clt_ctx, conf) == -1) {
478 log_warnx("tls_configure failed");
479 tls_config_free(conf);
483 tls_config_free(conf);
485 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
486 clt->clt_pc->proxy_name) == -1) {
487 log_warnx("tls_connect_socket failed");
491 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
493 if (clt->clt_bev == NULL) {
494 log_warn("bufferevent_new");
497 out = EVBUFFER_OUTPUT(clt->clt_bev);
499 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
500 proxy_tls_readcb, clt->clt_bev);
501 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
502 proxy_tls_writecb, clt->clt_bev);
504 /* bufferevent_settimeout(); */
505 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
507 /* TODO: compute the URL */
508 if (evbuffer_add_printf(out, "gemini://%s/%s",
509 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
510 log_warn("bufferevent_printf failed");
514 if (clt->clt_query &&
515 evbuffer_add_printf(out, "?%s", clt->clt_query) == -1) {
516 log_warn("bufferevent_printf failed");
520 if (evbuffer_add(out, "\r\n", 2) == -1) {
521 log_warn("bufferevent_add failed");
528 log_warn("failed to connect to %s:%d",
529 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
530 if (proxy_start_reply(clt, 501, "text/html") == -1)
532 if (tp_error(clt->clt_tp, -1, "Can't connect") == -1)
534 fcgi_end_request(clt, 1);
538 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
542 if (strncmp(mime, "text/gemini", 11) != 0)
545 clt->clt_translate = TR_ENABLED;
547 if ((mime = strchr(mime, ';')) == NULL)
551 while ((t = strsep(&mime, ";")) != NULL) {
552 if (!strncmp(t, "charset=", 8)) {
554 if (!strncasecmp(t, "utf8", 4) ||
555 !strncasecmp(t, "utf-8", 5) ||
556 !strncasecmp(t, "ascii", 5)) {
557 log_debug("unknown charset %s", t);
563 if (!strncmp(t, "lang=", 5)) {
565 if ((semi = strchr(t, ';')) != NULL)
568 if (strlcpy(lang, t, len) >= len) {
569 log_debug("lang too long: %s", t);
583 proxy_start_reply(struct client *clt, int status, const char *ctype)
587 csp = "Content-Security-Policy: default-src 'self'; "
588 "script-src 'none'; object-src 'none';\r\n";
590 if (ctype != NULL && !strcmp(ctype, "text/html"))
591 ctype = "text/html;charset=utf-8";
594 clt_printf(clt, "Status: %d\r\n", status) == -1)
598 clt_printf(clt, "Content-Type: %s\r\n", ctype) == -1)
601 if (clt_puts(clt, csp) == -1)
604 if (clt_puts(clt, "\r\n") == -1)
611 proxy_read(struct bufferevent *bev, void *d)
613 struct client *clt = d;
614 struct evbuffer *src = EVBUFFER_INPUT(bev);
621 if (clt->clt_headersdone) {
622 if (clt->clt_translate)
623 proxy_translate_gemtext(clt);
625 clt_write_bufferevent(clt, bev);
629 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
631 if (EVBUFFER_LENGTH(src) >= 1026)
632 proxy_error(bev, EV_READ, clt);
637 !isdigit((unsigned char)hdr[0]) ||
638 !isdigit((unsigned char)hdr[1]) ||
640 log_warnx("invalid ");
641 proxy_error(bev, EV_READ, clt);
645 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
652 if (proxy_start_reply(clt, 501, "text/html") == -1)
654 if (tp_error(clt->clt_tp, code, &hdr[3]) == -1)
656 fcgi_end_request(clt, 1);
660 mime = hdr + 2 + strspn(hdr + 2, " \t");
661 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
662 if (proxy_start_reply(clt, 501, "text/html") == -1)
664 if (tp_error(clt->clt_tp, -1, "Bad response") == -1)
666 fcgi_end_request(clt, 1);
670 if (clt->clt_translate)
671 ctype = "text/html;charset=utf-8";
675 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
678 clt->clt_headersdone = 1;
680 if (clt->clt_translate &&
681 tp_head(clt->clt_tp, lang, NULL) == -1)
685 * Trigger the read again so we proceed with the response
697 proxy_write(struct bufferevent *bev, void *d)
703 proxy_error(struct bufferevent *bev, short err, void *d)
705 struct client *clt = d;
706 int status = !(err & EVBUFFER_EOF);
708 log_debug("proxy error, shutting down the connection (err: %x)",
711 if (!clt->clt_headersdone) {
712 if (proxy_start_reply(clt, 501, "text/html") == -1)
714 if (tp_error(clt->clt_tp, -1, "Proxy error") == -1)
716 } else if (status == 0) {
717 if (clt->clt_translate & TR_PRE) {
718 if (clt_puts(clt, "</pre>"))
720 clt->clt_translate &= ~TR_PRE;
723 if (clt->clt_translate & TR_LIST) {
724 if (clt_puts(clt, "</ul>") == -1)
726 clt->clt_translate &= ~TR_LIST;
729 if (clt->clt_translate & TR_NAV) {
730 if (clt_puts(clt, "</ul></nav>") == -1)
732 clt->clt_translate &= ~TR_NAV;
735 if (clt->clt_translate &&
736 tp_foot(clt->clt_tp) == -1)
740 fcgi_end_request(clt, status);
744 proxy_tls_readcb(int fd, short event, void *arg)
746 struct bufferevent *bufev = arg;
747 struct client *clt = bufev->cbarg;
748 char rbuf[IBUF_READ_SIZE];
749 int what = EVBUFFER_READ;
750 int howmuch = IBUF_READ_SIZE;
754 if (event == EV_TIMEOUT) {
755 what |= EVBUFFER_TIMEOUT;
759 if (bufev->wm_read.high != 0)
760 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
762 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
763 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
765 } else if (ret == -1) {
766 what |= EVBUFFER_ERROR;
772 what |= EVBUFFER_EOF;
776 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
777 what |= EVBUFFER_ERROR;
781 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
783 len = EVBUFFER_LENGTH(bufev->input);
784 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
786 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
787 struct evbuffer *buf = bufev->input;
788 event_del(&bufev->ev_read);
789 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
793 if (bufev->readcb != NULL)
794 (*bufev->readcb)(bufev, bufev->cbarg);
798 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
802 (*bufev->errorcb)(bufev, what, bufev->cbarg);
806 proxy_bufferevent_add(struct event *ev, int timeout)
808 struct timeval tv, *ptv = NULL;
816 return (event_add(ev, ptv));
820 proxy_tls_writecb(int fd, short event, void *arg)
822 struct bufferevent *bufev = arg;
823 struct client *clt = bufev->cbarg;
825 short what = EVBUFFER_WRITE;
828 if (event == EV_TIMEOUT) {
829 what |= EVBUFFER_TIMEOUT;
833 if (EVBUFFER_LENGTH(bufev->output)) {
834 ret = tls_write(clt->clt_ctx,
835 EVBUFFER_DATA(bufev->output),
836 EVBUFFER_LENGTH(bufev->output));
837 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
839 } else if (ret == -1) {
840 what |= EVBUFFER_ERROR;
844 evbuffer_drain(bufev->output, len);
847 if (EVBUFFER_LENGTH(bufev->output) != 0)
848 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
850 if (bufev->writecb != NULL &&
851 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
852 (*bufev->writecb)(bufev, bufev->cbarg);
856 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
860 (*bufev->errorcb)(bufev, what, bufev->cbarg);
864 proxy_client_free(struct client *clt)
867 event_asr_abort(clt->clt_evasr);
869 if (clt->clt_addrinfo)
870 freeaddrinfo(clt->clt_addrinfo);
872 if (clt->clt_evconn_live)
873 event_del(&clt->clt_evconn);
875 if (clt->clt_fd != -1)
879 tls_free(clt->clt_ctx);
882 bufferevent_free(clt->clt_bev);
885 free(clt->clt_server_name);
886 free(clt->clt_script_name);
887 free(clt->clt_path_info);
888 free(clt->clt_query);