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;
361 if ((clt->clt_pc = proxy_server_match(env, clt)) == NULL) {
362 if (proxy_start_reply(clt, 501, "text/html") == -1)
364 if (tp_error(clt->clt_tp, -1, "unknown server") == -1)
366 return (fcgi_end_request(clt, 1));
369 if (clt->clt_bodylen != 0 && clt->clt_body == NULL) {
370 if (proxy_start_reply(clt, 400, "text/html") == -1)
372 if (tp_error(clt->clt_tp, -1, "bad request") == -1)
374 return (fcgi_end_request(clt, 1));
378 r = asprintf(&url, "%s%s?%s", clt->clt_script_name,
379 clt->clt_path_info + 1, clt->clt_body);
381 return (fcgi_end_request(clt, 1));
383 if (proxy_start_reply(clt, 302, url) == -1 ||
384 fcgi_end_request(clt, 1) == -1) {
392 (void)snprintf(port, sizeof(port), "%d", clt->clt_pc->proxy_port);
394 memset(&hints, 0, sizeof(hints));
395 hints.ai_family = AF_UNSPEC;
396 hints.ai_socktype = SOCK_STREAM;
398 query = getaddrinfo_async(clt->clt_pc->proxy_addr, port, &hints, NULL);
400 log_warn("getaddrinfo_async");
401 return (fcgi_abort_request(clt));
404 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
405 if (clt->clt_evasr == NULL) {
406 log_warn("event_asr_run");
408 return (fcgi_abort_request(clt));
415 proxy_resolved(struct asr_result *res, void *d)
417 struct client *clt = d;
418 struct proxy_config *pc = clt->clt_pc;
420 clt->clt_evasr = NULL;
422 if (res->ar_gai_errno != 0) {
423 log_warnx("failed to resolve %s:%d: %s",
424 pc->proxy_addr, pc->proxy_port,
425 gai_strerror(res->ar_gai_errno));
426 if (proxy_start_reply(clt, 501, "text/html") == -1)
428 if (tp_error(clt->clt_tp, -1, "Can't resolve host") == -1)
430 fcgi_end_request(clt, 1);
434 clt->clt_addrinfo = res->ar_addrinfo;
435 clt->clt_p = clt->clt_addrinfo;
436 proxy_connect(-1, 0, clt);
440 proxy_connect(int fd, short ev, void *d)
442 struct client *clt = d;
443 struct evbuffer *out;
445 struct tls_config *conf;
446 struct timeval conntv = {5, 0};
448 socklen_t len = sizeof(err);
451 if (clt->clt_p == NULL)
454 if (clt->clt_fd != -1) {
455 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
466 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
468 if (clt->clt_fd == -1) {
469 clt->clt_p = clt->clt_p->ai_next;
473 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
476 clt->clt_evconn_live = 1;
477 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
478 event_add(&clt->clt_evconn, &conntv);
482 clt->clt_evconn_live = 0;
483 freeaddrinfo(clt->clt_addrinfo);
484 clt->clt_addrinfo = clt->clt_p = NULL;
486 /* initialize TLS for Gemini */
487 if ((conf = tls_config_new()) == NULL) {
488 log_warn("tls_config_new failed");
492 tls_config_insecure_noverifycert(conf);
494 if ((clt->clt_ctx = tls_client()) == NULL) {
495 log_warnx("tls_client failed");
496 tls_config_free(conf);
500 if (tls_configure(clt->clt_ctx, conf) == -1) {
501 log_warnx("tls_configure failed");
502 tls_config_free(conf);
506 tls_config_free(conf);
508 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
509 clt->clt_pc->proxy_name) == -1) {
510 log_warnx("tls_connect_socket failed");
514 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
516 if (clt->clt_bev == NULL) {
517 log_warn("bufferevent_new");
520 out = EVBUFFER_OUTPUT(clt->clt_bev);
522 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
523 proxy_tls_readcb, clt->clt_bev);
524 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
525 proxy_tls_writecb, clt->clt_bev);
527 /* bufferevent_settimeout(); */
528 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
530 /* TODO: compute the URL */
531 if (evbuffer_add_printf(out, "gemini://%s/%s",
532 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
533 log_warn("bufferevent_printf failed");
537 if (clt->clt_query &&
538 evbuffer_add_printf(out, "?%s", clt->clt_query) == -1) {
539 log_warn("bufferevent_printf failed");
543 if (evbuffer_add(out, "\r\n", 2) == -1) {
544 log_warn("bufferevent_add failed");
551 log_warn("failed to connect to %s:%d",
552 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
553 if (proxy_start_reply(clt, 501, "text/html") == -1)
555 if (tp_error(clt->clt_tp, -1, "Can't connect") == -1)
557 fcgi_end_request(clt, 1);
561 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
565 if (strncmp(mime, "text/gemini", 11) != 0)
568 clt->clt_translate = TR_ENABLED;
570 if ((mime = strchr(mime, ';')) == NULL)
574 while ((t = strsep(&mime, ";")) != NULL) {
575 if (!strncmp(t, "charset=", 8)) {
577 if (!strncasecmp(t, "utf8", 4) ||
578 !strncasecmp(t, "utf-8", 5) ||
579 !strncasecmp(t, "ascii", 5)) {
580 log_debug("unknown charset %s", t);
586 if (!strncmp(t, "lang=", 5)) {
588 if ((semi = strchr(t, ';')) != NULL)
591 if (strlcpy(lang, t, len) >= len) {
592 log_debug("lang too long: %s", t);
606 proxy_start_reply(struct client *clt, int status, const char *ctype)
610 csp = "Content-Security-Policy: default-src 'self'; "
611 "script-src 'none'; object-src 'none';\r\n";
614 clt_printf(clt, "Status: %d\r\n", status) == -1)
617 if (clt_puts(clt, csp) == -1)
621 /* use "ctype" as redirect target */
622 if (clt_printf(clt, "Location: %s\r\n", ctype) == -1)
624 if (clt_puts(clt, "\r\n") == -1)
630 if (!strcmp(ctype, "text/html"))
631 ctype = "text/html;charset=utf-8";
632 if (clt_printf(clt, "Content-Type: %s\r\n", ctype)
637 if (clt_puts(clt, "\r\n") == -1)
644 proxy_read(struct bufferevent *bev, void *d)
646 struct client *clt = d;
647 struct evbuffer *src = EVBUFFER_INPUT(bev);
654 if (clt->clt_headersdone) {
655 if (clt->clt_translate)
656 proxy_translate_gemtext(clt);
658 clt_write_bufferevent(clt, bev);
662 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
664 if (EVBUFFER_LENGTH(src) >= 1026)
665 proxy_error(bev, EV_READ, clt);
670 !isdigit((unsigned char)hdr[0]) ||
671 !isdigit((unsigned char)hdr[1]) ||
673 log_warnx("invalid ");
674 proxy_error(bev, EV_READ, clt);
678 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
682 if (proxy_start_reply(clt, 200, "text/html") == -1)
684 if (tp_inputpage(clt->clt_tp, &hdr[3]) == -1)
686 fcgi_end_request(clt, 0);
692 if (proxy_start_reply(clt, 501, "text/html") == -1)
694 if (tp_error(clt->clt_tp, code, &hdr[3]) == -1)
696 fcgi_end_request(clt, 1);
700 mime = hdr + 2 + strspn(hdr + 2, " \t");
701 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
702 if (proxy_start_reply(clt, 501, "text/html") == -1)
704 if (tp_error(clt->clt_tp, -1, "Bad response") == -1)
706 fcgi_end_request(clt, 1);
710 if (clt->clt_translate)
711 ctype = "text/html;charset=utf-8";
715 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
718 clt->clt_headersdone = 1;
720 if (clt->clt_translate &&
721 tp_head(clt->clt_tp, lang, NULL) == -1)
725 * Trigger the read again so we proceed with the response
737 proxy_write(struct bufferevent *bev, void *d)
743 proxy_error(struct bufferevent *bev, short err, void *d)
745 struct client *clt = d;
746 int status = !(err & EVBUFFER_EOF);
748 log_debug("proxy error, shutting down the connection (err: %x)",
751 if (!clt->clt_headersdone) {
752 if (proxy_start_reply(clt, 501, "text/html") == -1)
754 if (tp_error(clt->clt_tp, -1, "Proxy error") == -1)
756 } else if (status == 0) {
757 if (clt->clt_translate & TR_PRE) {
758 if (clt_puts(clt, "</pre>"))
760 clt->clt_translate &= ~TR_PRE;
763 if (clt->clt_translate & TR_LIST) {
764 if (clt_puts(clt, "</ul>") == -1)
766 clt->clt_translate &= ~TR_LIST;
769 if (clt->clt_translate & TR_NAV) {
770 if (clt_puts(clt, "</ul></nav>") == -1)
772 clt->clt_translate &= ~TR_NAV;
775 if (clt->clt_translate &&
776 tp_foot(clt->clt_tp) == -1)
780 fcgi_end_request(clt, status);
784 proxy_tls_readcb(int fd, short event, void *arg)
786 struct bufferevent *bufev = arg;
787 struct client *clt = bufev->cbarg;
788 char rbuf[IBUF_READ_SIZE];
789 int what = EVBUFFER_READ;
790 int howmuch = IBUF_READ_SIZE;
794 if (event == EV_TIMEOUT) {
795 what |= EVBUFFER_TIMEOUT;
799 if (bufev->wm_read.high != 0)
800 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
802 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
803 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
805 } else if (ret == -1) {
806 what |= EVBUFFER_ERROR;
812 what |= EVBUFFER_EOF;
816 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
817 what |= EVBUFFER_ERROR;
821 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
823 len = EVBUFFER_LENGTH(bufev->input);
824 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
826 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
827 struct evbuffer *buf = bufev->input;
828 event_del(&bufev->ev_read);
829 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
833 if (bufev->readcb != NULL)
834 (*bufev->readcb)(bufev, bufev->cbarg);
838 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
842 (*bufev->errorcb)(bufev, what, bufev->cbarg);
846 proxy_bufferevent_add(struct event *ev, int timeout)
848 struct timeval tv, *ptv = NULL;
856 return (event_add(ev, ptv));
860 proxy_tls_writecb(int fd, short event, void *arg)
862 struct bufferevent *bufev = arg;
863 struct client *clt = bufev->cbarg;
865 short what = EVBUFFER_WRITE;
868 if (event == EV_TIMEOUT) {
869 what |= EVBUFFER_TIMEOUT;
873 if (EVBUFFER_LENGTH(bufev->output)) {
874 ret = tls_write(clt->clt_ctx,
875 EVBUFFER_DATA(bufev->output),
876 EVBUFFER_LENGTH(bufev->output));
877 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
879 } else if (ret == -1) {
880 what |= EVBUFFER_ERROR;
884 evbuffer_drain(bufev->output, len);
887 if (EVBUFFER_LENGTH(bufev->output) != 0)
888 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
890 if (bufev->writecb != NULL &&
891 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
892 (*bufev->writecb)(bufev, bufev->cbarg);
896 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
900 (*bufev->errorcb)(bufev, what, bufev->cbarg);
904 proxy_client_free(struct client *clt)
907 event_asr_abort(clt->clt_evasr);
909 if (clt->clt_addrinfo)
910 freeaddrinfo(clt->clt_addrinfo);
912 if (clt->clt_evconn_live)
913 event_del(&clt->clt_evconn);
915 if (clt->clt_fd != -1)
919 tls_free(clt->clt_ctx);
922 bufferevent_free(clt->clt_bev);
926 free(clt->clt_server_name);
927 free(clt->clt_script_name);
928 free(clt->clt_path_info);
929 free(clt->clt_query);