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 */
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;
202 if ((req->ctx = tls_client()) == NULL) {
203 close_with_errf(req, "tls_client: %s",
207 if (tls_configure(req->ctx, tlsconf) == -1) {
208 close_with_errf(req, "tls_configure: %s",
209 tls_error(req->ctx));
212 if (tls_connect_socket(req->ctx, req->fd, req->url.host)
214 close_with_errf(req, "tls_connect_socket: %s",
215 tls_error(req->ctx));
218 yield_w(req, net_tls_handshake, &timeout_for_handshake);
228 query_done(struct asr_result *res, void *d)
233 if (res->ar_gai_errno != 0) {
234 close_with_errf(req, "failed to resolve %s: %s",
235 req->url.host, gai_strerror(res->ar_gai_errno));
240 req->servinfo = res->ar_addrinfo;
241 req->p = res->ar_addrinfo;
242 try_to_connect(0, 0, req);
246 async_conn_towards(struct req *req)
249 const char *proto = "1965";
251 if (*req->url.port != '\0')
252 proto = req->url.port;
254 req->hints.ai_family = AF_UNSPEC;
255 req->hints.ai_socktype = SOCK_STREAM;
256 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
257 req->asrev = event_asr_run(q, query_done, req);
261 blocking_conn_towards(struct req *req)
263 struct addrinfo hints;
264 struct phos_uri *url = &req->url;
266 const char *proto = "1965";
268 if (*url->port != '\0')
271 memset(&hints, 0, sizeof(hints));
272 hints.ai_family = AF_UNSPEC;
273 hints.ai_socktype = SOCK_STREAM;
275 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
276 close_with_errf(req, "failed to resolve %s: %s",
277 url->host, gai_strerror(status));
282 req->p = req->servinfo;
283 try_to_connect(0, 0, req);
288 close_conn(int fd, short ev, void *d)
293 if (req->asrev != NULL)
294 event_asr_abort(req->asrev);
297 if (req->bev != NULL) {
298 bufferevent_free(req->bev);
302 if (req->ctx != NULL) {
303 switch (tls_close(req->ctx)) {
304 case TLS_WANT_POLLIN:
305 yield_r(req, close_conn, NULL);
307 case TLS_WANT_POLLOUT:
308 yield_w(req, close_conn, NULL);
316 TAILQ_REMOVE(&reqhead, req, reqs);
323 close_with_err(struct req *req, const char *err)
325 net_send_ui(IMSG_ERR, req->id, err, strlen(err)+1);
326 close_conn(0, 0, req);
330 close_with_errf(struct req *req, const char *fmt, ...)
336 if (vasprintf(&s, fmt, ap) == -1)
340 close_with_err(req, s);
345 net_tls_handshake(int fd, short event, void *d)
350 if (event == EV_TIMEOUT) {
351 close_with_err(req, "Timeout loading page");
355 switch (tls_handshake(req->ctx)) {
356 case TLS_WANT_POLLIN:
357 yield_r(req, net_tls_handshake, NULL);
359 case TLS_WANT_POLLOUT:
360 yield_w(req, net_tls_handshake, NULL);
364 hash = tls_peer_cert_hash(req->ctx);
366 close_with_errf(req, "handshake failed: %s",
367 tls_error(req->ctx));
370 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
374 net_tls_readcb(int fd, short event, void *d)
376 struct bufferevent *bufev = d;
377 struct req *req = bufev->cbarg;
378 char buf[IBUF_READ_SIZE];
379 int what = EVBUFFER_READ;
380 int howmuch = IBUF_READ_SIZE;
385 if (event == EV_TIMEOUT) {
386 what |= EVBUFFER_TIMEOUT;
390 if (bufev->wm_read.high != 0)
391 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
393 switch (ret = tls_read(req->ctx, buf, howmuch)) {
394 case TLS_WANT_POLLIN:
395 case TLS_WANT_POLLOUT:
398 what |= EVBUFFER_ERROR;
404 what |= EVBUFFER_EOF;
408 res = evbuffer_add(bufev->input, buf, len);
410 what |= EVBUFFER_ERROR;
414 event_add(&bufev->ev_read, NULL);
416 len = EVBUFFER_LENGTH(bufev->input);
417 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
420 if (bufev->readcb != NULL)
421 (*bufev->readcb)(bufev, bufev->cbarg);
425 event_add(&bufev->ev_read, NULL);
429 (*bufev->errorcb)(bufev, what, bufev->cbarg);
433 net_tls_writecb(int fd, short event, void *d)
435 struct bufferevent *bufev = d;
436 struct req *req = bufev->cbarg;
439 short what = EVBUFFER_WRITE;
441 if (event & EV_TIMEOUT) {
442 what |= EVBUFFER_TIMEOUT;
446 if (EVBUFFER_LENGTH(bufev->output) != 0) {
447 ret = tls_write(req->ctx, EVBUFFER_DATA(bufev->output),
448 EVBUFFER_LENGTH(bufev->output));
450 case TLS_WANT_POLLIN:
451 case TLS_WANT_POLLOUT:
454 what |= EVBUFFER_ERROR;
459 evbuffer_drain(bufev->output, len);
462 if (EVBUFFER_LENGTH(bufev->output) != 0)
463 event_add(&bufev->ev_write, NULL);
465 if (bufev->writecb != NULL &&
466 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
467 (*bufev->writecb)(bufev, bufev->cbarg);
471 event_add(&bufev->ev_write, NULL);
475 (*bufev->errorcb)(bufev, what, bufev->cbarg);
479 gemini_parse_reply(struct req *req, const char *header, size_t len)
487 if (!isdigit(header[0]) || !isdigit(header[1]))
490 code = (header[0] - '0')*10 + (header[1] - '0');
491 if (header[2] != ' ')
496 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
497 net_send_ui(IMSG_GOT_META, req->id, t, strlen(t)+1);
499 bufferevent_disable(req->bev, EV_READ|EV_WRITE);
501 if (code < 20 || code >= 30)
502 close_conn(0, 0, req);
506 /* called when we're ready to read/write */
508 net_ready(struct req *req)
510 req->bev = bufferevent_new(req->fd, net_read, net_write, net_error,
512 if (req->bev == NULL)
516 evbuffer_unfreeze(req->bev->input, 0);
517 evbuffer_unfreeze(req->bev->output, 1);
520 /* setup tls i/o layer */
521 if (req->ctx != NULL) {
522 event_set(&req->bev->ev_read, req->fd, EV_READ,
523 net_tls_readcb, req->bev);
524 event_set(&req->bev->ev_write, req->fd, EV_WRITE,
525 net_tls_writecb, req->bev);
528 /* TODO: adjust watermarks */
529 bufferevent_setwatermark(req->bev, EV_WRITE, 1, 0);
530 bufferevent_setwatermark(req->bev, EV_READ, 1, 0);
532 bufferevent_enable(req->bev, EV_READ|EV_WRITE);
534 bufferevent_write(req->bev, req->req, req->len);
537 /* called after a read has been done */
539 net_read(struct bufferevent *bev, void *d)
542 struct evbuffer *src = EVBUFFER_INPUT(bev);
548 if (!req->done_header) {
549 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
550 if (header == NULL && EVBUFFER_LENGTH(src) >= 1024)
554 r = gemini_parse_reply(req, header, len);
558 req->done_header = 1;
562 if ((len = EVBUFFER_LENGTH(src)) == 0)
564 data = EVBUFFER_DATA(src);
567 * Split data into chunks before sending. imsg can't handle
568 * message that are "too big".
571 chunk = MIN(len, 4096);
572 net_send_ui(IMSG_BUF, req->id, data, chunk);
577 evbuffer_drain(src, EVBUFFER_LENGTH(src));
581 (*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg);
584 /* called after a write has been done */
586 net_write(struct bufferevent *bev, void *d)
588 struct evbuffer *dst = EVBUFFER_OUTPUT(bev);
590 if (EVBUFFER_LENGTH(dst) == 0)
591 (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg);
595 net_error(struct bufferevent *bev, short error, void *d)
598 struct evbuffer *src;
600 if (error & EVBUFFER_TIMEOUT) {
601 close_with_err(req, "Timeout loading page");
605 if (error & EVBUFFER_ERROR) {
606 close_with_err(req, "buffer event error");
610 if (error & EVBUFFER_EOF) {
611 src = EVBUFFER_INPUT(req->bev);
612 if (EVBUFFER_LENGTH(src) != 0)
613 net_send_ui(IMSG_BUF, req->id, EVBUFFER_DATA(src),
614 EVBUFFER_LENGTH(src));
615 net_send_ui(IMSG_EOF, req->id, NULL, 0);
616 close_conn(0, 0, req);
620 if (error & EVBUFFER_WRITE) {
621 /* finished sending request */
622 bufferevent_disable(bev, EV_WRITE);
626 if (error & EVBUFFER_READ) {
627 close_with_err(req, "protocol error");
631 close_with_errf(req, "unknown event error %x", error);
635 handle_get_raw(struct imsg *imsg, size_t datalen)
642 if (datalen != sizeof(*r))
645 if ((req = calloc(1, sizeof(*req))) == NULL)
648 req->id = imsg->hdr.peerid;
649 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
651 strlcpy(req->url.host, r->host, sizeof(req->url.host));
652 strlcpy(req->url.port, r->port, sizeof(req->url.port));
654 strlcpy(req->req, r->req, sizeof(req->req));
655 req->len = strlen(r->req);
657 req->proto = r->proto;
660 async_conn_towards(req);
662 blocking_conn_towards(req);
667 handle_cert_status(struct imsg *imsg, size_t datalen)
672 req = req_by_id(imsg->hdr.peerid);
674 if (datalen < sizeof(is_ok))
676 memcpy(&is_ok, imsg->data, sizeof(is_ok));
681 close_conn(0, 0, req);
685 handle_proceed(struct imsg *imsg, size_t datalen)
689 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
692 bufferevent_enable(req->bev, EV_READ);
696 handle_stop(struct imsg *imsg, size_t datalen)
700 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
702 close_conn(0, 0, req);
706 handle_quit(struct imsg *imsg, size_t datalen)
712 handle_dispatch_imsg(int fd, short ev, void *d)
714 struct imsgev *iev = d;
716 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
717 err(1, "connection closed");
721 net_send_ui(int type, uint32_t peerid, const void *data,
724 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
733 TAILQ_INIT(&reqhead);
735 if ((tlsconf = tls_config_new()) == NULL)
737 tls_config_insecure_noverifycert(tlsconf);
738 tls_config_insecure_noverifyname(tlsconf);
742 /* Setup pipe and event handler to the main process */
743 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
745 imsg_init(&iev_ui->ibuf, 3);
746 iev_ui->handler = handle_dispatch_imsg;
747 iev_ui->events = EV_READ;
748 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
749 iev_ui->handler, iev_ui);
750 event_add(&iev_ui->ev, NULL);
752 sandbox_net_process();
756 tls_config_free(tlsconf);
757 msgbuf_clear(&iev_ui->ibuf.w);
758 close(iev_ui->ibuf.fd);