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>
46 #define MINIMUM(a, b) ((a) < (b) ? (a) : (b))
48 /* provided by OpenBSD' base libevent but not in any header? */
49 extern void bufferevent_read_pressure_cb(struct evbuffer *, size_t,
52 void proxy_init(struct privsep *, struct privsep_proc *, void *);
53 int proxy_launch(struct galileo *);
54 void proxy_inflight_dec(const char *);
55 int proxy_dispatch_parent(int, struct privsep_proc *, struct imsg *);
56 void proxy_translate_gemtext(struct client *);
57 void proxy_resolved(struct asr_result *, void *);
58 void proxy_connect(int, short, void *);
59 void proxy_read(struct bufferevent *, void *);
60 void proxy_write(struct bufferevent *, void *);
61 void proxy_error(struct bufferevent *, short, void *);
62 int proxy_bufferevent_add(struct event *, int);
63 void proxy_tls_writecb(int, short, void *);
64 void proxy_tls_readcb(int, short, void *);
66 static struct privsep_proc procs[] = {
67 { "parent", PROC_PARENT, proxy_dispatch_parent },
70 volatile int proxy_clients;
71 volatile int proxy_inflight;
72 uint32_t proxy_fcg_id;
75 proxy(struct privsep *ps, struct privsep_proc *p)
77 proc_run(ps, p, procs, nitems(procs), proxy_init, NULL);
81 proxy_init(struct privsep *ps, struct privsep_proc *p, void *arg)
83 if (config_init(ps->ps_env) == -1)
84 fatal("failed to initialize configuration");
86 /* We use a custom shutdown callback */
87 /* p->p_shutdown = proxy_shutdown */
89 if (pledge("stdio recvfd unix inet dns", NULL) == -1)
94 proxy_launch(struct galileo *env)
96 event_add(&env->sc_evsock, NULL);
101 proxy_purge(struct server *srv)
106 proxy_inflight_dec(const char *why)
109 log_debug("%s: inflight decremented, now %d, %s",
110 __func__, proxy_inflight, why);
114 proxy_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
116 struct privsep *ps = p->p_ps;
117 struct galileo *env = ps->ps_env;
119 switch (imsg->hdr.type) {
121 if (config_getserver(env, imsg) == -1)
122 fatal("config_getproxy");
127 if (env->sc_sock_fd != -1) {
128 event_del(&env->sc_evsock);
129 close(env->sc_sock_fd);
132 env->sc_sock_fd = config_getsock(env, imsg);
133 if (env->sc_sock_fd == -1)
134 fatal("config_getsock");
136 event_set(&env->sc_evsock, env->sc_sock_fd,
137 EV_READ | EV_PERSIST, fcgi_accept, env);
138 event_add(&env->sc_evsock, NULL);
139 evtimer_set(&env->sc_evpause, fcgi_accept, env);
142 log_debug("config done!");
148 log_warnx("unknown message %d", imsg->hdr.type);
156 printurl(struct client *clt, const char *str)
158 for (; *str; ++str) {
164 if (clt_printf(clt, "%2X", (unsigned char)*str) == -1)
168 if (clt_putc(clt, *str) == -1)
178 htmlescape(struct client *clt, const char *str)
182 for (; *str; ++str) {
185 r = clt_puts(clt, "<");
188 r = clt_puts(clt, ">");
191 r = clt_puts(clt, "&");
194 r = clt_putc(clt, *str);
206 gemtext_translate_line(struct client *clt, char *line)
208 /* preformatted line / closing */
209 if (clt->clt_translate & TR_PRE) {
210 if (!strncmp(line, "```", 3)) {
211 clt->clt_translate &= ~TR_PRE;
212 return (clt_puts(clt, "</pre>"));
215 if (htmlescape(clt, line) == -1)
217 return (clt_putc(clt, '\n'));
221 if (!strncmp(line, "* ", 2)) {
222 if (clt->clt_translate & TR_NAV) {
223 if (clt_puts(clt, "</ul></nav>") == -1)
225 clt->clt_translate &= ~TR_NAV;
228 if (!(clt->clt_translate & TR_LIST)) {
229 if (clt_puts(clt, "<ul>") == -1)
231 clt->clt_translate |= TR_LIST;
234 if (clt_puts(clt, "<li>") == -1 ||
235 htmlescape(clt, line + 2) == -1 ||
236 clt_puts(clt, "</li>") == -1)
241 if (clt->clt_translate & TR_LIST) {
242 if (clt_puts(clt, "</ul>") == -1)
244 clt->clt_translate &= ~TR_LIST;
247 /* link -- TODO: relativify from SCRIPT_NAME */
248 if (!strncmp(line, "=>", 2)) {
251 if (!(clt->clt_translate & TR_NAV)) {
252 if (clt_puts(clt, "<nav><ul>") == -1)
254 clt->clt_translate |= TR_NAV;
258 line += strspn(line, " \t");
260 label = line + strcspn(line, " \t");
266 if (clt_puts(clt, "<li><a href='") == -1 ||
267 printurl(clt, line) == -1 ||
268 clt_puts(clt, "'>") == -1 ||
269 htmlescape(clt, label) == -1 ||
270 clt_puts(clt, "</a></li>") == -1)
276 if (clt->clt_translate & TR_NAV) {
277 if (clt_puts(clt, "</ul></nav>") == -1)
279 clt->clt_translate &= ~TR_NAV;
283 if (!strncmp(line, "```", 3)) {
284 clt->clt_translate |= TR_PRE;
285 return (clt_puts(clt, "<pre>"));
290 if (clt_puts(clt, "<blockquote>") == -1 ||
291 htmlescape(clt, line + 1) == -1 ||
292 clt_puts(clt, "</blockquote>") == -1)
298 if (!strncmp(line, "###", 3)) {
299 if (clt_puts(clt, "<h3>") == -1 ||
300 htmlescape(clt, line + 3) == -1 ||
301 clt_puts(clt, "</h3>") == -1)
305 if (!strncmp(line, "##", 2)) {
306 if (clt_puts(clt, "<h2>") == -1 ||
307 htmlescape(clt, line + 2) == -1 ||
308 clt_puts(clt, "</h2>") == -1)
312 if (!strncmp(line, "#", 1)) {
313 if (clt_puts(clt, "<h1>") == -1 ||
314 htmlescape(clt, line + 1) == -1 ||
315 clt_puts(clt, "</h1>") == -1)
320 /* Not following strictly the gemini specification... */
325 if (clt_puts(clt, "<p>") == -1 ||
326 htmlescape(clt, line) == -1 ||
327 clt_puts(clt, "</p>") == -1)
334 proxy_translate_gemtext(struct client *clt)
336 struct bufferevent *bev = clt->clt_bev;
337 struct evbuffer *src = EVBUFFER_INPUT(bev);
343 line = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF);
347 r = gemtext_translate_line(clt, line);
354 static struct proxy_config *
355 proxy_server_match(struct galileo *env, struct client *clt)
359 if (clt->clt_server_name == NULL)
362 TAILQ_FOREACH(srv, &env->sc_servers, srv_entry) {
363 if (!strcmp(clt->clt_server_name, srv->srv_conf.host))
364 return &srv->srv_conf;
371 proxy_start_request(struct galileo *env, struct client *clt)
373 struct addrinfo hints;
374 struct asr_query *query;
377 if ((clt->clt_pc = proxy_server_match(env, clt)) == NULL) {
378 if (clt_printf(clt, "Status: 501\r\n\r\n") == -1)
380 fcgi_end_request(clt, 1);
384 (void)snprintf(port, sizeof(port), "%d", clt->clt_pc->proxy_port);
386 memset(&hints, 0, sizeof(hints));
387 hints.ai_family = AF_UNSPEC;
388 hints.ai_socktype = SOCK_STREAM;
390 query = getaddrinfo_async(clt->clt_pc->proxy_addr, port, &hints, NULL);
392 log_warn("getaddrinfo_async");
393 fcgi_abort_request(clt);
397 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
398 if (clt->clt_evasr == NULL) {
399 log_warn("event_asr_run");
401 fcgi_abort_request(clt);
407 proxy_resolved(struct asr_result *res, void *d)
409 struct client *clt = d;
410 struct proxy_config *pc = clt->clt_pc;
412 clt->clt_evasr = NULL;
414 if (res->ar_gai_errno != 0) {
415 log_warnx("failed to resolve %s:%d: %s",
416 pc->proxy_addr, pc->proxy_port,
417 gai_strerror(res->ar_gai_errno));
418 if (clt_printf(clt, "Status: 501\r\n") == -1)
420 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
422 if (clt_printf(clt, "Proxy error; connection failed") == -1)
424 fcgi_end_request(clt, 1);
428 clt->clt_addrinfo = res->ar_addrinfo;
429 clt->clt_p = clt->clt_addrinfo;
430 proxy_connect(-1, 0, clt);
434 proxy_connect(int fd, short ev, void *d)
436 struct client *clt = d;
437 struct evbuffer *out;
439 struct tls_config *conf;
440 struct timeval conntv = {5, 0};
442 socklen_t len = sizeof(err);
445 if (clt->clt_p == NULL)
448 if (clt->clt_fd != -1) {
449 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
460 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
462 if (clt->clt_fd == -1) {
463 clt->clt_p = clt->clt_p->ai_next;
467 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
470 clt->clt_evconn_live = 1;
471 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
472 event_add(&clt->clt_evconn, &conntv);
476 clt->clt_evconn_live = 0;
477 freeaddrinfo(clt->clt_addrinfo);
478 clt->clt_addrinfo = clt->clt_p = NULL;
480 /* initialize TLS for Gemini */
481 if ((conf = tls_config_new()) == NULL) {
482 log_warn("tls_config_new failed");
486 tls_config_insecure_noverifycert(conf);
488 if ((clt->clt_ctx = tls_client()) == NULL) {
489 log_warnx("tls_client failed");
490 tls_config_free(conf);
494 if (tls_configure(clt->clt_ctx, conf) == -1) {
495 log_warnx("tls_configure failed");
496 tls_config_free(conf);
500 tls_config_free(conf);
502 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
503 clt->clt_pc->proxy_name) == -1) {
504 log_warnx("tls_connect_socket failed");
508 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
510 if (clt->clt_bev == NULL) {
511 log_warn("bufferevent_new");
514 out = EVBUFFER_OUTPUT(clt->clt_bev);
516 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
517 proxy_tls_readcb, clt->clt_bev);
518 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
519 proxy_tls_writecb, clt->clt_bev);
521 /* bufferevent_settimeout(); */
522 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
524 /* TODO: compute the URL */
525 if (evbuffer_add_printf(out, "gemini://%s/%s\r\n",
526 clt->clt_pc->proxy_name, clt->clt_path_info) == -1) {
527 log_warn("bufferevent_printf failed");
534 log_warn("failed to connect to %s:%d",
535 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
536 if (clt_printf(clt, "Status: 501\r\n") == -1)
538 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
540 if (clt_printf(clt, "Proxy error; connection failed") == -1)
542 fcgi_end_request(clt, 1);
546 proxy_read(struct bufferevent *bev, void *d)
548 struct client *clt = d;
549 struct proxy_config *pc = clt->clt_pc;
550 struct evbuffer *src = EVBUFFER_INPUT(bev);
556 if (clt->clt_headersdone) {
558 if (clt->clt_translate)
559 proxy_translate_gemtext(clt);
561 clt_write_bufferevent(clt, bev);
565 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
567 if (EVBUFFER_LENGTH(src) >= 1026)
568 proxy_error(bev, EV_READ, clt);
573 !isdigit((unsigned char)hdr[0]) ||
574 !isdigit((unsigned char)hdr[1]) ||
576 log_warnx("invalid ");
578 proxy_error(bev, EV_READ, clt);
582 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
584 log_warnx("un-handled gemini reply status %d", code);
586 proxy_error(bev, EV_READ, clt);
590 if (!strncmp(&hdr[3], "text/gemini", 11)) {
591 ctype = "text/html; charset=utf8";
592 clt->clt_translate = TR_ENABLED;
596 if (clt_printf(clt, "Content-Type: %s\r\n", ctype) == -1)
598 if (clt_printf(clt, "\r\n") == -1)
601 clt->clt_headersdone = 1;
603 if (clt->clt_translate) {
604 if (clt_puts(clt, "<!doctype html><html><head>") == -1)
606 if (*pc->stylesheet != '\0' &&
607 clt_printf(clt, "<link rel='stylesheet' href='%s' />",
608 pc->stylesheet) == -1)
610 if (clt_puts(clt, "</head><body>") == -1)
618 proxy_write(struct bufferevent *bev, void *d)
624 proxy_error(struct bufferevent *bev, short err, void *d)
626 struct client *clt = d;
627 int status = !(err & EVBUFFER_EOF);
629 log_debug("proxy error, shutting down the connection (err: %x)",
632 if (!clt->clt_headersdone) {
633 if (clt_printf(clt, "Status: 501\r\n") == -1)
635 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
637 if (clt_printf(clt, "Proxy error\n") == -1)
639 } else if (status == 0) {
640 if (clt_puts(clt, "</body></html>") == -1)
644 fcgi_end_request(clt, status);
648 proxy_tls_readcb(int fd, short event, void *arg)
650 struct bufferevent *bufev = arg;
651 struct client *clt = bufev->cbarg;
652 char rbuf[IBUF_READ_SIZE];
653 int what = EVBUFFER_READ;
654 int howmuch = IBUF_READ_SIZE;
658 if (event == EV_TIMEOUT) {
659 what |= EVBUFFER_TIMEOUT;
663 if (bufev->wm_read.high != 0)
664 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
666 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
667 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
669 } else if (ret == -1) {
670 what |= EVBUFFER_ERROR;
676 what |= EVBUFFER_EOF;
680 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
681 what |= EVBUFFER_ERROR;
685 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
687 len = EVBUFFER_LENGTH(bufev->input);
688 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
690 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
691 struct evbuffer *buf = bufev->input;
692 event_del(&bufev->ev_read);
693 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
697 if (bufev->readcb != NULL)
698 (*bufev->readcb)(bufev, bufev->cbarg);
702 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
706 (*bufev->errorcb)(bufev, what, bufev->cbarg);
710 proxy_bufferevent_add(struct event *ev, int timeout)
712 struct timeval tv, *ptv = NULL;
720 return (event_add(ev, ptv));
724 proxy_tls_writecb(int fd, short event, void *arg)
726 struct bufferevent *bufev = arg;
727 struct client *clt = bufev->cbarg;
729 short what = EVBUFFER_WRITE;
732 if (event == EV_TIMEOUT) {
733 what |= EVBUFFER_TIMEOUT;
737 if (EVBUFFER_LENGTH(bufev->output)) {
738 ret = tls_write(clt->clt_ctx,
739 EVBUFFER_DATA(bufev->output),
740 EVBUFFER_LENGTH(bufev->output));
741 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
743 } else if (ret == -1) {
744 what |= EVBUFFER_ERROR;
748 evbuffer_drain(bufev->output, len);
751 if (EVBUFFER_LENGTH(bufev->output) != 0)
752 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
754 if (bufev->writecb != NULL &&
755 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
756 (*bufev->writecb)(bufev, bufev->cbarg);
760 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
764 (*bufev->errorcb)(bufev, what, bufev->cbarg);
768 proxy_client_free(struct client *clt)
771 event_asr_abort(clt->clt_evasr);
773 if (clt->clt_addrinfo)
774 freeaddrinfo(clt->clt_addrinfo);
776 if (clt->clt_evconn_live)
777 event_del(&clt->clt_evconn);
779 if (clt->clt_fd != -1)
783 tls_free(clt->clt_ctx);
786 bufferevent_free(clt->clt_bev);
788 free(clt->clt_server_name);
789 free(clt->clt_script_name);
790 free(clt->clt_path_info);