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 /*
18 * TODO:
19 * - move the various
20 * imsg_compose(...);
21 * imsg_flush(...);
22 * to something more asynchronous
23 */
25 #include <telescope.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
30 #include <netinet/in.h>
32 #include <assert.h>
33 #include <ctype.h>
34 #include <errno.h>
35 #include <netdb.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <tls.h>
41 #include <unistd.h>
43 #if HAVE_ASR_RUN
44 # include <asr.h>
45 #endif
47 static struct event imsgev;
48 static struct tls_config *tlsconf;
49 static struct imsgbuf *ibuf;
51 struct req;
53 static void die(void) __attribute__((__noreturn__));
55 #if HAVE_ASR_RUN
56 static void try_to_connect(int, short, void*);
57 static void query_done(struct asr_result*, void*);
58 static void async_conn_towards(struct req*);
59 #else
60 static char *xasprintf(const char*, ...);
61 static int blocking_conn_towards(struct url*, char**);
62 #endif
64 static void close_with_err(struct req*, const char*);
65 static void close_with_errf(struct req*, const char*, ...) __attribute__((format(printf, 2, 3)));
66 static struct req *req_by_id(uint32_t);
67 static struct req *req_by_id_try(uint32_t);
69 static void setup_tls(struct req*);
70 static void do_handshake(int, short, void*);
71 static void write_request(int, short, void*);
72 static void read_reply(int, short, void*);
73 static void parse_reply(struct req*);
74 static void copy_body(int, short, void*);
76 static void handle_get(struct imsg*, size_t);
77 static void handle_cert_status(struct imsg*, size_t);
78 static void handle_proceed(struct imsg*, size_t);
79 static void handle_stop(struct imsg*, size_t);
80 static void handle_quit(struct imsg*, size_t);
81 static void handle_dispatch_imsg(int, short, void*);
83 /* TODO: making this customizable */
84 struct timeval timeout_for_handshake = { 5, 0 };
86 static imsg_handlerfn *handlers[] = {
87 [IMSG_GET] = handle_get,
88 [IMSG_CERT_STATUS] = handle_cert_status,
89 [IMSG_PROCEED] = handle_proceed,
90 [IMSG_STOP] = handle_stop,
91 [IMSG_QUIT] = handle_quit,
92 };
94 typedef void (*statefn)(int, short, void*);
96 TAILQ_HEAD(, req) reqhead;
97 /* a pending request */
98 struct req {
99 struct event ev;
100 struct url url;
101 uint32_t id;
102 int fd;
103 struct tls *ctx;
104 char buf[1024];
105 size_t off;
107 #if HAVE_ASR_RUN
108 struct addrinfo hints, *servinfo, *p;
109 struct event_asr *asrev;
110 #endif
112 TAILQ_ENTRY(req) reqs;
113 };
115 static inline void
116 yield_r(struct req *req, statefn fn, struct timeval *tv)
118 event_once(req->fd, EV_READ, fn, req, tv);
121 static inline void
122 yield_w(struct req *req, statefn fn, struct timeval *tv)
124 event_once(req->fd, EV_WRITE, fn, req, tv);
127 static inline void
128 advance_buf(struct req *req, size_t len)
130 assert(len <= req->off);
132 req->off -= len;
133 memmove(req->buf, req->buf + len, req->off);
136 static void __attribute__((__noreturn__))
137 die(void)
139 abort(); /* TODO */
142 #if HAVE_ASR_RUN
143 static void
144 try_to_connect(int fd, short ev, void *d)
146 struct req *req = d;
147 int error = 0;
148 socklen_t len = sizeof(error);
150 if (req->p == NULL)
151 goto err;
153 if (req->fd != -1) {
154 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
155 goto err;
156 if (error != 0) {
157 errno = error;
158 goto err;
160 goto done;
163 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
164 if (req->fd == -1)
165 req->p = req->p->ai_next;
166 else {
167 mark_nonblock(req->fd);
168 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
169 goto done;
171 try_to_connect(fd, ev, req);
172 return;
174 err:
175 freeaddrinfo(req->servinfo);
176 close_with_errf(req, "failed to connect to %s",
177 req->url.host);
178 return;
180 done:
181 freeaddrinfo(req->servinfo);
182 setup_tls(req);
185 static void
186 query_done(struct asr_result *res, void *d)
188 struct req *req = d;
190 req->asrev = NULL;
191 if (res->ar_gai_errno != 0) {
192 close_with_errf(req, "failed to resolve %s: %s",
193 req->url.host, gai_strerror(res->ar_gai_errno));
194 return;
197 req->fd = -1;
198 req->servinfo = res->ar_addrinfo;
199 req->p = res->ar_addrinfo;
200 try_to_connect(0, 0, req);
203 static void
204 async_conn_towards(struct req *req)
206 struct asr_query *q;
207 const char *proto = "1965";
209 if (*req->url.port != '\0')
210 proto = req->url.port;
212 req->hints.ai_family = AF_UNSPEC;
213 req->hints.ai_socktype = SOCK_STREAM;
214 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
215 req->asrev = event_asr_run(q, query_done, req);
217 #else
218 static char *
219 xasprintf(const char *fmt, ...)
221 va_list ap;
222 char *s;
224 va_start(ap, fmt);
225 if (vasprintf(&s, fmt, ap) == -1)
226 s = NULL;
227 va_end(ap);
229 return s;
232 static int
233 blocking_conn_towards(struct url *url, char **err)
235 struct addrinfo hints, *servinfo, *p;
236 int status, sock;
237 const char *proto = "1965";
239 *err = NULL;
241 if (*url->port != '\0')
242 proto = url->port;
244 memset(&hints, 0, sizeof(hints));
245 hints.ai_family = AF_UNSPEC;
246 hints.ai_socktype = SOCK_STREAM;
248 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
249 *err = xasprintf("failed to resolve %s: %s",
250 url->host, gai_strerror(status));
251 return -1;
254 sock = -1;
255 for (p = servinfo; p != NULL; p = p->ai_next) {
256 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
257 continue;
258 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
259 break;
260 close(sock);
263 if (sock == -1)
264 *err = xasprintf("couldn't connect to %s", url->host);
265 else
266 mark_nonblock(sock);
268 freeaddrinfo(servinfo);
269 return sock;
271 #endif
273 static struct req *
274 req_by_id(uint32_t id)
276 struct req *r;
278 if ((r = req_by_id_try(id)) == NULL)
279 die();
280 return r;
283 static struct req *
284 req_by_id_try(uint32_t id)
286 struct req *r;
288 TAILQ_FOREACH(r, &reqhead, reqs) {
289 if (r->id == id)
290 return r;
293 return NULL;
296 static void
297 close_conn(int fd, short ev, void *d)
299 struct req *req = d;
301 #if HAVE_ASR_RUN
302 if (req->asrev != NULL)
303 event_asr_abort(req->asrev);
304 #endif
306 if (req->ctx != NULL) {
307 switch (tls_close(req->ctx)) {
308 case TLS_WANT_POLLIN:
309 yield_r(req, close_conn, NULL);
310 return;
311 case TLS_WANT_POLLOUT:
312 yield_w(req, close_conn, NULL);
313 return;
316 tls_free(req->ctx);
319 TAILQ_REMOVE(&reqhead, req, reqs);
320 if (req->fd != -1)
321 close(req->fd);
322 free(req);
325 static void
326 close_with_err(struct req *req, const char *err)
328 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
329 imsg_flush(ibuf);
330 close_conn(0, 0, req);
333 static void
334 close_with_errf(struct req *req, const char *fmt, ...)
336 va_list ap;
337 char *s;
339 va_start(ap, fmt);
340 if (vasprintf(&s, fmt, ap) == -1)
341 abort();
342 va_end(ap);
344 close_with_err(req, s);
345 free(s);
348 static void
349 setup_tls(struct req *req)
351 if ((req->ctx = tls_client()) == NULL) {
352 close_with_errf(req, "tls_client: %s", strerror(errno));
353 return;
355 if (tls_configure(req->ctx, tlsconf) == -1) {
356 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
357 return;
359 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
360 close_with_errf(req, "tls_connect_socket: %s", tls_error(req->ctx));
361 return;
363 yield_w(req, do_handshake, &timeout_for_handshake);
366 static void
367 do_handshake(int fd, short ev, void *d)
369 struct req *req = d;
370 const char *hash;
372 if (ev == EV_TIMEOUT) {
373 close_with_err(req, "Timeout loading page");
374 return;
377 switch (tls_handshake(req->ctx)) {
378 case TLS_WANT_POLLIN:
379 yield_r(req, do_handshake, NULL);
380 return;
381 case TLS_WANT_POLLOUT:
382 yield_w(req, do_handshake, NULL);
383 return;
386 hash = tls_peer_cert_hash(req->ctx);
387 if (hash == NULL) {
388 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
389 return;
391 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
392 imsg_flush(ibuf);
395 static void
396 write_request(int fd, short ev, void *d)
398 struct req *req = d;
399 ssize_t r;
400 size_t len;
401 char buf[1024];
403 strlcpy(buf, "gemini://", sizeof(buf));
404 strlcat(buf, req->url.host, sizeof(buf));
405 strlcat(buf, "/", sizeof(buf));
406 strlcat(buf, req->url.path, sizeof(buf));
408 if (req->url.query[0] != '\0') {
409 strlcat(buf, "?", sizeof(buf));
410 strlcat(buf, req->url.query, sizeof(buf));
413 len = strlcat(buf, "\r\n", sizeof(buf));
415 assert(len <= sizeof(buf));
417 switch (r = tls_write(req->ctx, buf, len)) {
418 case -1:
419 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
420 break;
421 case TLS_WANT_POLLIN:
422 yield_r(req, write_request, NULL);
423 break;
424 case TLS_WANT_POLLOUT:
425 yield_w(req, write_request, NULL);
426 break;
427 default:
428 /* assume r == len */
429 (void)r;
430 yield_r(req, read_reply, NULL);
431 break;
435 static void
436 read_reply(int fd, short ev, void *d)
438 struct req *req = d;
439 size_t len;
440 ssize_t r;
441 char *buf;
443 buf = req->buf + req->off;
444 len = sizeof(req->buf) - req->off;
446 switch (r = tls_read(req->ctx, buf, len)) {
447 case -1:
448 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
449 break;
450 case TLS_WANT_POLLIN:
451 yield_r(req, read_reply, NULL);
452 break;
453 case TLS_WANT_POLLOUT:
454 yield_w(req, read_reply, NULL);
455 break;
456 default:
457 req->off += r;
459 /* TODO: really watch for \r\n not \n alone */
460 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
461 parse_reply(req);
462 else if (req->off == sizeof(req->buf))
463 close_with_err(req, "invalid response");
464 else
465 yield_r(req, read_reply, NULL);
466 break;
470 static void
471 parse_reply(struct req *req)
473 int code;
474 char *e;
475 size_t len;
477 if (req->off < 4)
478 goto err;
480 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
481 goto err;
483 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
485 if (!isspace(req->buf[2]))
486 goto err;
488 advance_buf(req, 3);
489 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
490 goto err;
492 *e = '\0';
493 e++;
494 len = e - req->buf;
495 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
496 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
497 req->buf, len);
498 imsg_flush(ibuf);
500 if (code != 20)
501 close_conn(0, 0, req);
502 advance_buf(req, len+1); /* skip \n too */
504 return;
506 err:
507 close_with_err(req, "malformed request");
510 static void
511 copy_body(int fd, short ev, void *d)
513 struct req *req = d;
514 ssize_t r;
516 for (;;) {
517 if (req->off != 0) {
518 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
519 req->buf, req->off);
520 imsg_flush(ibuf);
521 req->off = 0;
524 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
525 case TLS_WANT_POLLIN:
526 yield_r(req, copy_body, NULL);
527 return;
528 case TLS_WANT_POLLOUT:
529 yield_w(req, copy_body, NULL);
530 return;
531 case 0:
532 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
533 imsg_flush(ibuf);
534 close_conn(0, 0, req);
535 return;
536 default:
537 req->off = r;
542 static void
543 handle_get(struct imsg *imsg, size_t datalen)
545 struct req *req;
546 const char *e;
547 char *data;
549 data = imsg->data;
551 if (data[datalen-1] != '\0')
552 die();
554 if ((req = calloc(1, sizeof(*req))) == NULL)
555 die();
557 req->id = imsg->hdr.peerid;
558 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
560 if (!url_parse(imsg->data, &req->url, &e)) {
561 close_with_err(req, e);
562 return;
565 #if HAVE_ASR_RUN
566 async_conn_towards(req);
567 #else
569 char *e = NULL;
571 if ((req->fd = blocking_conn_towards(&req->url, &err)) == -1) {
572 close_with_err(req, err);
573 free(err);
575 setup_tls(req);
577 #endif
580 static void
581 handle_cert_status(struct imsg *imsg, size_t datalen)
583 struct req *req;
584 int is_ok;
586 req = req_by_id(imsg->hdr.peerid);
588 if (datalen < sizeof(is_ok))
589 die();
590 memcpy(&is_ok, imsg->data, sizeof(is_ok));
592 if (is_ok)
593 yield_w(req, write_request, NULL);
594 else
595 close_conn(0, 0, req);
598 static void
599 handle_proceed(struct imsg *imsg, size_t datalen)
601 yield_r(req_by_id(imsg->hdr.peerid),
602 copy_body, NULL);
605 static void
606 handle_stop(struct imsg *imsg, size_t datalen)
608 struct req *req;
610 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
611 return;
612 close_conn(0, 0, req);
615 static void
616 handle_quit(struct imsg *imsg, size_t datalen)
618 event_loopbreak();
621 static void
622 handle_dispatch_imsg(int fd, short ev, void *d)
624 struct imsgbuf *ibuf = d;
625 dispatch_imsg(ibuf, handlers, sizeof(handlers));
628 int
629 client_main(struct imsgbuf *b)
631 ibuf = b;
633 TAILQ_INIT(&reqhead);
635 if ((tlsconf = tls_config_new()) == NULL)
636 die();
637 tls_config_insecure_noverifycert(tlsconf);
639 event_init();
641 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
642 event_add(&imsgev, NULL);
644 sandbox_network_process();
646 event_dispatch();
647 return 0;