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.
22 * to something more asynchronous
25 #include "telescope.h"
27 #include <sys/types.h>
28 #include <sys/socket.h>
30 #include <netinet/in.h>
47 static struct event imsgev;
48 static struct tls_config *tlsconf;
49 static struct imsgbuf *ibuf;
53 static void die(void) __attribute__((__noreturn__));
55 static void try_to_connect(int, short, void*);
58 static void query_done(struct asr_result*, void*);
59 static void async_conn_towards(struct req*);
61 static void blocking_conn_towards(struct req*);
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_raw(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_RAW] = handle_get_raw,
88 [IMSG_CERT_STATUS] = handle_cert_status,
89 [IMSG_PROCEED] = handle_proceed,
90 [IMSG_STOP] = handle_stop,
91 [IMSG_QUIT] = handle_quit,
94 typedef void (*statefn)(int, short, void*);
96 TAILQ_HEAD(, req) reqhead;
97 /* a pending request */
107 struct addrinfo *servinfo, *p;
109 struct addrinfo hints;
110 struct event_asr *asrev;
113 TAILQ_ENTRY(req) reqs;
117 yield_r(struct req *req, statefn fn, struct timeval *tv)
119 event_once(req->fd, EV_READ, fn, req, tv);
123 yield_w(struct req *req, statefn fn, struct timeval *tv)
125 event_once(req->fd, EV_WRITE, fn, req, tv);
129 advance_buf(struct req *req, size_t len)
131 assert(len <= req->off);
134 memmove(req->buf, req->buf + len, req->off);
137 static void __attribute__((__noreturn__))
144 try_to_connect(int fd, short ev, void *d)
148 socklen_t len = sizeof(error);
155 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
164 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
166 req->p = req->p->ai_next;
169 mark_nonblock(req->fd);
170 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
172 yield_w(req, try_to_connect, NULL);
177 freeaddrinfo(req->servinfo);
178 close_with_errf(req, "failed to connect to %s",
183 freeaddrinfo(req->servinfo);
189 query_done(struct asr_result *res, void *d)
194 if (res->ar_gai_errno != 0) {
195 close_with_errf(req, "failed to resolve %s: %s",
196 req->url.host, gai_strerror(res->ar_gai_errno));
201 req->servinfo = res->ar_addrinfo;
202 req->p = res->ar_addrinfo;
203 try_to_connect(0, 0, req);
207 async_conn_towards(struct req *req)
210 const char *proto = "1965";
212 if (*req->url.port != '\0')
213 proto = req->url.port;
215 req->hints.ai_family = AF_UNSPEC;
216 req->hints.ai_socktype = SOCK_STREAM;
217 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
218 req->asrev = event_asr_run(q, query_done, req);
222 blocking_conn_towards(struct req *req)
224 struct addrinfo hints;
225 struct phos_uri *url = &req->url;
227 const char *proto = "1965";
229 if (*url->port != '\0')
232 memset(&hints, 0, sizeof(hints));
233 hints.ai_family = AF_UNSPEC;
234 hints.ai_socktype = SOCK_STREAM;
236 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
237 close_with_errf(req, "failed to resolve %s: %s",
238 url->host, gai_strerror(status));
243 req->p = req->servinfo;
244 try_to_connect(0, 0, req);
249 req_by_id(uint32_t id)
253 if ((r = req_by_id_try(id)) == NULL)
259 req_by_id_try(uint32_t id)
263 TAILQ_FOREACH(r, &reqhead, reqs) {
272 close_conn(int fd, short ev, void *d)
277 if (req->asrev != NULL)
278 event_asr_abort(req->asrev);
281 if (req->ctx != NULL) {
282 switch (tls_close(req->ctx)) {
283 case TLS_WANT_POLLIN:
284 yield_r(req, close_conn, NULL);
286 case TLS_WANT_POLLOUT:
287 yield_w(req, close_conn, NULL);
294 TAILQ_REMOVE(&reqhead, req, reqs);
301 close_with_err(struct req *req, const char *err)
303 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
305 close_conn(0, 0, req);
309 close_with_errf(struct req *req, const char *fmt, ...)
315 if (vasprintf(&s, fmt, ap) == -1)
319 close_with_err(req, s);
324 setup_tls(struct req *req)
326 if ((req->ctx = tls_client()) == NULL) {
327 close_with_errf(req, "tls_client: %s", strerror(errno));
330 if (tls_configure(req->ctx, tlsconf) == -1) {
331 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
334 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
335 close_with_errf(req, "tls_connect_socket: %s", tls_error(req->ctx));
338 yield_w(req, do_handshake, &timeout_for_handshake);
342 do_handshake(int fd, short ev, void *d)
347 if (ev == EV_TIMEOUT) {
348 close_with_err(req, "Timeout loading page");
352 switch (tls_handshake(req->ctx)) {
353 case TLS_WANT_POLLIN:
354 yield_r(req, do_handshake, NULL);
356 case TLS_WANT_POLLOUT:
357 yield_w(req, do_handshake, NULL);
361 hash = tls_peer_cert_hash(req->ctx);
363 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
366 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
371 write_request(int fd, short ev, void *d)
377 len = strlen(req->buf);
379 switch (r = tls_write(req->ctx, req->buf, len)) {
381 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
383 case TLS_WANT_POLLIN:
384 yield_r(req, write_request, NULL);
386 case TLS_WANT_POLLOUT:
387 yield_w(req, write_request, NULL);
390 /* assume r == len */
392 yield_r(req, read_reply, NULL);
398 read_reply(int fd, short ev, void *d)
405 buf = req->buf + req->off;
406 len = sizeof(req->buf) - req->off;
408 switch (r = tls_read(req->ctx, buf, len)) {
410 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
412 case TLS_WANT_POLLIN:
413 yield_r(req, read_reply, NULL);
415 case TLS_WANT_POLLOUT:
416 yield_w(req, read_reply, NULL);
421 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
423 else if (req->off == sizeof(req->buf))
424 close_with_err(req, "invalid response");
426 yield_r(req, read_reply, NULL);
432 parse_reply(struct req *req)
441 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
444 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
446 if (!isspace(req->buf[2]))
450 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
456 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
457 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1, req->buf, len);
460 if (20 <= code && code < 30)
461 advance_buf(req, len+1); /* skip \n too */
463 close_conn(0, 0, req);
468 close_with_err(req, "malformed request");
472 copy_body(int fd, short ev, void *d)
479 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
485 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
486 case TLS_WANT_POLLIN:
487 yield_r(req, copy_body, NULL);
489 case TLS_WANT_POLLOUT:
490 yield_w(req, copy_body, NULL);
493 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
495 close_conn(0, 0, req);
504 handle_get_raw(struct imsg *imsg, size_t datalen)
511 if (datalen != sizeof(*r))
514 if ((req = calloc(1, sizeof(*req))) == NULL)
517 req->id = imsg->hdr.peerid;
518 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
520 strlcpy(req->url.host, r->host, sizeof(req->url.host));
521 strlcpy(req->url.port, r->port, sizeof(req->url.port));
522 strlcpy(req->buf, r->req, sizeof(req->buf));
525 async_conn_towards(req);
527 blocking_conn_towards(req);
532 handle_cert_status(struct imsg *imsg, size_t datalen)
537 req = req_by_id(imsg->hdr.peerid);
539 if (datalen < sizeof(is_ok))
541 memcpy(&is_ok, imsg->data, sizeof(is_ok));
544 yield_w(req, write_request, NULL);
546 close_conn(0, 0, req);
550 handle_proceed(struct imsg *imsg, size_t datalen)
552 yield_r(req_by_id(imsg->hdr.peerid),
557 handle_stop(struct imsg *imsg, size_t datalen)
561 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
563 close_conn(0, 0, req);
567 handle_quit(struct imsg *imsg, size_t datalen)
573 handle_dispatch_imsg(int fd, short ev, void *d)
575 struct imsgbuf *ibuf = d;
576 dispatch_imsg(ibuf, handlers, sizeof(handlers));
580 client_main(struct imsgbuf *b)
584 TAILQ_INIT(&reqhead);
586 if ((tlsconf = tls_config_new()) == NULL)
588 tls_config_insecure_noverifycert(tlsconf);
589 tls_config_insecure_noverifyname(tlsconf);
593 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
594 event_add(&imsgev, NULL);
596 sandbox_network_process();