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.
17 #include "telescope.h"
19 #include <sys/types.h>
20 #include <sys/socket.h>
22 #include <netinet/in.h>
39 static struct event imsgev;
40 static struct tls_config *tlsconf;
41 static struct imsgbuf *ibuf;
45 static void die(void) __attribute__((__noreturn__));
47 static void try_to_connect(int, short, void*);
50 static void query_done(struct asr_result*, void*);
51 static void async_conn_towards(struct req*);
53 static void blocking_conn_towards(struct req*);
56 static void close_with_err(struct req*, const char*);
57 static void close_with_errf(struct req*, const char*, ...) __attribute__((format(printf, 2, 3)));
58 static struct req *req_by_id(uint32_t);
59 static struct req *req_by_id_try(uint32_t);
61 static void setup_tls(struct req*);
62 static void do_handshake(int, short, void*);
63 static void write_request(int, short, void*);
64 static void read_reply(int, short, void*);
65 static void parse_reply(struct req*);
66 static void copy_body(int, short, void*);
68 static void handle_get_raw(struct imsg *, size_t);
69 static void handle_cert_status(struct imsg*, size_t);
70 static void handle_proceed(struct imsg*, size_t);
71 static void handle_stop(struct imsg*, size_t);
72 static void handle_quit(struct imsg*, size_t);
73 static void handle_dispatch_imsg(int, short, void*);
75 /* TODO: making this customizable */
76 struct timeval timeout_for_handshake = { 5, 0 };
78 static imsg_handlerfn *handlers[] = {
79 [IMSG_GET_RAW] = handle_get_raw,
80 [IMSG_CERT_STATUS] = handle_cert_status,
81 [IMSG_PROCEED] = handle_proceed,
82 [IMSG_STOP] = handle_stop,
83 [IMSG_QUIT] = handle_quit,
86 typedef void (*statefn)(int, short, void*);
88 TAILQ_HEAD(, req) reqhead;
89 /* a pending request */
99 struct addrinfo *servinfo, *p;
101 struct addrinfo hints;
102 struct event_asr *asrev;
105 TAILQ_ENTRY(req) reqs;
109 yield_r(struct req *req, statefn fn, struct timeval *tv)
111 event_once(req->fd, EV_READ, fn, req, tv);
115 yield_w(struct req *req, statefn fn, struct timeval *tv)
117 event_once(req->fd, EV_WRITE, fn, req, tv);
121 advance_buf(struct req *req, size_t len)
123 assert(len <= req->off);
126 memmove(req->buf, req->buf + len, req->off);
129 static void __attribute__((__noreturn__))
136 try_to_connect(int fd, short ev, void *d)
140 socklen_t len = sizeof(error);
147 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
156 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
158 req->p = req->p->ai_next;
161 mark_nonblock(req->fd);
162 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
164 yield_w(req, try_to_connect, NULL);
169 freeaddrinfo(req->servinfo);
170 close_with_errf(req, "failed to connect to %s",
175 freeaddrinfo(req->servinfo);
181 query_done(struct asr_result *res, void *d)
186 if (res->ar_gai_errno != 0) {
187 close_with_errf(req, "failed to resolve %s: %s",
188 req->url.host, gai_strerror(res->ar_gai_errno));
193 req->servinfo = res->ar_addrinfo;
194 req->p = res->ar_addrinfo;
195 try_to_connect(0, 0, req);
199 async_conn_towards(struct req *req)
202 const char *proto = "1965";
204 if (*req->url.port != '\0')
205 proto = req->url.port;
207 req->hints.ai_family = AF_UNSPEC;
208 req->hints.ai_socktype = SOCK_STREAM;
209 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
210 req->asrev = event_asr_run(q, query_done, req);
214 blocking_conn_towards(struct req *req)
216 struct addrinfo hints;
217 struct phos_uri *url = &req->url;
219 const char *proto = "1965";
221 if (*url->port != '\0')
224 memset(&hints, 0, sizeof(hints));
225 hints.ai_family = AF_UNSPEC;
226 hints.ai_socktype = SOCK_STREAM;
228 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
229 close_with_errf(req, "failed to resolve %s: %s",
230 url->host, gai_strerror(status));
235 req->p = req->servinfo;
236 try_to_connect(0, 0, req);
241 req_by_id(uint32_t id)
245 if ((r = req_by_id_try(id)) == NULL)
251 req_by_id_try(uint32_t id)
255 TAILQ_FOREACH(r, &reqhead, reqs) {
264 close_conn(int fd, short ev, void *d)
269 if (req->asrev != NULL)
270 event_asr_abort(req->asrev);
273 if (req->ctx != NULL) {
274 switch (tls_close(req->ctx)) {
275 case TLS_WANT_POLLIN:
276 yield_r(req, close_conn, NULL);
278 case TLS_WANT_POLLOUT:
279 yield_w(req, close_conn, NULL);
286 TAILQ_REMOVE(&reqhead, req, reqs);
293 close_with_err(struct req *req, const char *err)
295 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
297 close_conn(0, 0, req);
301 close_with_errf(struct req *req, const char *fmt, ...)
307 if (vasprintf(&s, fmt, ap) == -1)
311 close_with_err(req, s);
316 setup_tls(struct req *req)
318 if ((req->ctx = tls_client()) == NULL) {
319 close_with_errf(req, "tls_client: %s", strerror(errno));
322 if (tls_configure(req->ctx, tlsconf) == -1) {
323 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
326 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
327 close_with_errf(req, "tls_connect_socket: %s", tls_error(req->ctx));
330 yield_w(req, do_handshake, &timeout_for_handshake);
334 do_handshake(int fd, short ev, void *d)
339 if (ev == EV_TIMEOUT) {
340 close_with_err(req, "Timeout loading page");
344 switch (tls_handshake(req->ctx)) {
345 case TLS_WANT_POLLIN:
346 yield_r(req, do_handshake, NULL);
348 case TLS_WANT_POLLOUT:
349 yield_w(req, do_handshake, NULL);
353 hash = tls_peer_cert_hash(req->ctx);
355 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
358 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
363 write_request(int fd, short ev, void *d)
369 len = strlen(req->buf);
371 switch (r = tls_write(req->ctx, req->buf, len)) {
373 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
375 case TLS_WANT_POLLIN:
376 yield_r(req, write_request, NULL);
378 case TLS_WANT_POLLOUT:
379 yield_w(req, write_request, NULL);
382 /* assume r == len */
384 yield_r(req, read_reply, NULL);
390 read_reply(int fd, short ev, void *d)
397 buf = req->buf + req->off;
398 len = sizeof(req->buf) - req->off;
400 switch (r = tls_read(req->ctx, buf, len)) {
402 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
404 case TLS_WANT_POLLIN:
405 yield_r(req, read_reply, NULL);
407 case TLS_WANT_POLLOUT:
408 yield_w(req, read_reply, NULL);
413 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
415 else if (req->off == sizeof(req->buf))
416 close_with_err(req, "invalid response");
418 yield_r(req, read_reply, NULL);
424 parse_reply(struct req *req)
433 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
436 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
438 if (!isspace(req->buf[2]))
442 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
448 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
449 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1, req->buf, len);
452 if (20 <= code && code < 30)
453 advance_buf(req, len+1); /* skip \n too */
455 close_conn(0, 0, req);
460 close_with_err(req, "malformed request");
464 copy_body(int fd, short ev, void *d)
471 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
477 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
478 case TLS_WANT_POLLIN:
479 yield_r(req, copy_body, NULL);
481 case TLS_WANT_POLLOUT:
482 yield_w(req, copy_body, NULL);
485 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
487 close_conn(0, 0, req);
496 handle_get_raw(struct imsg *imsg, size_t datalen)
503 if (datalen != sizeof(*r))
506 if ((req = calloc(1, sizeof(*req))) == NULL)
509 req->id = imsg->hdr.peerid;
510 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
512 strlcpy(req->url.host, r->host, sizeof(req->url.host));
513 strlcpy(req->url.port, r->port, sizeof(req->url.port));
514 strlcpy(req->buf, r->req, sizeof(req->buf));
517 async_conn_towards(req);
519 blocking_conn_towards(req);
524 handle_cert_status(struct imsg *imsg, size_t datalen)
529 req = req_by_id(imsg->hdr.peerid);
531 if (datalen < sizeof(is_ok))
533 memcpy(&is_ok, imsg->data, sizeof(is_ok));
536 yield_w(req, write_request, NULL);
538 close_conn(0, 0, req);
542 handle_proceed(struct imsg *imsg, size_t datalen)
544 yield_r(req_by_id(imsg->hdr.peerid),
549 handle_stop(struct imsg *imsg, size_t datalen)
553 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
555 close_conn(0, 0, req);
559 handle_quit(struct imsg *imsg, size_t datalen)
565 handle_dispatch_imsg(int fd, short ev, void *d)
567 struct imsgbuf *ibuf = d;
568 dispatch_imsg(ibuf, handlers, sizeof(handlers));
576 TAILQ_INIT(&reqhead);
578 if ((tlsconf = tls_config_new()) == NULL)
580 tls_config_insecure_noverifycert(tlsconf);
581 tls_config_insecure_noverifyname(tlsconf);
585 /* Setup pipe and event handler to the main process */
586 if ((ibuf = calloc(1, sizeof(*ibuf))) == NULL)
589 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
590 event_add(&imsgev, NULL);
592 sandbox_network_process();