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, "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, "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, "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);
609 if (clt->clt_headersdone) {
610 if (clt->clt_translate)
611 proxy_translate_gemtext(clt);
613 clt_write_bufferevent(clt, bev);
617 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
619 if (EVBUFFER_LENGTH(src) >= 1026)
620 proxy_error(bev, EV_READ, clt);
625 !isdigit((unsigned char)hdr[0]) ||
626 !isdigit((unsigned char)hdr[1]) ||
628 log_warnx("invalid ");
629 proxy_error(bev, EV_READ, clt);
638 if (proxy_start_reply(clt, 501, "text/html") == -1)
640 if (tp_error(clt->clt_tp, &hdr[3]) == -1)
642 fcgi_end_request(clt, 1);
646 mime = hdr + 2 + strspn(hdr + 2, " \t");
647 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
648 if (proxy_start_reply(clt, 501, "text/html") == -1)
650 if (tp_error(clt->clt_tp, "Bad response") == -1)
652 fcgi_end_request(clt, 1);
656 if (clt->clt_translate)
657 ctype = "text/html;charset=utf-8";
661 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
664 clt->clt_headersdone = 1;
666 if (clt->clt_translate &&
667 tp_head(clt->clt_tp, lang, NULL) == -1)
671 * Trigger the read again so we proceed with the response
683 proxy_write(struct bufferevent *bev, void *d)
689 proxy_error(struct bufferevent *bev, short err, void *d)
691 struct client *clt = d;
692 int status = !(err & EVBUFFER_EOF);
694 log_debug("proxy error, shutting down the connection (err: %x)",
697 if (!clt->clt_headersdone) {
698 if (proxy_start_reply(clt, 501, "text/html") == -1)
700 if (tp_error(clt->clt_tp, "Proxy error") == -1)
702 } else if (status == 0) {
703 if (clt->clt_translate & TR_PRE) {
704 if (clt_puts(clt, "</pre>"))
706 clt->clt_translate &= ~TR_PRE;
709 if (clt->clt_translate & TR_LIST) {
710 if (clt_puts(clt, "</ul>") == -1)
712 clt->clt_translate &= ~TR_LIST;
715 if (clt->clt_translate & TR_NAV) {
716 if (clt_puts(clt, "</ul></nav>") == -1)
718 clt->clt_translate &= ~TR_NAV;
721 if (clt->clt_translate &&
722 tp_foot(clt->clt_tp) == -1)
726 fcgi_end_request(clt, status);
730 proxy_tls_readcb(int fd, short event, void *arg)
732 struct bufferevent *bufev = arg;
733 struct client *clt = bufev->cbarg;
734 char rbuf[IBUF_READ_SIZE];
735 int what = EVBUFFER_READ;
736 int howmuch = IBUF_READ_SIZE;
740 if (event == EV_TIMEOUT) {
741 what |= EVBUFFER_TIMEOUT;
745 if (bufev->wm_read.high != 0)
746 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
748 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
749 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
751 } else if (ret == -1) {
752 what |= EVBUFFER_ERROR;
758 what |= EVBUFFER_EOF;
762 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
763 what |= EVBUFFER_ERROR;
767 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
769 len = EVBUFFER_LENGTH(bufev->input);
770 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
772 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
773 struct evbuffer *buf = bufev->input;
774 event_del(&bufev->ev_read);
775 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
779 if (bufev->readcb != NULL)
780 (*bufev->readcb)(bufev, bufev->cbarg);
784 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
788 (*bufev->errorcb)(bufev, what, bufev->cbarg);
792 proxy_bufferevent_add(struct event *ev, int timeout)
794 struct timeval tv, *ptv = NULL;
802 return (event_add(ev, ptv));
806 proxy_tls_writecb(int fd, short event, void *arg)
808 struct bufferevent *bufev = arg;
809 struct client *clt = bufev->cbarg;
811 short what = EVBUFFER_WRITE;
814 if (event == EV_TIMEOUT) {
815 what |= EVBUFFER_TIMEOUT;
819 if (EVBUFFER_LENGTH(bufev->output)) {
820 ret = tls_write(clt->clt_ctx,
821 EVBUFFER_DATA(bufev->output),
822 EVBUFFER_LENGTH(bufev->output));
823 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
825 } else if (ret == -1) {
826 what |= EVBUFFER_ERROR;
830 evbuffer_drain(bufev->output, len);
833 if (EVBUFFER_LENGTH(bufev->output) != 0)
834 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
836 if (bufev->writecb != NULL &&
837 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
838 (*bufev->writecb)(bufev, bufev->cbarg);
842 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
846 (*bufev->errorcb)(bufev, what, bufev->cbarg);
850 proxy_client_free(struct client *clt)
853 event_asr_abort(clt->clt_evasr);
855 if (clt->clt_addrinfo)
856 freeaddrinfo(clt->clt_addrinfo);
858 if (clt->clt_evconn_live)
859 event_del(&clt->clt_evconn);
861 if (clt->clt_fd != -1)
865 tls_free(clt->clt_ctx);
868 bufferevent_free(clt->clt_bev);
871 free(clt->clt_server_name);
872 free(clt->clt_script_name);
873 free(clt->clt_path_info);