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 void proxy_read(struct bufferevent *, void *);
62 void proxy_write(struct bufferevent *, void *);
63 void proxy_error(struct bufferevent *, short, void *);
64 int proxy_bufferevent_add(struct event *, int);
65 void proxy_tls_writecb(int, short, void *);
66 void proxy_tls_readcb(int, short, void *);
68 static struct privsep_proc procs[] = {
69 { "parent", PROC_PARENT, proxy_dispatch_parent },
72 volatile int proxy_clients;
73 volatile int proxy_inflight;
74 uint32_t proxy_fcg_id;
77 proxy(struct privsep *ps, struct privsep_proc *p)
79 proc_run(ps, p, procs, nitems(procs), proxy_init, NULL);
83 proxy_init(struct privsep *ps, struct privsep_proc *p, void *arg)
85 if (config_init(ps->ps_env) == -1)
86 fatal("failed to initialize configuration");
88 /* We use a custom shutdown callback */
89 /* p->p_shutdown = proxy_shutdown */
91 if (pledge("stdio recvfd unix inet dns", NULL) == -1)
96 proxy_launch(struct galileo *env)
98 event_add(&env->sc_evsock, NULL);
103 proxy_purge(struct server *srv)
108 proxy_inflight_dec(const char *why)
111 log_debug("%s: inflight decremented, now %d, %s",
112 __func__, proxy_inflight, why);
116 proxy_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
118 struct privsep *ps = p->p_ps;
119 struct galileo *env = ps->ps_env;
121 switch (imsg->hdr.type) {
123 if (config_getserver(env, imsg) == -1)
124 fatal("config_getproxy");
129 if (env->sc_sock_fd != -1) {
130 event_del(&env->sc_evsock);
131 close(env->sc_sock_fd);
134 env->sc_sock_fd = config_getsock(env, imsg);
135 if (env->sc_sock_fd == -1)
136 fatal("config_getsock");
138 event_set(&env->sc_evsock, env->sc_sock_fd,
139 EV_READ | EV_PERSIST, fcgi_accept, env);
140 event_add(&env->sc_evsock, NULL);
141 evtimer_set(&env->sc_evpause, fcgi_accept, env);
144 log_debug("config done!");
150 log_warnx("unknown message %d", imsg->hdr.type);
158 printurl(struct client *clt, const char *str)
160 for (; *str; ++str) {
166 if (clt_printf(clt, "%2X", (unsigned char)*str) == -1)
170 if (clt_putc(clt, *str) == -1)
180 htmlescape(struct client *clt, const char *str)
184 for (; *str; ++str) {
187 r = clt_puts(clt, "<");
190 r = clt_puts(clt, ">");
193 r = clt_puts(clt, "&");
196 r = clt_putc(clt, *str);
208 gemtext_translate_line(struct client *clt, char *line)
210 /* preformatted line / closing */
211 if (clt->clt_translate & TR_PRE) {
212 if (!strncmp(line, "```", 3)) {
213 clt->clt_translate &= ~TR_PRE;
214 return (clt_puts(clt, "</pre>"));
217 if (htmlescape(clt, line) == -1)
219 return (clt_putc(clt, '\n'));
223 if (!strncmp(line, "* ", 2)) {
224 if (clt->clt_translate & TR_NAV) {
225 if (clt_puts(clt, "</ul></nav>") == -1)
227 clt->clt_translate &= ~TR_NAV;
230 if (!(clt->clt_translate & TR_LIST)) {
231 if (clt_puts(clt, "<ul>") == -1)
233 clt->clt_translate |= TR_LIST;
236 if (clt_puts(clt, "<li>") == -1 ||
237 htmlescape(clt, line + 2) == -1 ||
238 clt_puts(clt, "</li>") == -1)
243 if (clt->clt_translate & TR_LIST) {
244 if (clt_puts(clt, "</ul>") == -1)
246 clt->clt_translate &= ~TR_LIST;
249 /* link -- TODO: relativify from SCRIPT_NAME */
250 if (!strncmp(line, "=>", 2)) {
254 line += strspn(line, " \t");
256 label = line + strcspn(line, " \t");
262 if (fnmatch("*.jpg", line, 0) == 0 ||
263 fnmatch("*.jpeg", line, 0) == 0 ||
264 fnmatch("*.gif", line, 0) == 0 ||
265 fnmatch("*.png", line, 0) == 0 ||
266 fnmatch("*.svg", line, 0) == 0 ||
267 fnmatch("*.webp", line, 0) == 0) {
268 if (clt->clt_translate & TR_NAV) {
269 if (clt_puts(clt, "</ul></nav>") == -1)
271 clt->clt_translate &= ~TR_NAV;
274 if (tp_figure(clt->clt_tp, line, label) == -1)
280 if (!(clt->clt_translate & TR_NAV)) {
281 if (clt_puts(clt, "<nav><ul>") == -1)
283 clt->clt_translate |= TR_NAV;
286 if (clt_puts(clt, "<li><a href='") == -1 ||
287 printurl(clt, line) == -1 ||
288 clt_puts(clt, "'>") == -1 ||
289 htmlescape(clt, label) == -1 ||
290 clt_puts(clt, "</a></li>") == -1)
296 if (clt->clt_translate & TR_NAV) {
297 if (clt_puts(clt, "</ul></nav>") == -1)
299 clt->clt_translate &= ~TR_NAV;
303 if (!strncmp(line, "```", 3)) {
304 clt->clt_translate |= TR_PRE;
305 return (clt_puts(clt, "<pre>"));
310 if (clt_puts(clt, "<blockquote>") == -1 ||
311 htmlescape(clt, line + 1) == -1 ||
312 clt_puts(clt, "</blockquote>") == -1)
318 if (!strncmp(line, "###", 3)) {
319 if (clt_puts(clt, "<h3>") == -1 ||
320 htmlescape(clt, line + 3) == -1 ||
321 clt_puts(clt, "</h3>") == -1)
325 if (!strncmp(line, "##", 2)) {
326 if (clt_puts(clt, "<h2>") == -1 ||
327 htmlescape(clt, line + 2) == -1 ||
328 clt_puts(clt, "</h2>") == -1)
332 if (!strncmp(line, "#", 1)) {
333 if (clt_puts(clt, "<h1>") == -1 ||
334 htmlescape(clt, line + 1) == -1 ||
335 clt_puts(clt, "</h1>") == -1)
340 /* Not following strictly the gemini specification... */
345 if (clt_puts(clt, "<p>") == -1 ||
346 htmlescape(clt, line) == -1 ||
347 clt_puts(clt, "</p>") == -1)
354 proxy_translate_gemtext(struct client *clt)
356 struct bufferevent *bev = clt->clt_bev;
357 struct evbuffer *src = EVBUFFER_INPUT(bev);
363 line = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF);
367 r = gemtext_translate_line(clt, line);
374 static struct proxy_config *
375 proxy_server_match(struct galileo *env, struct client *clt)
379 if (clt->clt_server_name == NULL)
382 TAILQ_FOREACH(srv, &env->sc_servers, srv_entry) {
383 if (!strcmp(clt->clt_server_name, srv->srv_conf.host))
384 return &srv->srv_conf;
391 proxy_start_request(struct galileo *env, struct client *clt)
393 struct addrinfo hints;
394 struct asr_query *query;
397 if ((clt->clt_pc = proxy_server_match(env, clt)) == NULL) {
398 if (clt_printf(clt, "Status: 501\r\n\r\n") == -1)
400 fcgi_end_request(clt, 1);
404 (void)snprintf(port, sizeof(port), "%d", clt->clt_pc->proxy_port);
406 memset(&hints, 0, sizeof(hints));
407 hints.ai_family = AF_UNSPEC;
408 hints.ai_socktype = SOCK_STREAM;
410 query = getaddrinfo_async(clt->clt_pc->proxy_addr, port, &hints, NULL);
412 log_warn("getaddrinfo_async");
413 fcgi_abort_request(clt);
417 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
418 if (clt->clt_evasr == NULL) {
419 log_warn("event_asr_run");
421 fcgi_abort_request(clt);
427 proxy_resolved(struct asr_result *res, void *d)
429 struct client *clt = d;
430 struct proxy_config *pc = clt->clt_pc;
432 clt->clt_evasr = NULL;
434 if (res->ar_gai_errno != 0) {
435 log_warnx("failed to resolve %s:%d: %s",
436 pc->proxy_addr, pc->proxy_port,
437 gai_strerror(res->ar_gai_errno));
438 if (clt_printf(clt, "Status: 501\r\n") == -1)
440 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
442 if (clt_printf(clt, "Proxy error; connection failed") == -1)
444 fcgi_end_request(clt, 1);
448 clt->clt_addrinfo = res->ar_addrinfo;
449 clt->clt_p = clt->clt_addrinfo;
450 proxy_connect(-1, 0, clt);
454 proxy_connect(int fd, short ev, void *d)
456 struct client *clt = d;
457 struct evbuffer *out;
459 struct tls_config *conf;
460 struct timeval conntv = {5, 0};
462 socklen_t len = sizeof(err);
465 if (clt->clt_p == NULL)
468 if (clt->clt_fd != -1) {
469 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
480 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
482 if (clt->clt_fd == -1) {
483 clt->clt_p = clt->clt_p->ai_next;
487 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
490 clt->clt_evconn_live = 1;
491 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
492 event_add(&clt->clt_evconn, &conntv);
496 clt->clt_evconn_live = 0;
497 freeaddrinfo(clt->clt_addrinfo);
498 clt->clt_addrinfo = clt->clt_p = NULL;
500 /* initialize TLS for Gemini */
501 if ((conf = tls_config_new()) == NULL) {
502 log_warn("tls_config_new failed");
506 tls_config_insecure_noverifycert(conf);
508 if ((clt->clt_ctx = tls_client()) == NULL) {
509 log_warnx("tls_client failed");
510 tls_config_free(conf);
514 if (tls_configure(clt->clt_ctx, conf) == -1) {
515 log_warnx("tls_configure failed");
516 tls_config_free(conf);
520 tls_config_free(conf);
522 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
523 clt->clt_pc->proxy_name) == -1) {
524 log_warnx("tls_connect_socket failed");
528 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
530 if (clt->clt_bev == NULL) {
531 log_warn("bufferevent_new");
534 out = EVBUFFER_OUTPUT(clt->clt_bev);
536 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
537 proxy_tls_readcb, clt->clt_bev);
538 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
539 proxy_tls_writecb, clt->clt_bev);
541 /* bufferevent_settimeout(); */
542 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
544 /* TODO: compute the URL */
545 if (evbuffer_add_printf(out, "gemini://%s/%s\r\n",
546 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
547 log_warn("bufferevent_printf failed");
554 log_warn("failed to connect to %s:%d",
555 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
556 if (clt_printf(clt, "Status: 501\r\n") == -1)
558 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
560 if (clt_printf(clt, "Proxy error; connection failed") == -1)
562 fcgi_end_request(clt, 1);
566 parse_mime(struct client *clt, char *mime, char *lang, size_t len)
570 if (strncmp(mime, "text/gemini", 11) != 0)
573 clt->clt_translate = TR_ENABLED;
575 if ((mime = strchr(mime, ';')) == NULL)
579 while ((t = strsep(&mime, ";")) != NULL) {
580 if (!strncmp(t, "charset=", 8)) {
582 if (!strncasecmp(t, "utf8", 4) ||
583 !strncasecmp(t, "utf-8", 5) ||
584 !strncasecmp(t, "ascii", 5)) {
585 log_debug("unknown charset %s", t);
591 if (!strncmp(t, "lang=", 5)) {
593 if ((semi = strchr(t, ';')) != NULL)
596 if (strlcpy(lang, t, len) >= len) {
597 log_debug("lang too long: %s", t);
611 proxy_tp_puts(struct template *tp, const char *c)
613 struct client *clt = tp->tp_arg;
615 if (clt_puts(clt, c) == -1) {
623 proxy_tp_putc(struct template *tp, int c)
625 struct client *clt = tp->tp_arg;
627 if (clt_putc(clt, c) == -1) {
635 proxy_read(struct bufferevent *bev, void *d)
637 struct client *clt = d;
638 struct proxy_config *pc = clt->clt_pc;
639 struct evbuffer *src = EVBUFFER_INPUT(bev);
645 if (clt->clt_headersdone) {
646 if (clt->clt_translate)
647 proxy_translate_gemtext(clt);
649 clt_write_bufferevent(clt, bev);
653 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
655 if (EVBUFFER_LENGTH(src) >= 1026)
656 proxy_error(bev, EV_READ, clt);
661 !isdigit((unsigned char)hdr[0]) ||
662 !isdigit((unsigned char)hdr[1]) ||
664 log_warnx("invalid ");
665 proxy_error(bev, EV_READ, clt);
674 if (clt_puts(clt, "Status: 501\r\n") == -1)
677 "Content-Type: text/plain;charset=utf-8\r\n") == -1)
679 if (clt_puts(clt, "\r\n") == -1)
681 if (clt_printf(clt, "Request failed with code %c%c\n\n",
682 hdr[0], hdr[1]) == -1)
684 if (clt_printf(clt, "The server says: %s\n", &hdr[3]) == -1)
686 fcgi_end_request(clt, 1);
690 mime = hdr + 2 + strspn(hdr + 2, " \t");
691 if (parse_mime(clt, mime, lang, sizeof(lang)) == -1) {
692 if (clt_puts(clt, "Status: 501\r\n") == -1)
695 "Content-Type: text/plain;charset=utf-8\r\n") == -1)
697 if (clt_puts(clt, "\r\n") == -1)
699 if (clt_printf(clt, "Failed to parse the Gemini response\n")
701 fcgi_end_request(clt, 1);
705 if (clt->clt_translate) {
706 clt->clt_tp = template(clt, proxy_tp_puts, proxy_tp_putc);
708 ctype = "text/html;charset=utf-8";
712 if (clt_printf(clt, "Content-Type: %s\r\n\r\n", ctype) == -1)
715 clt->clt_headersdone = 1;
717 if (clt->clt_translate &&
718 tp_head(clt->clt_tp, lang, pc->stylesheet) == -1)
722 * Trigger the read again so we proceed with the response
734 proxy_write(struct bufferevent *bev, void *d)
740 proxy_error(struct bufferevent *bev, short err, void *d)
742 struct client *clt = d;
743 int status = !(err & EVBUFFER_EOF);
745 log_debug("proxy error, shutting down the connection (err: %x)",
748 if (!clt->clt_headersdone) {
749 if (clt_printf(clt, "Status: 501\r\n") == -1)
751 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
753 if (clt_printf(clt, "Proxy error\n") == -1)
755 } else if (status == 0) {
756 if (clt->clt_translate & TR_PRE) {
757 if (clt_puts(clt, "</pre>"))
759 clt->clt_translate &= ~TR_PRE;
762 if (clt->clt_translate & TR_LIST) {
763 if (clt_puts(clt, "</ul>") == -1)
765 clt->clt_translate &= ~TR_LIST;
768 if (clt->clt_translate & TR_NAV) {
769 if (clt_puts(clt, "</ul></nav>") == -1)
771 clt->clt_translate &= ~TR_NAV;
774 if (tp_foot(clt->clt_tp) == -1)
778 fcgi_end_request(clt, status);
782 proxy_tls_readcb(int fd, short event, void *arg)
784 struct bufferevent *bufev = arg;
785 struct client *clt = bufev->cbarg;
786 char rbuf[IBUF_READ_SIZE];
787 int what = EVBUFFER_READ;
788 int howmuch = IBUF_READ_SIZE;
792 if (event == EV_TIMEOUT) {
793 what |= EVBUFFER_TIMEOUT;
797 if (bufev->wm_read.high != 0)
798 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
800 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
801 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
803 } else if (ret == -1) {
804 what |= EVBUFFER_ERROR;
810 what |= EVBUFFER_EOF;
814 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
815 what |= EVBUFFER_ERROR;
819 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
821 len = EVBUFFER_LENGTH(bufev->input);
822 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
824 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
825 struct evbuffer *buf = bufev->input;
826 event_del(&bufev->ev_read);
827 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
831 if (bufev->readcb != NULL)
832 (*bufev->readcb)(bufev, bufev->cbarg);
836 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
840 (*bufev->errorcb)(bufev, what, bufev->cbarg);
844 proxy_bufferevent_add(struct event *ev, int timeout)
846 struct timeval tv, *ptv = NULL;
854 return (event_add(ev, ptv));
858 proxy_tls_writecb(int fd, short event, void *arg)
860 struct bufferevent *bufev = arg;
861 struct client *clt = bufev->cbarg;
863 short what = EVBUFFER_WRITE;
866 if (event == EV_TIMEOUT) {
867 what |= EVBUFFER_TIMEOUT;
871 if (EVBUFFER_LENGTH(bufev->output)) {
872 ret = tls_write(clt->clt_ctx,
873 EVBUFFER_DATA(bufev->output),
874 EVBUFFER_LENGTH(bufev->output));
875 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
877 } else if (ret == -1) {
878 what |= EVBUFFER_ERROR;
882 evbuffer_drain(bufev->output, len);
885 if (EVBUFFER_LENGTH(bufev->output) != 0)
886 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
888 if (bufev->writecb != NULL &&
889 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
890 (*bufev->writecb)(bufev, bufev->cbarg);
894 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
898 (*bufev->errorcb)(bufev, what, bufev->cbarg);
902 proxy_client_free(struct client *clt)
905 event_asr_abort(clt->clt_evasr);
907 if (clt->clt_addrinfo)
908 freeaddrinfo(clt->clt_addrinfo);
910 if (clt->clt_evconn_live)
911 event_del(&clt->clt_evconn);
913 if (clt->clt_fd != -1)
917 tls_free(clt->clt_ctx);
920 bufferevent_free(clt->clt_bev);
923 free(clt->clt_server_name);
924 free(clt->clt_script_name);
925 free(clt->clt_path_info);