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>
47 #define MINIMUM(a, b) ((a) < (b) ? (a) : (b))
49 /* provided by OpenBSD' base libevent but not in any header? */
50 extern void bufferevent_read_pressure_cb(struct evbuffer *, size_t,
53 void proxy_init(struct privsep *, struct privsep_proc *, void *);
54 int proxy_launch(struct galileo *);
55 void proxy_inflight_dec(const char *);
56 int proxy_dispatch_parent(int, struct privsep_proc *, struct imsg *);
57 void proxy_translate_gemtext(struct client *);
58 void proxy_resolved(struct asr_result *, void *);
59 void proxy_connect(int, short, void *);
60 void proxy_read(struct bufferevent *, void *);
61 void proxy_write(struct bufferevent *, void *);
62 void proxy_error(struct bufferevent *, short, void *);
63 int proxy_bufferevent_add(struct event *, int);
64 void proxy_tls_writecb(int, short, void *);
65 void proxy_tls_readcb(int, short, void *);
67 static struct privsep_proc procs[] = {
68 { "parent", PROC_PARENT, proxy_dispatch_parent },
71 volatile int proxy_clients;
72 volatile int proxy_inflight;
73 uint32_t proxy_fcg_id;
76 proxy(struct privsep *ps, struct privsep_proc *p)
78 proc_run(ps, p, procs, nitems(procs), proxy_init, NULL);
82 proxy_init(struct privsep *ps, struct privsep_proc *p, void *arg)
84 if (config_init(ps->ps_env) == -1)
85 fatal("failed to initialize configuration");
87 /* We use a custom shutdown callback */
88 /* p->p_shutdown = proxy_shutdown */
90 if (pledge("stdio recvfd unix inet dns", NULL) == -1)
95 proxy_launch(struct galileo *env)
97 event_add(&env->sc_evsock, NULL);
102 proxy_purge(struct server *srv)
107 proxy_inflight_dec(const char *why)
110 log_debug("%s: inflight decremented, now %d, %s",
111 __func__, proxy_inflight, why);
115 proxy_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
117 struct privsep *ps = p->p_ps;
118 struct galileo *env = ps->ps_env;
120 switch (imsg->hdr.type) {
122 if (config_getserver(env, imsg) == -1)
123 fatal("config_getproxy");
128 if (env->sc_sock_fd != -1) {
129 event_del(&env->sc_evsock);
130 close(env->sc_sock_fd);
133 env->sc_sock_fd = config_getsock(env, imsg);
134 if (env->sc_sock_fd == -1)
135 fatal("config_getsock");
137 event_set(&env->sc_evsock, env->sc_sock_fd,
138 EV_READ | EV_PERSIST, fcgi_accept, env);
139 event_add(&env->sc_evsock, NULL);
140 evtimer_set(&env->sc_evpause, fcgi_accept, env);
143 log_debug("config done!");
149 log_warnx("unknown message %d", imsg->hdr.type);
157 printurl(struct client *clt, const char *str)
159 for (; *str; ++str) {
165 if (clt_printf(clt, "%2X", (unsigned char)*str) == -1)
169 if (clt_putc(clt, *str) == -1)
179 htmlescape(struct client *clt, const char *str)
183 for (; *str; ++str) {
186 r = clt_puts(clt, "<");
189 r = clt_puts(clt, ">");
192 r = clt_puts(clt, "&");
195 r = clt_putc(clt, *str);
207 gemtext_translate_line(struct client *clt, char *line)
209 /* preformatted line / closing */
210 if (clt->clt_translate & TR_PRE) {
211 if (!strncmp(line, "```", 3)) {
212 clt->clt_translate &= ~TR_PRE;
213 return (clt_puts(clt, "</pre>"));
216 if (htmlescape(clt, line) == -1)
218 return (clt_putc(clt, '\n'));
222 if (!strncmp(line, "* ", 2)) {
223 if (clt->clt_translate & TR_NAV) {
224 if (clt_puts(clt, "</ul></nav>") == -1)
226 clt->clt_translate &= ~TR_NAV;
229 if (!(clt->clt_translate & TR_LIST)) {
230 if (clt_puts(clt, "<ul>") == -1)
232 clt->clt_translate |= TR_LIST;
235 if (clt_puts(clt, "<li>") == -1 ||
236 htmlescape(clt, line + 2) == -1 ||
237 clt_puts(clt, "</li>") == -1)
242 if (clt->clt_translate & TR_LIST) {
243 if (clt_puts(clt, "</ul>") == -1)
245 clt->clt_translate &= ~TR_LIST;
248 /* link -- TODO: relativify from SCRIPT_NAME */
249 if (!strncmp(line, "=>", 2)) {
253 line += strspn(line, " \t");
255 label = line + strcspn(line, " \t");
261 if (fnmatch("*.jpg", line, 0) == 0 ||
262 fnmatch("*.jpeg", line, 0) == 0 ||
263 fnmatch("*.gif", line, 0) == 0 ||
264 fnmatch("*.png", line, 0) == 0 ||
265 fnmatch("*.svg", line, 0) == 0 ||
266 fnmatch("*.webp", line, 0) == 0) {
267 if (clt->clt_translate & TR_NAV) {
268 if (clt_puts(clt, "</ul></nav>") == -1)
270 clt->clt_translate &= ~TR_NAV;
273 if (clt_puts(clt, "<figure><a href='") == -1 ||
274 printurl(clt, line) == -1 ||
275 clt_puts(clt, "'><img src='") == -1 ||
276 printurl(clt, line) == -1 ||
277 clt_puts(clt, "' /></a><figcaption>") == -1 ||
278 htmlescape(clt, label) == -1 ||
279 clt_puts(clt, "</figcaption></figure>") == -1)
285 if (!(clt->clt_translate & TR_NAV)) {
286 if (clt_puts(clt, "<nav><ul>") == -1)
288 clt->clt_translate |= TR_NAV;
291 if (clt_puts(clt, "<li><a href='") == -1 ||
292 printurl(clt, line) == -1 ||
293 clt_puts(clt, "'>") == -1 ||
294 htmlescape(clt, label) == -1 ||
295 clt_puts(clt, "</a></li>") == -1)
301 if (clt->clt_translate & TR_NAV) {
302 if (clt_puts(clt, "</ul></nav>") == -1)
304 clt->clt_translate &= ~TR_NAV;
308 if (!strncmp(line, "```", 3)) {
309 clt->clt_translate |= TR_PRE;
310 return (clt_puts(clt, "<pre>"));
315 if (clt_puts(clt, "<blockquote>") == -1 ||
316 htmlescape(clt, line + 1) == -1 ||
317 clt_puts(clt, "</blockquote>") == -1)
323 if (!strncmp(line, "###", 3)) {
324 if (clt_puts(clt, "<h3>") == -1 ||
325 htmlescape(clt, line + 3) == -1 ||
326 clt_puts(clt, "</h3>") == -1)
330 if (!strncmp(line, "##", 2)) {
331 if (clt_puts(clt, "<h2>") == -1 ||
332 htmlescape(clt, line + 2) == -1 ||
333 clt_puts(clt, "</h2>") == -1)
337 if (!strncmp(line, "#", 1)) {
338 if (clt_puts(clt, "<h1>") == -1 ||
339 htmlescape(clt, line + 1) == -1 ||
340 clt_puts(clt, "</h1>") == -1)
345 /* Not following strictly the gemini specification... */
350 if (clt_puts(clt, "<p>") == -1 ||
351 htmlescape(clt, line) == -1 ||
352 clt_puts(clt, "</p>") == -1)
359 proxy_translate_gemtext(struct client *clt)
361 struct bufferevent *bev = clt->clt_bev;
362 struct evbuffer *src = EVBUFFER_INPUT(bev);
368 line = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF);
372 r = gemtext_translate_line(clt, line);
379 static struct proxy_config *
380 proxy_server_match(struct galileo *env, struct client *clt)
384 if (clt->clt_server_name == NULL)
387 TAILQ_FOREACH(srv, &env->sc_servers, srv_entry) {
388 if (!strcmp(clt->clt_server_name, srv->srv_conf.host))
389 return &srv->srv_conf;
396 proxy_start_request(struct galileo *env, struct client *clt)
398 struct addrinfo hints;
399 struct asr_query *query;
402 if ((clt->clt_pc = proxy_server_match(env, clt)) == NULL) {
403 if (clt_printf(clt, "Status: 501\r\n\r\n") == -1)
405 fcgi_end_request(clt, 1);
409 (void)snprintf(port, sizeof(port), "%d", clt->clt_pc->proxy_port);
411 memset(&hints, 0, sizeof(hints));
412 hints.ai_family = AF_UNSPEC;
413 hints.ai_socktype = SOCK_STREAM;
415 query = getaddrinfo_async(clt->clt_pc->proxy_addr, port, &hints, NULL);
417 log_warn("getaddrinfo_async");
418 fcgi_abort_request(clt);
422 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
423 if (clt->clt_evasr == NULL) {
424 log_warn("event_asr_run");
426 fcgi_abort_request(clt);
432 proxy_resolved(struct asr_result *res, void *d)
434 struct client *clt = d;
435 struct proxy_config *pc = clt->clt_pc;
437 clt->clt_evasr = NULL;
439 if (res->ar_gai_errno != 0) {
440 log_warnx("failed to resolve %s:%d: %s",
441 pc->proxy_addr, pc->proxy_port,
442 gai_strerror(res->ar_gai_errno));
443 if (clt_printf(clt, "Status: 501\r\n") == -1)
445 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
447 if (clt_printf(clt, "Proxy error; connection failed") == -1)
449 fcgi_end_request(clt, 1);
453 clt->clt_addrinfo = res->ar_addrinfo;
454 clt->clt_p = clt->clt_addrinfo;
455 proxy_connect(-1, 0, clt);
459 proxy_connect(int fd, short ev, void *d)
461 struct client *clt = d;
462 struct evbuffer *out;
464 struct tls_config *conf;
465 struct timeval conntv = {5, 0};
467 socklen_t len = sizeof(err);
470 if (clt->clt_p == NULL)
473 if (clt->clt_fd != -1) {
474 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
485 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
487 if (clt->clt_fd == -1) {
488 clt->clt_p = clt->clt_p->ai_next;
492 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
495 clt->clt_evconn_live = 1;
496 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
497 event_add(&clt->clt_evconn, &conntv);
501 clt->clt_evconn_live = 0;
502 freeaddrinfo(clt->clt_addrinfo);
503 clt->clt_addrinfo = clt->clt_p = NULL;
505 /* initialize TLS for Gemini */
506 if ((conf = tls_config_new()) == NULL) {
507 log_warn("tls_config_new failed");
511 tls_config_insecure_noverifycert(conf);
513 if ((clt->clt_ctx = tls_client()) == NULL) {
514 log_warnx("tls_client failed");
515 tls_config_free(conf);
519 if (tls_configure(clt->clt_ctx, conf) == -1) {
520 log_warnx("tls_configure failed");
521 tls_config_free(conf);
525 tls_config_free(conf);
527 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
528 clt->clt_pc->proxy_name) == -1) {
529 log_warnx("tls_connect_socket failed");
533 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
535 if (clt->clt_bev == NULL) {
536 log_warn("bufferevent_new");
539 out = EVBUFFER_OUTPUT(clt->clt_bev);
541 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
542 proxy_tls_readcb, clt->clt_bev);
543 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
544 proxy_tls_writecb, clt->clt_bev);
546 /* bufferevent_settimeout(); */
547 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
549 /* TODO: compute the URL */
550 if (evbuffer_add_printf(out, "gemini://%s/%s\r\n",
551 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
552 log_warn("bufferevent_printf failed");
559 log_warn("failed to connect to %s:%d",
560 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
561 if (clt_printf(clt, "Status: 501\r\n") == -1)
563 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
565 if (clt_printf(clt, "Proxy error; connection failed") == -1)
567 fcgi_end_request(clt, 1);
571 proxy_read(struct bufferevent *bev, void *d)
573 struct client *clt = d;
574 struct proxy_config *pc = clt->clt_pc;
575 struct evbuffer *src = EVBUFFER_INPUT(bev);
580 if (clt->clt_headersdone) {
582 if (clt->clt_translate)
583 proxy_translate_gemtext(clt);
585 clt_write_bufferevent(clt, bev);
589 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
591 if (EVBUFFER_LENGTH(src) >= 1026)
592 proxy_error(bev, EV_READ, clt);
597 !isdigit((unsigned char)hdr[0]) ||
598 !isdigit((unsigned char)hdr[1]) ||
600 log_warnx("invalid ");
602 proxy_error(bev, EV_READ, clt);
611 if (clt_puts(clt, "Status: 501\r\n") == -1)
614 "Content-Type: text/plain;charset=utf8\r\n") == -1)
616 if (clt_puts(clt, "\r\n") == -1)
618 if (clt_printf(clt, "Request failed with code %c%c\n\n",
619 hdr[0], hdr[1]) == -1)
621 if (clt_printf(clt, "The server says: %s\n", &hdr[3]) == -1)
623 fcgi_end_request(clt, 1);
627 if (!strncmp(&hdr[3], "text/gemini", 11)) {
628 ctype = "text/html; charset=utf8";
629 clt->clt_translate = TR_ENABLED;
633 if (clt_printf(clt, "Content-Type: %s\r\n", ctype) == -1)
635 if (clt_printf(clt, "\r\n") == -1)
638 clt->clt_headersdone = 1;
640 if (clt->clt_translate) {
641 if (clt_puts(clt, "<!doctype html><html><head>") == -1)
643 if (*pc->stylesheet != '\0' &&
644 clt_printf(clt, "<link rel='stylesheet' href='%s' />",
645 pc->stylesheet) == -1)
647 if (clt_puts(clt, "</head><body>") == -1)
655 proxy_write(struct bufferevent *bev, void *d)
661 proxy_error(struct bufferevent *bev, short err, void *d)
663 struct client *clt = d;
664 int status = !(err & EVBUFFER_EOF);
666 log_debug("proxy error, shutting down the connection (err: %x)",
669 if (!clt->clt_headersdone) {
670 if (clt_printf(clt, "Status: 501\r\n") == -1)
672 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
674 if (clt_printf(clt, "Proxy error\n") == -1)
676 } else if (status == 0) {
677 if (clt_puts(clt, "</body></html>") == -1)
681 fcgi_end_request(clt, status);
685 proxy_tls_readcb(int fd, short event, void *arg)
687 struct bufferevent *bufev = arg;
688 struct client *clt = bufev->cbarg;
689 char rbuf[IBUF_READ_SIZE];
690 int what = EVBUFFER_READ;
691 int howmuch = IBUF_READ_SIZE;
695 if (event == EV_TIMEOUT) {
696 what |= EVBUFFER_TIMEOUT;
700 if (bufev->wm_read.high != 0)
701 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
703 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
704 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
706 } else if (ret == -1) {
707 what |= EVBUFFER_ERROR;
713 what |= EVBUFFER_EOF;
717 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
718 what |= EVBUFFER_ERROR;
722 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
724 len = EVBUFFER_LENGTH(bufev->input);
725 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
727 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
728 struct evbuffer *buf = bufev->input;
729 event_del(&bufev->ev_read);
730 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
734 if (bufev->readcb != NULL)
735 (*bufev->readcb)(bufev, bufev->cbarg);
739 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
743 (*bufev->errorcb)(bufev, what, bufev->cbarg);
747 proxy_bufferevent_add(struct event *ev, int timeout)
749 struct timeval tv, *ptv = NULL;
757 return (event_add(ev, ptv));
761 proxy_tls_writecb(int fd, short event, void *arg)
763 struct bufferevent *bufev = arg;
764 struct client *clt = bufev->cbarg;
766 short what = EVBUFFER_WRITE;
769 if (event == EV_TIMEOUT) {
770 what |= EVBUFFER_TIMEOUT;
774 if (EVBUFFER_LENGTH(bufev->output)) {
775 ret = tls_write(clt->clt_ctx,
776 EVBUFFER_DATA(bufev->output),
777 EVBUFFER_LENGTH(bufev->output));
778 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
780 } else if (ret == -1) {
781 what |= EVBUFFER_ERROR;
785 evbuffer_drain(bufev->output, len);
788 if (EVBUFFER_LENGTH(bufev->output) != 0)
789 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
791 if (bufev->writecb != NULL &&
792 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
793 (*bufev->writecb)(bufev, bufev->cbarg);
797 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
801 (*bufev->errorcb)(bufev, what, bufev->cbarg);
805 proxy_client_free(struct client *clt)
808 event_asr_abort(clt->clt_evasr);
810 if (clt->clt_addrinfo)
811 freeaddrinfo(clt->clt_addrinfo);
813 if (clt->clt_evconn_live)
814 event_del(&clt->clt_evconn);
816 if (clt->clt_fd != -1)
820 tls_free(clt->clt_ctx);
823 bufferevent_free(clt->clt_bev);
825 free(clt->clt_server_name);
826 free(clt->clt_script_name);
827 free(clt->clt_path_info);