2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
20 #include <sys/socket.h>
22 #include <netinet/in.h>
39 #include "telescope.h"
41 static struct imsgev *iev_ui;
42 static struct tls_config *tlsconf;
44 /* a pending request */
53 struct bufferevent *bev;
55 struct addrinfo *servinfo, *p;
57 struct addrinfo hints;
58 struct event_asr *asrev;
61 TAILQ_ENTRY(req) reqs;
64 static struct req *req_by_id(uint32_t);
66 static void die(void) __attribute__((__noreturn__));
68 static void try_to_connect(int, short, void*);
71 static void query_done(struct asr_result*, void*);
72 static void async_conn_towards(struct req*);
74 static void blocking_conn_towards(struct req*);
77 static void close_with_err(struct req*, const char*);
78 static void close_with_errf(struct req*, const char*, ...)
79 __attribute__((format(printf, 2, 3)));
81 static void net_tls_handshake(int, short, void *);
82 static void net_tls_readcb(int, short, void *);
83 static void net_tls_writecb(int, short, void *);
85 static int gemini_parse_reply(struct req *, const char *, size_t);
87 static void net_ready(struct req *req);
88 static void net_read(struct bufferevent *, void *);
89 static void net_write(struct bufferevent *, void *);
90 static void net_error(struct bufferevent *, short, void *);
92 static void handle_get_raw(struct imsg *, size_t);
93 static void handle_cert_status(struct imsg*, size_t);
94 static void handle_proceed(struct imsg*, size_t);
95 static void handle_stop(struct imsg*, size_t);
96 static void handle_quit(struct imsg*, size_t);
97 static void handle_dispatch_imsg(int, short, void*);
99 static int net_send_ui(int, uint32_t, const void *, uint16_t);
101 /* TODO: making this customizable */
102 struct timeval timeout_for_handshake = { 5, 0 };
104 static imsg_handlerfn *handlers[] = {
105 [IMSG_GET_RAW] = handle_get_raw,
106 [IMSG_CERT_STATUS] = handle_cert_status,
107 [IMSG_PROCEED] = handle_proceed,
108 [IMSG_STOP] = handle_stop,
109 [IMSG_QUIT] = handle_quit,
112 typedef void (*statefn)(int, short, void*);
114 TAILQ_HEAD(, req) reqhead;
117 yield_r(struct req *req, statefn fn, struct timeval *tv)
119 event_once(req->fd, EV_READ, fn, req, tv);
123 yield_w(struct req *req, statefn fn, struct timeval *tv)
125 event_once(req->fd, EV_WRITE, fn, req, tv);
129 req_by_id(uint32_t id)
133 TAILQ_FOREACH(r, &reqhead, reqs) {
141 static void __attribute__((__noreturn__))
148 try_to_connect(int fd, short ev, void *d)
152 socklen_t len = sizeof(error);
159 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error,
169 req->fd = socket(req->p->ai_family, req->p->ai_socktype,
170 req->p->ai_protocol);
172 req->p = req->p->ai_next;
175 mark_nonblock(req->fd);
176 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
178 yield_w(req, try_to_connect, NULL);
183 freeaddrinfo(req->servinfo);
184 close_with_errf(req, "failed to connect to %s",
189 freeaddrinfo(req->servinfo);
192 if ((req->ctx = tls_client()) == NULL) {
193 close_with_errf(req, "tls_client: %s", strerror(errno));
196 if (tls_configure(req->ctx, tlsconf) == -1) {
197 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
200 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
201 close_with_errf(req, "tls_connect_socket: %s",
202 tls_error(req->ctx));
205 yield_w(req, net_tls_handshake, &timeout_for_handshake);
210 query_done(struct asr_result *res, void *d)
215 if (res->ar_gai_errno != 0) {
216 close_with_errf(req, "failed to resolve %s: %s",
217 req->url.host, gai_strerror(res->ar_gai_errno));
222 req->servinfo = res->ar_addrinfo;
223 req->p = res->ar_addrinfo;
224 try_to_connect(0, 0, req);
228 async_conn_towards(struct req *req)
231 const char *proto = "1965";
233 if (*req->url.port != '\0')
234 proto = req->url.port;
236 req->hints.ai_family = AF_UNSPEC;
237 req->hints.ai_socktype = SOCK_STREAM;
238 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
239 req->asrev = event_asr_run(q, query_done, req);
243 blocking_conn_towards(struct req *req)
245 struct addrinfo hints;
246 struct phos_uri *url = &req->url;
248 const char *proto = "1965";
250 if (*url->port != '\0')
253 memset(&hints, 0, sizeof(hints));
254 hints.ai_family = AF_UNSPEC;
255 hints.ai_socktype = SOCK_STREAM;
257 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
258 close_with_errf(req, "failed to resolve %s: %s",
259 url->host, gai_strerror(status));
264 req->p = req->servinfo;
265 try_to_connect(0, 0, req);
270 close_conn(int fd, short ev, void *d)
275 if (req->asrev != NULL)
276 event_asr_abort(req->asrev);
279 if (req->bev != NULL) {
280 bufferevent_free(req->bev);
284 if (req->ctx != NULL) {
285 switch (tls_close(req->ctx)) {
286 case TLS_WANT_POLLIN:
287 yield_r(req, close_conn, NULL);
289 case TLS_WANT_POLLOUT:
290 yield_w(req, close_conn, NULL);
298 TAILQ_REMOVE(&reqhead, req, reqs);
305 close_with_err(struct req *req, const char *err)
307 net_send_ui(IMSG_ERR, req->id, err, strlen(err)+1);
308 close_conn(0, 0, req);
312 close_with_errf(struct req *req, const char *fmt, ...)
318 if (vasprintf(&s, fmt, ap) == -1)
322 close_with_err(req, s);
327 net_tls_handshake(int fd, short event, void *d)
332 if (event == EV_TIMEOUT) {
333 close_with_err(req, "Timeout loading page");
337 switch (tls_handshake(req->ctx)) {
338 case TLS_WANT_POLLIN:
339 yield_r(req, net_tls_handshake, NULL);
341 case TLS_WANT_POLLOUT:
342 yield_w(req, net_tls_handshake, NULL);
346 hash = tls_peer_cert_hash(req->ctx);
348 close_with_errf(req, "handshake failed: %s",
349 tls_error(req->ctx));
352 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
356 net_tls_readcb(int fd, short event, void *d)
358 struct bufferevent *bufev = d;
359 struct req *req = bufev->cbarg;
360 char buf[IBUF_READ_SIZE];
361 int what = EVBUFFER_READ;
362 int howmuch = IBUF_READ_SIZE;
366 if (event == EV_TIMEOUT) {
367 what |= EVBUFFER_TIMEOUT;
371 if (bufev->wm_read.high != 0)
372 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
374 switch (ret = tls_read(req->ctx, buf, howmuch)) {
375 case TLS_WANT_POLLIN:
376 case TLS_WANT_POLLOUT:
379 what |= EVBUFFER_ERROR;
385 what |= EVBUFFER_EOF;
389 if (evbuffer_add(bufev->input, buf, len) == -1) {
390 what |= EVBUFFER_ERROR;
394 event_add(&bufev->ev_read, NULL);
396 len = EVBUFFER_LENGTH(bufev->input);
397 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
400 if (bufev->readcb != NULL)
401 (*bufev->readcb)(bufev, bufev->cbarg);
405 event_add(&bufev->ev_read, NULL);
409 (*bufev->errorcb)(bufev, what, bufev->cbarg);
413 net_tls_writecb(int fd, short event, void *d)
415 struct bufferevent *bufev = d;
416 struct req *req = bufev->cbarg;
419 short what = EVBUFFER_WRITE;
421 if (event & EV_TIMEOUT) {
422 what |= EVBUFFER_TIMEOUT;
426 if (EVBUFFER_LENGTH(bufev->output) != 0) {
427 ret = tls_write(req->ctx, EVBUFFER_DATA(bufev->output),
428 EVBUFFER_LENGTH(bufev->output));
430 case TLS_WANT_POLLIN:
431 case TLS_WANT_POLLOUT:
434 what |= EVBUFFER_ERROR;
438 evbuffer_drain(bufev->output, len);
441 if (EVBUFFER_LENGTH(bufev->output) != 0)
442 event_add(&bufev->ev_write, NULL);
444 if (bufev->writecb != NULL &&
445 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
446 (*bufev->writecb)(bufev, bufev->cbarg);
450 event_add(&bufev->ev_write, NULL);
454 (*bufev->errorcb)(bufev, what, bufev->cbarg);
458 gemini_parse_reply(struct req *req, const char *header, size_t len)
466 if (!isdigit(header[0]) || !isdigit(header[1]))
469 code = (header[0] - '0')*10 + (header[1] - '0');
470 if (header[2] != ' ')
475 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
476 net_send_ui(IMSG_GOT_META, req->id, t, strlen(t)+1);
478 bufferevent_disable(req->bev, EV_READ|EV_WRITE);
480 if (code < 20 || code >= 30)
481 close_conn(0, 0, req);
485 /* called when we're ready to read/write */
487 net_ready(struct req *req)
489 req->bev = bufferevent_new(req->fd, net_read, net_write, net_error,
491 if (req->bev == NULL)
494 /* setup tls i/o layer */
495 if (req->ctx != NULL) {
496 event_set(&req->bev->ev_read, req->fd, EV_READ,
497 net_tls_readcb, req->bev);
498 event_set(&req->bev->ev_write, req->fd, EV_WRITE,
499 net_tls_writecb, req->bev);
502 /* TODO: adjust watermarks */
503 bufferevent_setwatermark(req->bev, EV_WRITE, 1, 0);
504 bufferevent_setwatermark(req->bev, EV_READ, 1, 0);
506 bufferevent_enable(req->bev, EV_READ|EV_WRITE);
508 bufferevent_write(req->bev, req->req, req->len);
511 /* called after a read has been done */
513 net_read(struct bufferevent *bev, void *d)
516 struct evbuffer *src = EVBUFFER_INPUT(bev);
522 if (!req->done_header) {
523 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
524 if (header == NULL && EVBUFFER_LENGTH(src) >= 1024)
528 r = gemini_parse_reply(req, header, len);
532 req->done_header = 1;
536 if ((len = EVBUFFER_LENGTH(src)) == 0)
538 data = EVBUFFER_DATA(src);
539 net_send_ui(IMSG_BUF, req->id, data, len);
540 evbuffer_drain(src, len);
544 (*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg);
547 /* called after a write has been done */
549 net_write(struct bufferevent *bev, void *d)
551 struct evbuffer *dst = EVBUFFER_OUTPUT(bev);
553 if (EVBUFFER_LENGTH(dst) == 0)
554 (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg);
558 net_error(struct bufferevent *bev, short error, void *d)
562 if (error & EVBUFFER_TIMEOUT) {
563 close_with_err(req, "Timeout loading page");
567 if (error & EVBUFFER_ERROR) {
568 close_with_err(req, "buffer event error");
572 if (error & EVBUFFER_EOF) {
573 net_send_ui(IMSG_EOF, req->id, NULL, 0);
574 close_conn(0, 0, req);
578 if (error & EVBUFFER_WRITE) {
579 /* finished sending request */
580 bufferevent_disable(bev, EV_WRITE);
584 if (error & EVBUFFER_READ) {
585 close_with_err(req, "protocol error");
589 close_with_errf(req, "unknown event error %x", error);
593 handle_get_raw(struct imsg *imsg, size_t datalen)
600 if (datalen != sizeof(*r))
603 if ((req = calloc(1, sizeof(*req))) == NULL)
606 req->id = imsg->hdr.peerid;
607 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
609 strlcpy(req->url.host, r->host, sizeof(req->url.host));
610 strlcpy(req->url.port, r->port, sizeof(req->url.port));
612 strlcpy(req->req, r->req, sizeof(req->req));
613 req->len = strlen(r->req);
616 async_conn_towards(req);
618 blocking_conn_towards(req);
623 handle_cert_status(struct imsg *imsg, size_t datalen)
628 req = req_by_id(imsg->hdr.peerid);
630 if (datalen < sizeof(is_ok))
632 memcpy(&is_ok, imsg->data, sizeof(is_ok));
637 close_conn(0, 0, req);
641 handle_proceed(struct imsg *imsg, size_t datalen)
645 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
648 bufferevent_enable(req->bev, EV_READ);
652 handle_stop(struct imsg *imsg, size_t datalen)
656 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
658 close_conn(0, 0, req);
662 handle_quit(struct imsg *imsg, size_t datalen)
668 handle_dispatch_imsg(int fd, short ev, void *d)
670 struct imsgev *iev = d;
672 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
673 err(1, "connection closed");
677 net_send_ui(int type, uint32_t peerid, const void *data,
680 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
689 TAILQ_INIT(&reqhead);
691 if ((tlsconf = tls_config_new()) == NULL)
693 tls_config_insecure_noverifycert(tlsconf);
694 tls_config_insecure_noverifyname(tlsconf);
698 /* Setup pipe and event handler to the main process */
699 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
701 imsg_init(&iev_ui->ibuf, 3);
702 iev_ui->handler = handle_dispatch_imsg;
703 iev_ui->events = EV_READ;
704 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
705 iev_ui->handler, iev_ui);
706 event_add(&iev_ui->ev, NULL);
708 sandbox_net_process();
712 tls_config_free(tlsconf);
713 msgbuf_clear(&iev_ui->ibuf.w);
714 close(iev_ui->ibuf.fd);