Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
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.
7 *
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.
15 */
17 #include "compat.h"
19 #include <sys/types.h>
20 #include <sys/socket.h>
22 #include <netinet/in.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <netdb.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <tls.h>
33 #include <unistd.h>
35 #if HAVE_ASR_RUN
36 # include <asr.h>
37 #endif
39 #include "telescope.h"
40 #include "utils.h"
42 static struct imsgev *iev_ui;
44 /* a pending request */
45 struct req {
46 struct phos_uri url;
47 uint32_t id;
48 int proto;
49 int fd;
50 struct tls *ctx;
51 char req[1027];
52 size_t len;
53 int done_header;
54 struct bufferevent *bev;
56 struct addrinfo *servinfo, *p;
57 #if HAVE_ASR_RUN
58 struct addrinfo hints;
59 struct event_asr *asrev;
60 #endif
62 TAILQ_ENTRY(req) reqs;
63 };
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*);
71 #if HAVE_ASR_RUN
72 static void query_done(struct asr_result*, void*);
73 #endif
74 static void conn_towards(struct req*);
76 static void close_with_err(struct req*, const char*);
77 static void close_with_errf(struct req*, const char*, ...)
78 __attribute__((format(printf, 2, 3)));
80 static void net_tls_handshake(int, short, void *);
81 static void net_tls_readcb(int, short, void *);
82 static void net_tls_writecb(int, short, void *);
84 static int gemini_parse_reply(struct req *, const char *, size_t);
86 static void net_ready(struct req *req);
87 static void net_read(struct bufferevent *, void *);
88 static void net_write(struct bufferevent *, void *);
89 static void net_error(struct bufferevent *, short, void *);
91 static void handle_dispatch_imsg(int, short, void*);
93 static int net_send_ui(int, uint32_t, const void *, uint16_t);
95 /* TODO: making this customizable */
96 struct timeval timeout_for_handshake = { 5, 0 };
98 typedef void (*statefn)(int, short, void*);
100 TAILQ_HEAD(, req) reqhead;
102 static inline void
103 yield_r(struct req *req, statefn fn, struct timeval *tv)
105 event_once(req->fd, EV_READ, fn, req, tv);
108 static inline void
109 yield_w(struct req *req, statefn fn, struct timeval *tv)
111 event_once(req->fd, EV_WRITE, fn, req, tv);
114 static struct req *
115 req_by_id(uint32_t id)
117 struct req *r;
119 TAILQ_FOREACH(r, &reqhead, reqs) {
120 if (r->id == id)
121 return r;
124 return NULL;
127 static void __attribute__((__noreturn__))
128 die(void)
130 abort(); /* TODO */
133 static void
134 try_to_connect(int fd, short ev, void *d)
136 struct req *req = d;
137 int error = 0;
138 socklen_t len = sizeof(error);
140 again:
141 if (req->p == NULL)
142 goto err;
144 if (req->fd != -1) {
145 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error,
146 &len) == -1)
147 goto err;
148 if (error != 0) {
149 errno = error;
150 goto err;
152 goto done;
155 req->fd = socket(req->p->ai_family, req->p->ai_socktype,
156 req->p->ai_protocol);
157 if (req->fd == -1) {
158 req->p = req->p->ai_next;
159 goto again;
162 if (!mark_nonblock_cloexec(req->fd))
163 goto err;
164 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
165 goto done;
166 yield_w(req, try_to_connect, NULL);
167 return;
169 err:
170 freeaddrinfo(req->servinfo);
171 close_with_errf(req, "failed to connect to %s",
172 req->url.host);
173 return;
175 done:
176 freeaddrinfo(req->servinfo);
178 switch (req->proto) {
179 case PROTO_FINGER:
180 case PROTO_GOPHER:
181 /* finger and gopher don't have a header nor TLS */
182 req->done_header = 1;
183 net_ready(req);
184 break;
186 case PROTO_GEMINI: {
187 struct tls_config *conf;
189 if ((conf = tls_config_new()) == NULL)
190 die();
192 tls_config_insecure_noverifycert(conf);
193 tls_config_insecure_noverifyname(conf);
195 /* prepare tls */
196 if ((req->ctx = tls_client()) == NULL) {
197 close_with_errf(req, "tls_client: %s",
198 strerror(errno));
199 return;
202 if (tls_configure(req->ctx, conf) == -1) {
203 close_with_errf(req, "tls_configure: %s",
204 tls_error(req->ctx));
205 return;
207 tls_config_free(conf);
209 if (tls_connect_socket(req->ctx, req->fd, req->url.host)
210 == -1) {
211 close_with_errf(req, "tls_connect_socket: %s",
212 tls_error(req->ctx));
213 return;
215 yield_w(req, net_tls_handshake, &timeout_for_handshake);
216 break;
219 default:
220 die();
224 #if HAVE_ASR_RUN
225 static void
226 query_done(struct asr_result *res, void *d)
228 struct req *req = d;
230 req->asrev = NULL;
231 if (res->ar_gai_errno != 0) {
232 close_with_errf(req, "failed to resolve %s: %s",
233 req->url.host, gai_strerror(res->ar_gai_errno));
234 return;
237 req->fd = -1;
238 req->servinfo = res->ar_addrinfo;
239 req->p = res->ar_addrinfo;
240 try_to_connect(0, 0, req);
243 static void
244 conn_towards(struct req *req)
246 struct asr_query *q;
247 const char *proto = "1965";
249 if (*req->url.port != '\0')
250 proto = req->url.port;
252 req->hints.ai_family = AF_UNSPEC;
253 req->hints.ai_socktype = SOCK_STREAM;
254 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
255 req->asrev = event_asr_run(q, query_done, req);
257 #else
258 static void
259 conn_towards(struct req *req)
261 struct addrinfo hints;
262 struct phos_uri *url = &req->url;
263 int status;
264 const char *proto = "1965";
266 if (*url->port != '\0')
267 proto = url->port;
269 memset(&hints, 0, sizeof(hints));
270 hints.ai_family = AF_UNSPEC;
271 hints.ai_socktype = SOCK_STREAM;
273 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
274 close_with_errf(req, "failed to resolve %s: %s",
275 url->host, gai_strerror(status));
276 return;
279 req->fd = -1;
280 req->p = req->servinfo;
281 try_to_connect(0, 0, req);
283 #endif
285 static void
286 close_conn(int fd, short ev, void *d)
288 struct req *req = d;
290 #if HAVE_ASR_RUN
291 if (req->asrev != NULL)
292 event_asr_abort(req->asrev);
293 #endif
295 if (req->bev != NULL) {
296 bufferevent_free(req->bev);
297 req->bev = NULL;
300 if (req->ctx != NULL) {
301 switch (tls_close(req->ctx)) {
302 case TLS_WANT_POLLIN:
303 yield_r(req, close_conn, NULL);
304 return;
305 case TLS_WANT_POLLOUT:
306 yield_w(req, close_conn, NULL);
307 return;
310 tls_free(req->ctx);
311 req->ctx = NULL;
314 TAILQ_REMOVE(&reqhead, req, reqs);
315 if (req->fd != -1)
316 close(req->fd);
317 free(req);
320 static void
321 close_with_err(struct req *req, const char *err)
323 net_send_ui(IMSG_ERR, req->id, err, strlen(err)+1);
324 close_conn(0, 0, req);
327 static void
328 close_with_errf(struct req *req, const char *fmt, ...)
330 va_list ap;
331 char *s;
333 va_start(ap, fmt);
334 if (vasprintf(&s, fmt, ap) == -1)
335 abort();
336 va_end(ap);
338 close_with_err(req, s);
339 free(s);
342 static void
343 net_tls_handshake(int fd, short event, void *d)
345 struct req *req = d;
346 const char *hash;
348 if (event == EV_TIMEOUT) {
349 close_with_err(req, "Timeout loading page");
350 return;
353 switch (tls_handshake(req->ctx)) {
354 case TLS_WANT_POLLIN:
355 yield_r(req, net_tls_handshake, NULL);
356 return;
357 case TLS_WANT_POLLOUT:
358 yield_w(req, net_tls_handshake, NULL);
359 return;
362 hash = tls_peer_cert_hash(req->ctx);
363 if (hash == NULL) {
364 close_with_errf(req, "handshake failed: %s",
365 tls_error(req->ctx));
366 return;
368 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
371 static void
372 net_tls_readcb(int fd, short event, void *d)
374 struct bufferevent *bufev = d;
375 struct req *req = bufev->cbarg;
376 char buf[IBUF_READ_SIZE];
377 int what = EVBUFFER_READ;
378 int howmuch = IBUF_READ_SIZE;
379 int res;
380 ssize_t ret;
381 size_t len;
383 if (event == EV_TIMEOUT) {
384 what |= EVBUFFER_TIMEOUT;
385 goto err;
388 if (bufev->wm_read.high != 0)
389 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
391 switch (ret = tls_read(req->ctx, buf, howmuch)) {
392 case TLS_WANT_POLLIN:
393 case TLS_WANT_POLLOUT:
394 goto retry;
395 case -1:
396 what |= EVBUFFER_ERROR;
397 goto err;
399 len = ret;
401 if (len == 0) {
402 what |= EVBUFFER_EOF;
403 goto err;
406 res = evbuffer_add(bufev->input, buf, len);
407 if (res == -1) {
408 what |= EVBUFFER_ERROR;
409 goto err;
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)
416 return;
418 if (bufev->readcb != NULL)
419 (*bufev->readcb)(bufev, bufev->cbarg);
420 return;
422 retry:
423 event_add(&bufev->ev_read, NULL);
424 return;
426 err:
427 (*bufev->errorcb)(bufev, what, bufev->cbarg);
430 static void
431 net_tls_writecb(int fd, short event, void *d)
433 struct bufferevent *bufev = d;
434 struct req *req = bufev->cbarg;
435 ssize_t ret;
436 size_t len;
437 short what = EVBUFFER_WRITE;
439 if (event & EV_TIMEOUT) {
440 what |= EVBUFFER_TIMEOUT;
441 goto err;
444 if (EVBUFFER_LENGTH(bufev->output) != 0) {
445 ret = tls_write(req->ctx, EVBUFFER_DATA(bufev->output),
446 EVBUFFER_LENGTH(bufev->output));
447 switch (ret) {
448 case TLS_WANT_POLLIN:
449 case TLS_WANT_POLLOUT:
450 goto retry;
451 case -1:
452 what |= EVBUFFER_ERROR;
453 goto err;
455 len = ret;
457 evbuffer_drain(bufev->output, len);
460 if (EVBUFFER_LENGTH(bufev->output) != 0)
461 event_add(&bufev->ev_write, NULL);
463 if (bufev->writecb != NULL &&
464 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
465 (*bufev->writecb)(bufev, bufev->cbarg);
466 return;
468 retry:
469 event_add(&bufev->ev_write, NULL);
470 return;
472 err:
473 (*bufev->errorcb)(bufev, what, bufev->cbarg);
476 static int
477 gemini_parse_reply(struct req *req, const char *header, size_t len)
479 int code;
480 const char *t;
482 if (len < 4)
483 return 0;
485 if (!isdigit(header[0]) || !isdigit(header[1]))
486 return 0;
488 code = (header[0] - '0')*10 + (header[1] - '0');
489 if (header[2] != ' ')
490 return 0;
492 t = header + 3;
494 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
495 net_send_ui(IMSG_GOT_META, req->id, t, strlen(t)+1);
497 bufferevent_disable(req->bev, EV_READ|EV_WRITE);
499 return code;
502 /* called when we're ready to read/write */
503 static void
504 net_ready(struct req *req)
506 req->bev = bufferevent_new(req->fd, net_read, net_write, net_error,
507 req);
508 if (req->bev == NULL)
509 die();
511 #if HAVE_EVENT2
512 evbuffer_unfreeze(req->bev->input, 0);
513 evbuffer_unfreeze(req->bev->output, 1);
514 #endif
516 /* setup tls i/o layer */
517 if (req->ctx != NULL) {
518 event_set(&req->bev->ev_read, req->fd, EV_READ,
519 net_tls_readcb, req->bev);
520 event_set(&req->bev->ev_write, req->fd, EV_WRITE,
521 net_tls_writecb, req->bev);
524 /* TODO: adjust watermarks */
525 bufferevent_setwatermark(req->bev, EV_WRITE, 1, 0);
526 bufferevent_setwatermark(req->bev, EV_READ, 1, 0);
528 bufferevent_enable(req->bev, EV_READ|EV_WRITE);
530 bufferevent_write(req->bev, req->req, req->len);
533 /* called after a read has been done */
534 static void
535 net_read(struct bufferevent *bev, void *d)
537 struct req *req = d;
538 struct evbuffer *src = EVBUFFER_INPUT(bev);
539 uint8_t *data;
540 size_t len, chunk;
541 int r;
542 char *header;
544 if (!req->done_header) {
545 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
546 if (header == NULL && EVBUFFER_LENGTH(src) >= 1024)
547 goto err;
548 if (header == NULL)
549 return;
550 r = gemini_parse_reply(req, header, len);
551 free(header);
552 req->done_header = 1;
553 if (r == 0)
554 goto err;
555 else if (r < 20 || r >= 30)
556 close_conn(0, 0, req);
557 return;
560 if ((len = EVBUFFER_LENGTH(src)) == 0)
561 return;
562 data = EVBUFFER_DATA(src);
564 /*
565 * Split data into chunks before sending. imsg can't handle
566 * message that are "too big".
567 */
568 while (len != 0) {
569 chunk = MIN(len, 4096);
570 net_send_ui(IMSG_BUF, req->id, data, chunk);
571 data += chunk;
572 len -= chunk;
575 evbuffer_drain(src, EVBUFFER_LENGTH(src));
576 return;
578 err:
579 (*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg);
582 /* called after a write has been done */
583 static void
584 net_write(struct bufferevent *bev, void *d)
586 struct evbuffer *dst = EVBUFFER_OUTPUT(bev);
588 if (EVBUFFER_LENGTH(dst) == 0)
589 (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg);
592 static void
593 net_error(struct bufferevent *bev, short error, void *d)
595 struct req *req = d;
596 struct evbuffer *src;
598 if (error & EVBUFFER_TIMEOUT) {
599 close_with_err(req, "Timeout loading page");
600 return;
603 if (error & EVBUFFER_ERROR) {
604 close_with_err(req, "buffer event error");
605 return;
608 if (error & EVBUFFER_EOF) {
609 /* EOF and no header */
610 if (!req->done_header) {
611 close_with_err(req, "protocol error");
612 return;
615 src = EVBUFFER_INPUT(req->bev);
616 if (EVBUFFER_LENGTH(src) != 0)
617 net_send_ui(IMSG_BUF, req->id, EVBUFFER_DATA(src),
618 EVBUFFER_LENGTH(src));
619 net_send_ui(IMSG_EOF, req->id, NULL, 0);
620 close_conn(0, 0, req);
621 return;
624 if (error & EVBUFFER_WRITE) {
625 /* finished sending request */
626 bufferevent_disable(bev, EV_WRITE);
627 return;
630 if (error & EVBUFFER_READ) {
631 close_with_err(req, "protocol error");
632 return;
635 close_with_errf(req, "unknown event error %x", error);
638 static void
639 handle_dispatch_imsg(int fd, short event, void *d)
641 struct imsgev *iev = d;
642 struct imsgbuf *ibuf = &iev->ibuf;
643 struct imsg imsg;
644 struct req *req;
645 struct get_req *r;
646 size_t datalen;
647 ssize_t n;
648 int certok;
650 if (event & EV_READ) {
651 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
652 err(1, "imsg_read");
653 if (n == 0)
654 err(1, "connection closed");
656 if (event & EV_WRITE) {
657 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
658 err(1, "msgbuf_write");
659 if (n == 0)
660 err(1, "connection closed");
663 for (;;) {
664 if ((n = imsg_get(ibuf, &imsg)) == -1)
665 err(1, "imsg_get");
666 if (n == 0)
667 break;
668 datalen = IMSG_DATA_SIZE(imsg);
669 switch (imsg.hdr.type) {
670 case IMSG_GET:
671 r = imsg.data;
672 if (datalen != sizeof(*r) ||
673 r->host[sizeof(r->host) - 1] != '\0' ||
674 r->port[sizeof(r->port) - 1] != '\0' ||
675 r->req[sizeof(r->req) - 1] != '\0')
676 die();
677 if (r->proto != PROTO_FINGER &&
678 r->proto != PROTO_GEMINI &&
679 r->proto != PROTO_GOPHER)
680 die();
682 if ((req = calloc(1, sizeof(*req))) == NULL)
683 die();
685 req->id = imsg.hdr.peerid;
686 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
688 strlcpy(req->url.host, r->host, sizeof(req->url.host));
689 strlcpy(req->url.port, r->port, sizeof(req->url.port));
690 req->len = strlcpy(req->req, r->req, sizeof(req->req));
691 req->proto = r->proto;
692 conn_towards(req);
693 break;
695 case IMSG_CERT_STATUS:
696 if ((req = req_by_id(imsg.hdr.peerid)) == NULL)
697 break;
699 if (datalen != sizeof(certok))
700 die();
701 memcpy(&certok, imsg.data, sizeof(certok));
702 if (certok)
703 net_ready(req);
704 else
705 close_conn(0, 0, req);
706 break;
708 case IMSG_PROCEED:
709 if ((req = req_by_id(imsg.hdr.peerid)) == NULL)
710 break;
711 bufferevent_enable(req->bev, EV_READ);
712 break;
714 case IMSG_STOP:
715 if ((req = req_by_id(imsg.hdr.peerid)) == NULL)
716 break;
717 close_conn(0, 0, req);
718 break;
720 case IMSG_QUIT:
721 event_loopbreak();
722 imsg_free(&imsg);
723 return;
725 default:
726 errx(1, "got unknown imsg %d", imsg.hdr.type);
729 imsg_free(&imsg);
732 imsg_event_add(iev);
735 static int
736 net_send_ui(int type, uint32_t peerid, const void *data,
737 uint16_t datalen)
739 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
740 data, datalen);
743 int
744 net_main(void)
746 setproctitle("net");
748 TAILQ_INIT(&reqhead);
750 event_init();
752 /* Setup pipe and event handler to the main process */
753 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
754 die();
755 imsg_init(&iev_ui->ibuf, 3);
756 iev_ui->handler = handle_dispatch_imsg;
757 iev_ui->events = EV_READ;
758 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
759 iev_ui->handler, iev_ui);
760 event_add(&iev_ui->ev, NULL);
762 sandbox_net_process();
764 event_dispatch();
766 msgbuf_clear(&iev_ui->ibuf.w);
767 close(iev_ui->ibuf.fd);
768 free(iev_ui);
770 return 0;