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 *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_getproxy(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 struct proxy_config *
338 proxy_match(struct galileo *env, const char *name)
345 TAILQ_FOREACH(pr, &env->sc_proxies, pr_entry) {
346 if (!strcmp(name, pr->pr_conf.host))
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_match(env, clt->clt_server_name)) == 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 memset(&hints, 0, sizeof(hints));
393 hints.ai_family = AF_UNSPEC;
394 hints.ai_socktype = SOCK_STREAM;
396 query = getaddrinfo_async(clt->clt_pc->proxy_addr,
397 clt->clt_pc->proxy_port, &hints, NULL);
399 log_warn("getaddrinfo_async");
400 return (fcgi_abort_request(clt));
403 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
404 if (clt->clt_evasr == NULL) {
405 log_warn("event_asr_run");
407 return (fcgi_abort_request(clt));
414 proxy_resolved(struct asr_result *res, void *d)
416 struct client *clt = d;
417 struct proxy_config *pc = clt->clt_pc;
419 clt->clt_evasr = NULL;
421 if (res->ar_gai_errno != 0) {
422 log_warnx("failed to resolve %s:%s: %s",
423 pc->proxy_addr, pc->proxy_port,
424 gai_strerror(res->ar_gai_errno));
425 if (proxy_start_reply(clt, 501, "text/html") == -1)
427 if (tp_error(clt->clt_tp, -1, "Can't resolve host") == -1)
429 fcgi_end_request(clt, 1);
433 clt->clt_addrinfo = res->ar_addrinfo;
434 clt->clt_p = clt->clt_addrinfo;
435 proxy_connect(-1, 0, clt);
439 proxy_connect(int fd, short ev, void *d)
441 struct client *clt = d;
442 struct evbuffer *out;
444 struct tls_config *conf;
445 struct timeval conntv = {5, 0};
447 socklen_t len = sizeof(err);
450 if (clt->clt_p == NULL)
453 if (clt->clt_fd != -1) {
454 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
465 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
467 if (clt->clt_fd == -1) {
468 clt->clt_p = clt->clt_p->ai_next;
472 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
475 clt->clt_evconn_live = 1;
476 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
477 event_add(&clt->clt_evconn, &conntv);
481 clt->clt_evconn_live = 0;
482 freeaddrinfo(clt->clt_addrinfo);
483 clt->clt_addrinfo = clt->clt_p = NULL;
485 /* initialize TLS for Gemini */
486 if ((conf = tls_config_new()) == NULL) {
487 log_warn("tls_config_new failed");
491 tls_config_insecure_noverifycert(conf);
493 if ((clt->clt_ctx = tls_client()) == NULL) {
494 log_warnx("tls_client failed");
495 tls_config_free(conf);
499 if (tls_configure(clt->clt_ctx, conf) == -1) {
500 log_warnx("tls_configure failed");
501 tls_config_free(conf);
505 tls_config_free(conf);
507 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
508 clt->clt_pc->proxy_name) == -1) {
509 log_warnx("tls_connect_socket failed");
513 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
515 if (clt->clt_bev == NULL) {
516 log_warn("bufferevent_new");
519 out = EVBUFFER_OUTPUT(clt->clt_bev);
521 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
522 proxy_tls_readcb, clt->clt_bev);
523 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
524 proxy_tls_writecb, clt->clt_bev);
526 /* bufferevent_settimeout(); */
527 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
529 /* TODO: compute the URL */
530 if (evbuffer_add_printf(out, "gemini://%s/%s",
531 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
532 log_warn("bufferevent_printf failed");
536 if (clt->clt_query &&
537 evbuffer_add_printf(out, "?%s", clt->clt_query) == -1) {
538 log_warn("bufferevent_printf failed");
542 if (evbuffer_add(out, "\r\n", 2) == -1) {
543 log_warn("bufferevent_add failed");
550 log_warn("failed to connect to %s:%s",
551 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
552 if (proxy_start_reply(clt, 501, "text/html") == -1)
554 if (tp_error(clt->clt_tp, -1, "Can't connect") == -1)
556 fcgi_end_request(clt, 1);
560 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
564 if (strncmp(mime, "text/gemini", 11) != 0)
567 clt->clt_translate = TR_ENABLED;
569 if ((mime = strchr(mime, ';')) == NULL)
573 while ((t = strsep(&mime, ";")) != NULL) {
574 if (!strncmp(t, "charset=", 8)) {
576 if (!strncasecmp(t, "utf8", 4) ||
577 !strncasecmp(t, "utf-8", 5) ||
578 !strncasecmp(t, "ascii", 5)) {
579 log_debug("unknown charset %s", t);
585 if (!strncmp(t, "lang=", 5)) {
587 if ((semi = strchr(t, ';')) != NULL)
590 if (strlcpy(lang, t, len) >= len) {
591 log_debug("lang too long: %s", t);
605 proxy_start_reply(struct client *clt, int status, const char *ctype)
609 csp = "Content-Security-Policy: default-src 'self'; "
610 "script-src 'none'; object-src 'none';\r\n";
613 clt_printf(clt, "Status: %d\r\n", status) == -1)
616 if (clt_puts(clt, csp) == -1)
620 /* use "ctype" as redirect target */
621 if (clt_printf(clt, "Location: %s\r\n", ctype) == -1)
623 if (clt_puts(clt, "\r\n") == -1)
629 if (!strcmp(ctype, "text/html"))
630 ctype = "text/html;charset=utf-8";
631 if (clt_printf(clt, "Content-Type: %s\r\n", ctype)
636 if (clt_puts(clt, "\r\n") == -1)
643 proxy_read(struct bufferevent *bev, void *d)
645 struct client *clt = d;
646 struct evbuffer *src = EVBUFFER_INPUT(bev);
653 if (clt->clt_headersdone) {
654 if (clt->clt_translate)
655 proxy_translate_gemtext(clt);
657 clt_write_bufferevent(clt, bev);
661 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
663 if (EVBUFFER_LENGTH(src) >= 1026)
664 proxy_error(bev, EV_READ, clt);
669 !isdigit((unsigned char)hdr[0]) ||
670 !isdigit((unsigned char)hdr[1]) ||
672 log_warnx("invalid ");
673 proxy_error(bev, EV_READ, clt);
677 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
681 if (proxy_start_reply(clt, 200, "text/html") == -1)
683 if (tp_inputpage(clt->clt_tp, &hdr[3]) == -1)
685 fcgi_end_request(clt, 0);
691 /* XXX: do proper parsing */
692 if (hdr[3] == '/' || strstr(&hdr[3], "//") == NULL) {
695 if (asprintf(&url, "%s%s", clt->clt_script_name,
699 if (proxy_start_reply(clt, 302, url)) {
704 fcgi_end_request(clt, 0);
709 if (proxy_start_reply(clt, 501, "text/html") == -1)
711 if (tp_error(clt->clt_tp, code, &hdr[3]) == -1)
713 fcgi_end_request(clt, 1);
717 mime = hdr + 2 + strspn(hdr + 2, " \t");
718 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
719 if (proxy_start_reply(clt, 501, "text/html") == -1)
721 if (tp_error(clt->clt_tp, -1, "Bad response") == -1)
723 fcgi_end_request(clt, 1);
727 if (clt->clt_translate)
728 ctype = "text/html;charset=utf-8";
732 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
735 clt->clt_headersdone = 1;
737 if (clt->clt_translate &&
738 tp_head(clt->clt_tp, lang, NULL) == -1)
742 * Trigger the read again so we proceed with the response
754 proxy_write(struct bufferevent *bev, void *d)
760 proxy_error(struct bufferevent *bev, short err, void *d)
762 struct client *clt = d;
763 int status = !(err & EVBUFFER_EOF);
765 log_debug("proxy error, shutting down the connection (err: %x)",
768 if (!clt->clt_headersdone) {
769 if (proxy_start_reply(clt, 501, "text/html") == -1)
771 if (tp_error(clt->clt_tp, -1, "Proxy error") == -1)
773 } else if (status == 0) {
774 if (clt->clt_translate & TR_PRE) {
775 if (clt_puts(clt, "</pre>"))
777 clt->clt_translate &= ~TR_PRE;
780 if (clt->clt_translate & TR_LIST) {
781 if (clt_puts(clt, "</ul>") == -1)
783 clt->clt_translate &= ~TR_LIST;
786 if (clt->clt_translate & TR_NAV) {
787 if (clt_puts(clt, "</ul></nav>") == -1)
789 clt->clt_translate &= ~TR_NAV;
792 if (clt->clt_translate &&
793 tp_foot(clt->clt_tp) == -1)
797 fcgi_end_request(clt, status);
801 proxy_tls_readcb(int fd, short event, void *arg)
803 struct bufferevent *bufev = arg;
804 struct client *clt = bufev->cbarg;
805 char rbuf[IBUF_READ_SIZE];
806 int what = EVBUFFER_READ;
807 int howmuch = IBUF_READ_SIZE;
811 if (event == EV_TIMEOUT) {
812 what |= EVBUFFER_TIMEOUT;
816 if (bufev->wm_read.high != 0)
817 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
819 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
820 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
822 } else if (ret == -1) {
823 what |= EVBUFFER_ERROR;
829 what |= EVBUFFER_EOF;
833 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
834 what |= EVBUFFER_ERROR;
838 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
840 len = EVBUFFER_LENGTH(bufev->input);
841 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
843 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
844 struct evbuffer *buf = bufev->input;
845 event_del(&bufev->ev_read);
846 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
850 if (bufev->readcb != NULL)
851 (*bufev->readcb)(bufev, bufev->cbarg);
855 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
859 (*bufev->errorcb)(bufev, what, bufev->cbarg);
863 proxy_bufferevent_add(struct event *ev, int timeout)
865 struct timeval tv, *ptv = NULL;
873 return (event_add(ev, ptv));
877 proxy_tls_writecb(int fd, short event, void *arg)
879 struct bufferevent *bufev = arg;
880 struct client *clt = bufev->cbarg;
882 short what = EVBUFFER_WRITE;
885 if (event == EV_TIMEOUT) {
886 what |= EVBUFFER_TIMEOUT;
890 if (EVBUFFER_LENGTH(bufev->output)) {
891 ret = tls_write(clt->clt_ctx,
892 EVBUFFER_DATA(bufev->output),
893 EVBUFFER_LENGTH(bufev->output));
894 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
896 } else if (ret == -1) {
897 what |= EVBUFFER_ERROR;
901 evbuffer_drain(bufev->output, len);
904 if (EVBUFFER_LENGTH(bufev->output) != 0)
905 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
907 if (bufev->writecb != NULL &&
908 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
909 (*bufev->writecb)(bufev, bufev->cbarg);
913 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
917 (*bufev->errorcb)(bufev, what, bufev->cbarg);
921 proxy_client_free(struct client *clt)
924 event_asr_abort(clt->clt_evasr);
926 if (clt->clt_addrinfo)
927 freeaddrinfo(clt->clt_addrinfo);
929 if (clt->clt_evconn_live)
930 event_del(&clt->clt_evconn);
932 if (clt->clt_fd != -1)
936 tls_free(clt->clt_ctx);
939 bufferevent_free(clt->clt_bev);
943 free(clt->clt_server_name);
944 free(clt->clt_script_name);
945 free(clt->clt_path_info);
946 free(clt->clt_query);