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_inpre) {
210 if (!strncmp(line, "```", 3)) {
212 return (clt_puts(clt, "</pre>"));
215 if (htmlescape(clt, line) == -1)
217 return (clt_putc(clt, '\n'));
221 if (!strncmp(line, "```", 3)) {
223 return (clt_puts(clt, "<pre>"));
228 if (clt_puts(clt, "<blockquote>") == -1 ||
229 htmlescape(clt, line + 1) == -1 ||
230 clt_puts(clt, "</blockquote>") == -1)
236 if (!strncmp(line, "###", 3)) {
237 if (clt_puts(clt, "<h3>") == -1 ||
238 htmlescape(clt, line + 3) == -1 ||
239 clt_puts(clt, "</h3>") == -1)
243 if (!strncmp(line, "##", 2)) {
244 if (clt_puts(clt, "<h2>") == -1 ||
245 htmlescape(clt, line + 2) == -1 ||
246 clt_puts(clt, "</h2>") == -1)
250 if (!strncmp(line, "#", 1)) {
251 if (clt_puts(clt, "<h1>") == -1 ||
252 htmlescape(clt, line + 1) == -1 ||
253 clt_puts(clt, "</h1>") == -1)
258 /* bullet -- XXX: group */
259 if (!strncmp(line, "* ", 2)) {
260 if (clt_puts(clt, "<ul><li>") == -1 ||
261 htmlescape(clt, line + 2) == -1 ||
262 clt_puts(clt, "</li></ul>") == -1)
267 /* link -- XXX: group */
268 if (!strncmp(line, "=>", 2)) {
272 line += strspn(line, " \t");
274 label = line + strcspn(line, " \t");
280 if (clt_puts(clt, "<p><a href='") == -1 ||
281 printurl(clt, line) == -1 ||
282 clt_puts(clt, "'>") == -1 ||
283 htmlescape(clt, label) == -1 ||
284 clt_puts(clt, "</a></p>") == -1)
290 if (clt_puts(clt, "<p>") == -1 ||
291 htmlescape(clt, line) == -1 ||
292 clt_puts(clt, "</p>") == -1)
298 proxy_translate_gemtext(struct client *clt)
300 struct bufferevent *bev = clt->clt_bev;
301 struct evbuffer *src = EVBUFFER_INPUT(bev);
307 line = evbuffer_readln(src, &len, EVBUFFER_EOL_ANY);
311 r = gemtext_translate_line(clt, line);
318 static struct proxy_config *
319 proxy_server_match(struct galileo *env, struct client *clt)
323 if (clt->clt_server_name == NULL)
326 TAILQ_FOREACH(srv, &env->sc_servers, srv_entry) {
327 if (!strcmp(clt->clt_server_name, srv->srv_conf.host))
328 return &srv->srv_conf;
335 proxy_start_request(struct galileo *env, struct client *clt)
337 struct addrinfo hints;
338 struct asr_query *query;
341 if ((clt->clt_pc = proxy_server_match(env, clt)) == NULL) {
342 if (clt_printf(clt, "Status: 501\r\n\r\n") == -1)
344 fcgi_end_request(clt, 1);
348 (void)snprintf(port, sizeof(port), "%d", clt->clt_pc->proxy_port);
350 memset(&hints, 0, sizeof(hints));
351 hints.ai_family = AF_UNSPEC;
352 hints.ai_socktype = SOCK_STREAM;
354 query = getaddrinfo_async(clt->clt_pc->proxy_addr, port, &hints, NULL);
356 log_warn("getaddrinfo_async");
357 fcgi_abort_request(clt);
361 clt->clt_evasr = event_asr_run(query, proxy_resolved, clt);
362 if (clt->clt_evasr == NULL) {
363 log_warn("event_asr_run");
365 fcgi_abort_request(clt);
371 proxy_resolved(struct asr_result *res, void *d)
373 struct client *clt = d;
374 struct proxy_config *pc = clt->clt_pc;
376 clt->clt_evasr = NULL;
378 if (res->ar_gai_errno != 0) {
379 log_warnx("failed to resolve %s:%d: %s",
380 pc->proxy_addr, pc->proxy_port,
381 gai_strerror(res->ar_gai_errno));
382 if (clt_printf(clt, "Status: 501\r\n") == -1)
384 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
386 if (clt_printf(clt, "Proxy error; connection failed") == -1)
388 fcgi_end_request(clt, 1);
392 clt->clt_addrinfo = res->ar_addrinfo;
393 clt->clt_p = clt->clt_addrinfo;
394 proxy_connect(-1, 0, clt);
398 proxy_connect(int fd, short ev, void *d)
400 struct client *clt = d;
401 struct evbuffer *out;
403 struct tls_config *conf;
404 struct timeval conntv = {5, 0};
406 socklen_t len = sizeof(err);
409 if (clt->clt_p == NULL)
412 if (clt->clt_fd != -1) {
413 if (getsockopt(clt->clt_fd, SOL_SOCKET, SO_ERROR, &err, &len)
424 clt->clt_fd = socket(p->ai_family, p->ai_socktype | SOCK_NONBLOCK,
426 if (clt->clt_fd == -1) {
427 clt->clt_p = clt->clt_p->ai_next;
431 if (connect(clt->clt_fd, p->ai_addr, p->ai_addrlen) == 0)
434 clt->clt_evconn_live = 1;
435 event_set(&clt->clt_evconn, clt->clt_fd, EV_WRITE, proxy_connect, clt);
436 event_add(&clt->clt_evconn, &conntv);
440 clt->clt_evconn_live = 0;
441 freeaddrinfo(clt->clt_addrinfo);
442 clt->clt_addrinfo = clt->clt_p = NULL;
444 /* initialize TLS for Gemini */
445 if ((conf = tls_config_new()) == NULL) {
446 log_warn("tls_config_new failed");
450 tls_config_insecure_noverifycert(conf);
452 if ((clt->clt_ctx = tls_client()) == NULL) {
453 log_warnx("tls_client failed");
454 tls_config_free(conf);
458 if (tls_configure(clt->clt_ctx, conf) == -1) {
459 log_warnx("tls_configure failed");
460 tls_config_free(conf);
464 tls_config_free(conf);
466 if (tls_connect_socket(clt->clt_ctx, clt->clt_fd,
467 clt->clt_pc->proxy_name) == -1) {
468 log_warnx("tls_connect_socket failed");
472 clt->clt_bev = bufferevent_new(clt->clt_fd, proxy_read, proxy_write,
474 if (clt->clt_bev == NULL) {
475 log_warn("bufferevent_new");
478 out = EVBUFFER_OUTPUT(clt->clt_bev);
480 event_set(&clt->clt_bev->ev_read, clt->clt_fd, EV_READ,
481 proxy_tls_readcb, clt->clt_bev);
482 event_set(&clt->clt_bev->ev_write, clt->clt_fd, EV_WRITE,
483 proxy_tls_writecb, clt->clt_bev);
485 /* bufferevent_settimeout(); */
486 bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
488 /* TODO: compute the URL */
489 if (evbuffer_add_printf(out, "gemini://localhost/\r\n") == -1) {
490 log_warn("bufferevent_printf failed");
497 log_warn("failed to connect to %s:%d",
498 clt->clt_pc->proxy_addr, clt->clt_pc->proxy_port);
499 if (clt_printf(clt, "Status: 501\r\n") == -1)
501 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
503 if (clt_printf(clt, "Proxy error; connection failed") == -1)
505 fcgi_end_request(clt, 1);
509 proxy_read(struct bufferevent *bev, void *d)
511 struct client *clt = d;
512 struct evbuffer *src = EVBUFFER_INPUT(bev);
518 if (clt->clt_headersdone) {
520 if (clt->clt_translate)
521 proxy_translate_gemtext(clt);
523 clt_write_bufferevent(clt, bev);
527 hdr = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
529 if (EVBUFFER_LENGTH(src) >= 1026)
530 proxy_error(bev, EV_READ, clt);
535 !isdigit((unsigned char)hdr[0]) ||
536 !isdigit((unsigned char)hdr[1]) ||
538 log_warnx("invalid ");
540 proxy_error(bev, EV_READ, clt);
544 code = (hdr[0] - '0') * 10 + (hdr[1] - '0');
546 log_warnx("un-handled gemini reply status %d", code);
548 proxy_error(bev, EV_READ, clt);
552 if (!strncmp(&hdr[3], "text/gemini", 11)) {
553 ctype = "text/html; charset=utf8";
554 clt->clt_translate = 1;
558 if (clt_printf(clt, "Content-Type: %s\r\n", ctype) == -1)
560 if (clt_printf(clt, "\r\n") == -1)
563 clt->clt_headersdone = 1;
565 if (clt->clt_translate) {
566 if (clt_puts(clt, "<!doctype html>"
567 "<html><head></head><body>") == -1)
575 proxy_write(struct bufferevent *bev, void *d)
581 proxy_error(struct bufferevent *bev, short err, void *d)
583 struct client *clt = d;
584 int status = !(err & EVBUFFER_EOF);
586 log_debug("proxy error, shutting down the connection (err: %x)",
589 if (!clt->clt_headersdone) {
590 if (clt_printf(clt, "Status: 501\r\n") == -1)
592 if (clt_printf(clt, "Content-Type: text/plain\r\n") == -1)
594 if (clt_printf(clt, "Proxy error\n") == -1)
596 } else if (status == 0) {
597 if (clt_puts(clt, "</body></html>") == -1)
601 fcgi_end_request(clt, status);
605 proxy_tls_readcb(int fd, short event, void *arg)
607 struct bufferevent *bufev = arg;
608 struct client *clt = bufev->cbarg;
609 char rbuf[IBUF_READ_SIZE];
610 int what = EVBUFFER_READ;
611 int howmuch = IBUF_READ_SIZE;
615 if (event == EV_TIMEOUT) {
616 what |= EVBUFFER_TIMEOUT;
620 if (bufev->wm_read.high != 0)
621 howmuch = MINIMUM(sizeof(rbuf), bufev->wm_read.high);
623 ret = tls_read(clt->clt_ctx, rbuf, howmuch);
624 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
626 } else if (ret == -1) {
627 what |= EVBUFFER_ERROR;
633 what |= EVBUFFER_EOF;
637 if (evbuffer_add(bufev->input, rbuf, len) == -1) {
638 what |= EVBUFFER_ERROR;
642 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
644 len = EVBUFFER_LENGTH(bufev->input);
645 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
647 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
648 struct evbuffer *buf = bufev->input;
649 event_del(&bufev->ev_read);
650 evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
654 if (bufev->readcb != NULL)
655 (*bufev->readcb)(bufev, bufev->cbarg);
659 proxy_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
663 (*bufev->errorcb)(bufev, what, bufev->cbarg);
667 proxy_bufferevent_add(struct event *ev, int timeout)
669 struct timeval tv, *ptv = NULL;
677 return (event_add(ev, ptv));
681 proxy_tls_writecb(int fd, short event, void *arg)
683 struct bufferevent *bufev = arg;
684 struct client *clt = bufev->cbarg;
686 short what = EVBUFFER_WRITE;
689 if (event == EV_TIMEOUT) {
690 what |= EVBUFFER_TIMEOUT;
694 if (EVBUFFER_LENGTH(bufev->output)) {
695 ret = tls_write(clt->clt_ctx,
696 EVBUFFER_DATA(bufev->output),
697 EVBUFFER_LENGTH(bufev->output));
698 if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
700 } else if (ret == -1) {
701 what |= EVBUFFER_ERROR;
705 evbuffer_drain(bufev->output, len);
708 if (EVBUFFER_LENGTH(bufev->output) != 0)
709 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
711 if (bufev->writecb != NULL &&
712 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
713 (*bufev->writecb)(bufev, bufev->cbarg);
717 proxy_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
721 (*bufev->errorcb)(bufev, what, bufev->cbarg);
725 proxy_client_free(struct client *clt)
728 event_asr_abort(clt->clt_evasr);
730 if (clt->clt_addrinfo)
731 freeaddrinfo(clt->clt_addrinfo);
733 if (clt->clt_evconn_live)
734 event_del(&clt->clt_evconn);
736 if (clt->clt_fd != -1)
740 tls_free(clt->clt_ctx);
743 bufferevent_free(clt->clt_bev);
745 free(clt->clt_server_name);
746 free(clt->clt_script_name);
747 free(clt->clt_path_info);