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"
42 static struct imsgev *iev_ui;
44 /* a pending request */
54 struct bufferevent *bev;
56 struct addrinfo *servinfo, *p;
58 struct addrinfo hints;
59 struct event_asr *asrev;
62 TAILQ_ENTRY(req) reqs;
65 static struct req *req_by_id(uint32_t);
67 static void die(void) __attribute__((__noreturn__));
69 static void try_to_connect(int, short, void*);
72 static void query_done(struct asr_result*, void*);
73 static void async_conn_towards(struct req*);
75 static void blocking_conn_towards(struct req*);
78 static void close_with_err(struct req*, const char*);
79 static void close_with_errf(struct req*, const char*, ...)
80 __attribute__((format(printf, 2, 3)));
82 static void net_tls_handshake(int, short, void *);
83 static void net_tls_readcb(int, short, void *);
84 static void net_tls_writecb(int, short, void *);
86 static int gemini_parse_reply(struct req *, const char *, size_t);
88 static void net_ready(struct req *req);
89 static void net_read(struct bufferevent *, void *);
90 static void net_write(struct bufferevent *, void *);
91 static void net_error(struct bufferevent *, short, void *);
93 static void handle_get_raw(struct imsg *, size_t);
94 static void handle_cert_status(struct imsg*, size_t);
95 static void handle_proceed(struct imsg*, size_t);
96 static void handle_stop(struct imsg*, size_t);
97 static void handle_quit(struct imsg*, size_t);
98 static void handle_dispatch_imsg(int, short, void*);
100 static int net_send_ui(int, uint32_t, const void *, uint16_t);
102 /* TODO: making this customizable */
103 struct timeval timeout_for_handshake = { 5, 0 };
105 static imsg_handlerfn *handlers[] = {
106 [IMSG_GET_RAW] = handle_get_raw,
107 [IMSG_CERT_STATUS] = handle_cert_status,
108 [IMSG_PROCEED] = handle_proceed,
109 [IMSG_STOP] = handle_stop,
110 [IMSG_QUIT] = handle_quit,
113 typedef void (*statefn)(int, short, void*);
115 TAILQ_HEAD(, req) reqhead;
118 yield_r(struct req *req, statefn fn, struct timeval *tv)
120 event_once(req->fd, EV_READ, fn, req, tv);
124 yield_w(struct req *req, statefn fn, struct timeval *tv)
126 event_once(req->fd, EV_WRITE, fn, req, tv);
130 req_by_id(uint32_t id)
134 TAILQ_FOREACH(r, &reqhead, reqs) {
142 static void __attribute__((__noreturn__))
149 try_to_connect(int fd, short ev, void *d)
153 socklen_t len = sizeof(error);
160 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error,
170 req->fd = socket(req->p->ai_family, req->p->ai_socktype,
171 req->p->ai_protocol);
173 req->p = req->p->ai_next;
176 mark_nonblock(req->fd);
177 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
179 yield_w(req, try_to_connect, NULL);
184 freeaddrinfo(req->servinfo);
185 close_with_errf(req, "failed to connect to %s",
190 freeaddrinfo(req->servinfo);
192 switch (req->proto) {
195 /* finger and gopher don't have a header nor TLS */
196 req->done_header = 1;
201 struct tls_config *conf;
203 if ((conf = tls_config_new()) == NULL)
206 tls_config_insecure_noverifycert(conf);
207 tls_config_insecure_noverifyname(conf);
210 if ((req->ctx = tls_client()) == NULL) {
211 close_with_errf(req, "tls_client: %s",
216 if (tls_configure(req->ctx, conf) == -1) {
217 close_with_errf(req, "tls_configure: %s",
218 tls_error(req->ctx));
221 tls_config_free(conf);
223 if (tls_connect_socket(req->ctx, req->fd, req->url.host)
225 close_with_errf(req, "tls_connect_socket: %s",
226 tls_error(req->ctx));
229 yield_w(req, net_tls_handshake, &timeout_for_handshake);
240 query_done(struct asr_result *res, void *d)
245 if (res->ar_gai_errno != 0) {
246 close_with_errf(req, "failed to resolve %s: %s",
247 req->url.host, gai_strerror(res->ar_gai_errno));
252 req->servinfo = res->ar_addrinfo;
253 req->p = res->ar_addrinfo;
254 try_to_connect(0, 0, req);
258 async_conn_towards(struct req *req)
261 const char *proto = "1965";
263 if (*req->url.port != '\0')
264 proto = req->url.port;
266 req->hints.ai_family = AF_UNSPEC;
267 req->hints.ai_socktype = SOCK_STREAM;
268 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
269 req->asrev = event_asr_run(q, query_done, req);
273 blocking_conn_towards(struct req *req)
275 struct addrinfo hints;
276 struct phos_uri *url = &req->url;
278 const char *proto = "1965";
280 if (*url->port != '\0')
283 memset(&hints, 0, sizeof(hints));
284 hints.ai_family = AF_UNSPEC;
285 hints.ai_socktype = SOCK_STREAM;
287 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
288 close_with_errf(req, "failed to resolve %s: %s",
289 url->host, gai_strerror(status));
294 req->p = req->servinfo;
295 try_to_connect(0, 0, req);
300 close_conn(int fd, short ev, void *d)
305 if (req->asrev != NULL)
306 event_asr_abort(req->asrev);
309 if (req->bev != NULL) {
310 bufferevent_free(req->bev);
314 if (req->ctx != NULL) {
315 switch (tls_close(req->ctx)) {
316 case TLS_WANT_POLLIN:
317 yield_r(req, close_conn, NULL);
319 case TLS_WANT_POLLOUT:
320 yield_w(req, close_conn, NULL);
328 TAILQ_REMOVE(&reqhead, req, reqs);
335 close_with_err(struct req *req, const char *err)
337 net_send_ui(IMSG_ERR, req->id, err, strlen(err)+1);
338 close_conn(0, 0, req);
342 close_with_errf(struct req *req, const char *fmt, ...)
348 if (vasprintf(&s, fmt, ap) == -1)
352 close_with_err(req, s);
357 net_tls_handshake(int fd, short event, void *d)
362 if (event == EV_TIMEOUT) {
363 close_with_err(req, "Timeout loading page");
367 switch (tls_handshake(req->ctx)) {
368 case TLS_WANT_POLLIN:
369 yield_r(req, net_tls_handshake, NULL);
371 case TLS_WANT_POLLOUT:
372 yield_w(req, net_tls_handshake, NULL);
376 hash = tls_peer_cert_hash(req->ctx);
378 close_with_errf(req, "handshake failed: %s",
379 tls_error(req->ctx));
382 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
386 net_tls_readcb(int fd, short event, void *d)
388 struct bufferevent *bufev = d;
389 struct req *req = bufev->cbarg;
390 char buf[IBUF_READ_SIZE];
391 int what = EVBUFFER_READ;
392 int howmuch = IBUF_READ_SIZE;
397 if (event == EV_TIMEOUT) {
398 what |= EVBUFFER_TIMEOUT;
402 if (bufev->wm_read.high != 0)
403 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
405 switch (ret = tls_read(req->ctx, buf, howmuch)) {
406 case TLS_WANT_POLLIN:
407 case TLS_WANT_POLLOUT:
410 what |= EVBUFFER_ERROR;
416 what |= EVBUFFER_EOF;
420 res = evbuffer_add(bufev->input, buf, len);
422 what |= EVBUFFER_ERROR;
426 event_add(&bufev->ev_read, NULL);
428 len = EVBUFFER_LENGTH(bufev->input);
429 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
432 if (bufev->readcb != NULL)
433 (*bufev->readcb)(bufev, bufev->cbarg);
437 event_add(&bufev->ev_read, NULL);
441 (*bufev->errorcb)(bufev, what, bufev->cbarg);
445 net_tls_writecb(int fd, short event, void *d)
447 struct bufferevent *bufev = d;
448 struct req *req = bufev->cbarg;
451 short what = EVBUFFER_WRITE;
453 if (event & EV_TIMEOUT) {
454 what |= EVBUFFER_TIMEOUT;
458 if (EVBUFFER_LENGTH(bufev->output) != 0) {
459 ret = tls_write(req->ctx, EVBUFFER_DATA(bufev->output),
460 EVBUFFER_LENGTH(bufev->output));
462 case TLS_WANT_POLLIN:
463 case TLS_WANT_POLLOUT:
466 what |= EVBUFFER_ERROR;
471 evbuffer_drain(bufev->output, len);
474 if (EVBUFFER_LENGTH(bufev->output) != 0)
475 event_add(&bufev->ev_write, NULL);
477 if (bufev->writecb != NULL &&
478 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
479 (*bufev->writecb)(bufev, bufev->cbarg);
483 event_add(&bufev->ev_write, NULL);
487 (*bufev->errorcb)(bufev, what, bufev->cbarg);
491 gemini_parse_reply(struct req *req, const char *header, size_t len)
499 if (!isdigit(header[0]) || !isdigit(header[1]))
502 code = (header[0] - '0')*10 + (header[1] - '0');
503 if (header[2] != ' ')
508 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
509 net_send_ui(IMSG_GOT_META, req->id, t, strlen(t)+1);
511 bufferevent_disable(req->bev, EV_READ|EV_WRITE);
513 if (code < 20 || code >= 30)
514 close_conn(0, 0, req);
518 /* called when we're ready to read/write */
520 net_ready(struct req *req)
522 req->bev = bufferevent_new(req->fd, net_read, net_write, net_error,
524 if (req->bev == NULL)
528 evbuffer_unfreeze(req->bev->input, 0);
529 evbuffer_unfreeze(req->bev->output, 1);
532 /* setup tls i/o layer */
533 if (req->ctx != NULL) {
534 event_set(&req->bev->ev_read, req->fd, EV_READ,
535 net_tls_readcb, req->bev);
536 event_set(&req->bev->ev_write, req->fd, EV_WRITE,
537 net_tls_writecb, req->bev);
540 /* TODO: adjust watermarks */
541 bufferevent_setwatermark(req->bev, EV_WRITE, 1, 0);
542 bufferevent_setwatermark(req->bev, EV_READ, 1, 0);
544 bufferevent_enable(req->bev, EV_READ|EV_WRITE);
546 bufferevent_write(req->bev, req->req, req->len);
549 /* called after a read has been done */
551 net_read(struct bufferevent *bev, void *d)
554 struct evbuffer *src = EVBUFFER_INPUT(bev);
560 if (!req->done_header) {
561 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
562 if (header == NULL && EVBUFFER_LENGTH(src) >= 1024)
566 r = gemini_parse_reply(req, header, len);
570 req->done_header = 1;
574 if ((len = EVBUFFER_LENGTH(src)) == 0)
576 data = EVBUFFER_DATA(src);
579 * Split data into chunks before sending. imsg can't handle
580 * message that are "too big".
583 chunk = MIN(len, 4096);
584 net_send_ui(IMSG_BUF, req->id, data, chunk);
589 evbuffer_drain(src, EVBUFFER_LENGTH(src));
593 (*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg);
596 /* called after a write has been done */
598 net_write(struct bufferevent *bev, void *d)
600 struct evbuffer *dst = EVBUFFER_OUTPUT(bev);
602 if (EVBUFFER_LENGTH(dst) == 0)
603 (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg);
607 net_error(struct bufferevent *bev, short error, void *d)
610 struct evbuffer *src;
612 if (error & EVBUFFER_TIMEOUT) {
613 close_with_err(req, "Timeout loading page");
617 if (error & EVBUFFER_ERROR) {
618 close_with_err(req, "buffer event error");
622 if (error & EVBUFFER_EOF) {
623 /* EOF and no header */
624 if (!req->done_header) {
625 close_with_err(req, "protocol error");
629 src = EVBUFFER_INPUT(req->bev);
630 if (EVBUFFER_LENGTH(src) != 0)
631 net_send_ui(IMSG_BUF, req->id, EVBUFFER_DATA(src),
632 EVBUFFER_LENGTH(src));
633 net_send_ui(IMSG_EOF, req->id, NULL, 0);
634 close_conn(0, 0, req);
638 if (error & EVBUFFER_WRITE) {
639 /* finished sending request */
640 bufferevent_disable(bev, EV_WRITE);
644 if (error & EVBUFFER_READ) {
645 close_with_err(req, "protocol error");
649 close_with_errf(req, "unknown event error %x", error);
653 handle_get_raw(struct imsg *imsg, size_t datalen)
660 if (datalen != sizeof(*r))
663 if ((req = calloc(1, sizeof(*req))) == NULL)
666 req->id = imsg->hdr.peerid;
667 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
669 strlcpy(req->url.host, r->host, sizeof(req->url.host));
670 strlcpy(req->url.port, r->port, sizeof(req->url.port));
672 strlcpy(req->req, r->req, sizeof(req->req));
673 req->len = strlen(r->req);
675 req->proto = r->proto;
678 async_conn_towards(req);
680 blocking_conn_towards(req);
685 handle_cert_status(struct imsg *imsg, size_t datalen)
690 req = req_by_id(imsg->hdr.peerid);
692 if (datalen < sizeof(is_ok))
694 memcpy(&is_ok, imsg->data, sizeof(is_ok));
699 close_conn(0, 0, req);
703 handle_proceed(struct imsg *imsg, size_t datalen)
707 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
710 bufferevent_enable(req->bev, EV_READ);
714 handle_stop(struct imsg *imsg, size_t datalen)
718 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
720 close_conn(0, 0, req);
724 handle_quit(struct imsg *imsg, size_t datalen)
730 handle_dispatch_imsg(int fd, short ev, void *d)
732 struct imsgev *iev = d;
734 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
735 err(1, "connection closed");
739 net_send_ui(int type, uint32_t peerid, const void *data,
742 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
751 TAILQ_INIT(&reqhead);
755 /* Setup pipe and event handler to the main process */
756 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
758 imsg_init(&iev_ui->ibuf, 3);
759 iev_ui->handler = handle_dispatch_imsg;
760 iev_ui->events = EV_READ;
761 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
762 iev_ui->handler, iev_ui);
763 event_add(&iev_ui->ev, NULL);
765 sandbox_net_process();
769 msgbuf_clear(&iev_ui->ibuf.w);
770 close(iev_ui->ibuf.fd);