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\r\n",
509 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
510 log_warn("bufferevent_printf failed");
517 log_warn("failed to connect to %s:%d",
518 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
519 if (proxy_start_reply(clt, 501, "text/html") == -1)
521 if (tp_error(clt->clt_tp, -1, "Can't connect") == -1)
523 fcgi_end_request(clt, 1);
527 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
531 if (strncmp(mime, "text/gemini", 11) != 0)
534 clt->clt_translate = TR_ENABLED;
536 if ((mime = strchr(mime, ';')) == NULL)
540 while ((t = strsep(&mime, ";")) != NULL) {
541 if (!strncmp(t, "charset=", 8)) {
543 if (!strncasecmp(t, "utf8", 4) ||
544 !strncasecmp(t, "utf-8", 5) ||
545 !strncasecmp(t, "ascii", 5)) {
546 log_debug("unknown charset %s", t);
552 if (!strncmp(t, "lang=", 5)) {
554 if ((semi = strchr(t, ';')) != NULL)
557 if (strlcpy(lang, t, len) >= len) {
558 log_debug("lang too long: %s", t);
572 proxy_start_reply(struct client *clt, int status, const char *ctype)
576 csp = "Content-Security-Policy: default-src 'self'; "
577 "script-src 'none'; object-src 'none';\r\n";
579 if (ctype != NULL && !strcmp(ctype, "text/html"))
580 ctype = "text/html;charset=utf-8";
583 clt_printf(clt, "Status: %d\r\n", status) == -1)
587 clt_printf(clt, "Content-Type: %s\r\n", ctype) == -1)
590 if (clt_puts(clt, csp) == -1)
593 if (clt_puts(clt, "\r\n") == -1)
600 proxy_read(struct bufferevent *bev, void *d)
602 struct client *clt = d;
603 struct evbuffer *src = EVBUFFER_INPUT(bev);
610 if (clt->clt_headersdone) {
611 if (clt->clt_translate)
612 proxy_translate_gemtext(clt);
614 clt_write_bufferevent(clt, bev);
618 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
620 if (EVBUFFER_LENGTH(src) >= 1026)
621 proxy_error(bev, EV_READ, clt);
626 !isdigit((unsigned char)hdr[0]) ||
627 !isdigit((unsigned char)hdr[1]) ||
629 log_warnx("invalid ");
630 proxy_error(bev, EV_READ, clt);
634 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
641 if (proxy_start_reply(clt, 501, "text/html") == -1)
643 if (tp_error(clt->clt_tp, code, &hdr[3]) == -1)
645 fcgi_end_request(clt, 1);
649 mime = hdr + 2 + strspn(hdr + 2, " \t");
650 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
651 if (proxy_start_reply(clt, 501, "text/html") == -1)
653 if (tp_error(clt->clt_tp, -1, "Bad response") == -1)
655 fcgi_end_request(clt, 1);
659 if (clt->clt_translate)
660 ctype = "text/html;charset=utf-8";
664 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
667 clt->clt_headersdone = 1;
669 if (clt->clt_translate &&
670 tp_head(clt->clt_tp, lang, NULL) == -1)
674 * Trigger the read again so we proceed with the response
686 proxy_write(struct bufferevent *bev, void *d)
692 proxy_error(struct bufferevent *bev, short err, void *d)
694 struct client *clt = d;
695 int status = !(err & EVBUFFER_EOF);
697 log_debug("proxy error, shutting down the connection (err: %x)",
700 if (!clt->clt_headersdone) {
701 if (proxy_start_reply(clt, 501, "text/html") == -1)
703 if (tp_error(clt->clt_tp, -1, "Proxy error") == -1)
705 } else if (status == 0) {
706 if (clt->clt_translate & TR_PRE) {
707 if (clt_puts(clt, "</pre>"))
709 clt->clt_translate &= ~TR_PRE;
712 if (clt->clt_translate & TR_LIST) {
713 if (clt_puts(clt, "</ul>") == -1)
715 clt->clt_translate &= ~TR_LIST;
718 if (clt->clt_translate & TR_NAV) {
719 if (clt_puts(clt, "</ul></nav>") == -1)
721 clt->clt_translate &= ~TR_NAV;
724 if (clt->clt_translate &&
725 tp_foot(clt->clt_tp) == -1)
729 fcgi_end_request(clt, status);
733 proxy_tls_readcb(int fd, short event, void *arg)
735 struct bufferevent *bufev = arg;
736 struct client *clt = bufev->cbarg;
737 char rbuf[IBUF_READ_SIZE];
738 int what = EVBUFFER_READ;
739 int howmuch = IBUF_READ_SIZE;
743 if (event == EV_TIMEOUT) {
744 what |= EVBUFFER_TIMEOUT;
748 if (bufev->wm_read.high != 0)
749 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
751 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
752 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
754 } else if (ret == -1) {
755 what |= EVBUFFER_ERROR;
761 what |= EVBUFFER_EOF;
765 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
766 what |= EVBUFFER_ERROR;
770 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
772 len = EVBUFFER_LENGTH(bufev->input);
773 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
775 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
776 struct evbuffer *buf = bufev->input;
777 event_del(&bufev->ev_read);
778 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
782 if (bufev->readcb != NULL)
783 (*bufev->readcb)(bufev, bufev->cbarg);
787 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
791 (*bufev->errorcb)(bufev, what, bufev->cbarg);
795 proxy_bufferevent_add(struct event *ev, int timeout)
797 struct timeval tv, *ptv = NULL;
805 return (event_add(ev, ptv));
809 proxy_tls_writecb(int fd, short event, void *arg)
811 struct bufferevent *bufev = arg;
812 struct client *clt = bufev->cbarg;
814 short what = EVBUFFER_WRITE;
817 if (event == EV_TIMEOUT) {
818 what |= EVBUFFER_TIMEOUT;
822 if (EVBUFFER_LENGTH(bufev->output)) {
823 ret = tls_write(clt->clt_ctx,
824 EVBUFFER_DATA(bufev->output),
825 EVBUFFER_LENGTH(bufev->output));
826 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
828 } else if (ret == -1) {
829 what |= EVBUFFER_ERROR;
833 evbuffer_drain(bufev->output, len);
836 if (EVBUFFER_LENGTH(bufev->output) != 0)
837 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
839 if (bufev->writecb != NULL &&
840 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
841 (*bufev->writecb)(bufev, bufev->cbarg);
845 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
849 (*bufev->errorcb)(bufev, what, bufev->cbarg);
853 proxy_client_free(struct client *clt)
856 event_asr_abort(clt->clt_evasr);
858 if (clt->clt_addrinfo)
859 freeaddrinfo(clt->clt_addrinfo);
861 if (clt->clt_evconn_live)
862 event_del(&clt->clt_evconn);
864 if (clt->clt_fd != -1)
868 tls_free(clt->clt_ctx);
871 bufferevent_free(clt->clt_bev);
874 free(clt->clt_server_name);
875 free(clt->clt_script_name);
876 free(clt->clt_path_info);