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;
384 if (event == EV_TIMEOUT) {
385 what |= EVBUFFER_TIMEOUT;
389 if (bufev->wm_read.high != 0)
390 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
392 switch (ret = tls_read(req->ctx, buf, howmuch)) {
393 case TLS_WANT_POLLIN:
394 case TLS_WANT_POLLOUT:
397 what |= EVBUFFER_ERROR;
403 what |= EVBUFFER_EOF;
407 if (evbuffer_add(bufev->input, buf, len) == -1) {
408 what |= EVBUFFER_ERROR;
412 event_add(&bufev->ev_read, NULL);
414 len = EVBUFFER_LENGTH(bufev->input);
415 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
418 if (bufev->readcb != NULL)
419 (*bufev->readcb)(bufev, bufev->cbarg);
423 event_add(&bufev->ev_read, NULL);
427 (*bufev->errorcb)(bufev, what, bufev->cbarg);
431 net_tls_writecb(int fd, short event, void *d)
433 struct bufferevent *bufev = d;
434 struct req *req = bufev->cbarg;
437 short what = EVBUFFER_WRITE;
439 if (event & EV_TIMEOUT) {
440 what |= EVBUFFER_TIMEOUT;
444 if (EVBUFFER_LENGTH(bufev->output) != 0) {
445 ret = tls_write(req->ctx, EVBUFFER_DATA(bufev->output),
446 EVBUFFER_LENGTH(bufev->output));
448 case TLS_WANT_POLLIN:
449 case TLS_WANT_POLLOUT:
452 what |= EVBUFFER_ERROR;
456 evbuffer_drain(bufev->output, len);
459 if (EVBUFFER_LENGTH(bufev->output) != 0)
460 event_add(&bufev->ev_write, NULL);
462 if (bufev->writecb != NULL &&
463 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
464 (*bufev->writecb)(bufev, bufev->cbarg);
468 event_add(&bufev->ev_write, NULL);
472 (*bufev->errorcb)(bufev, what, bufev->cbarg);
476 gemini_parse_reply(struct req *req, const char *header, size_t len)
484 if (!isdigit(header[0]) || !isdigit(header[1]))
487 code = (header[0] - '0')*10 + (header[1] - '0');
488 if (header[2] != ' ')
493 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
494 net_send_ui(IMSG_GOT_META, req->id, t, strlen(t)+1);
496 bufferevent_disable(req->bev, EV_READ|EV_WRITE);
498 if (code < 20 || code >= 30)
499 close_conn(0, 0, req);
503 /* called when we're ready to read/write */
505 net_ready(struct req *req)
507 req->bev = bufferevent_new(req->fd, net_read, net_write, net_error,
509 if (req->bev == NULL)
512 /* setup tls i/o layer */
513 if (req->ctx != NULL) {
514 event_set(&req->bev->ev_read, req->fd, EV_READ,
515 net_tls_readcb, req->bev);
516 event_set(&req->bev->ev_write, req->fd, EV_WRITE,
517 net_tls_writecb, req->bev);
520 /* TODO: adjust watermarks */
521 bufferevent_setwatermark(req->bev, EV_WRITE, 1, 0);
522 bufferevent_setwatermark(req->bev, EV_READ, 1, 0);
524 bufferevent_enable(req->bev, EV_READ|EV_WRITE);
526 bufferevent_write(req->bev, req->req, req->len);
529 /* called after a read has been done */
531 net_read(struct bufferevent *bev, void *d)
534 struct evbuffer *src = EVBUFFER_INPUT(bev);
540 if (!req->done_header) {
541 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
542 if (header == NULL && EVBUFFER_LENGTH(src) >= 1024)
546 r = gemini_parse_reply(req, header, len);
550 req->done_header = 1;
554 if ((len = EVBUFFER_LENGTH(src)) == 0)
556 data = EVBUFFER_DATA(src);
557 net_send_ui(IMSG_BUF, req->id, data, len);
558 evbuffer_drain(src, len);
562 (*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg);
565 /* called after a write has been done */
567 net_write(struct bufferevent *bev, void *d)
569 struct evbuffer *dst = EVBUFFER_OUTPUT(bev);
571 if (EVBUFFER_LENGTH(dst) == 0)
572 (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg);
576 net_error(struct bufferevent *bev, short error, void *d)
579 struct evbuffer *src;
581 if (error & EVBUFFER_TIMEOUT) {
582 close_with_err(req, "Timeout loading page");
586 if (error & EVBUFFER_ERROR) {
587 close_with_err(req, "buffer event error");
591 if (error & EVBUFFER_EOF) {
592 src = EVBUFFER_INPUT(req->bev);
593 if (EVBUFFER_LENGTH(src) != 0)
594 net_send_ui(IMSG_BUF, req->id, EVBUFFER_DATA(src),
595 EVBUFFER_LENGTH(src));
596 net_send_ui(IMSG_EOF, req->id, NULL, 0);
597 close_conn(0, 0, req);
601 if (error & EVBUFFER_WRITE) {
602 /* finished sending request */
603 bufferevent_disable(bev, EV_WRITE);
607 if (error & EVBUFFER_READ) {
608 close_with_err(req, "protocol error");
612 close_with_errf(req, "unknown event error %x", error);
616 handle_get_raw(struct imsg *imsg, size_t datalen)
623 if (datalen != sizeof(*r))
626 if ((req = calloc(1, sizeof(*req))) == NULL)
629 req->id = imsg->hdr.peerid;
630 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
632 strlcpy(req->url.host, r->host, sizeof(req->url.host));
633 strlcpy(req->url.port, r->port, sizeof(req->url.port));
635 strlcpy(req->req, r->req, sizeof(req->req));
636 req->len = strlen(r->req);
638 req->proto = r->proto;
641 async_conn_towards(req);
643 blocking_conn_towards(req);
648 handle_cert_status(struct imsg *imsg, size_t datalen)
653 req = req_by_id(imsg->hdr.peerid);
655 if (datalen < sizeof(is_ok))
657 memcpy(&is_ok, imsg->data, sizeof(is_ok));
662 close_conn(0, 0, req);
666 handle_proceed(struct imsg *imsg, size_t datalen)
670 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
673 bufferevent_enable(req->bev, EV_READ);
677 handle_stop(struct imsg *imsg, size_t datalen)
681 if ((req = req_by_id(imsg->hdr.peerid)) == NULL)
683 close_conn(0, 0, req);
687 handle_quit(struct imsg *imsg, size_t datalen)
693 handle_dispatch_imsg(int fd, short ev, void *d)
695 struct imsgev *iev = d;
697 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
698 err(1, "connection closed");
702 net_send_ui(int type, uint32_t peerid, const void *data,
705 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
714 TAILQ_INIT(&reqhead);
716 if ((tlsconf = tls_config_new()) == NULL)
718 tls_config_insecure_noverifycert(tlsconf);
719 tls_config_insecure_noverifyname(tlsconf);
723 /* Setup pipe and event handler to the main process */
724 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
726 imsg_init(&iev_ui->ibuf, 3);
727 iev_ui->handler = handle_dispatch_imsg;
728 iev_ui->events = EV_READ;
729 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
730 iev_ui->handler, iev_ui);
731 event_add(&iev_ui->ev, NULL);
733 sandbox_net_process();
737 tls_config_free(tlsconf);
738 msgbuf_clear(&iev_ui->ibuf.w);
739 close(iev_ui->ibuf.fd);