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;
46 static void die(void) __attribute__((__noreturn__));
48 static void try_to_connect(int, short, void*);
51 static void query_done(struct asr_result*, void*);
52 static void async_conn_towards(struct req*);
54 static void blocking_conn_towards(struct req*);
57 static void close_with_err(struct req*, const char*);
58 static void close_with_errf(struct req*, const char*, ...) __attribute__((format(printf, 2, 3)));
59 static struct req *req_by_id(uint32_t);
60 static struct req *req_by_id_try(uint32_t);
62 static void setup_tls(struct req*);
63 static void do_handshake(int, short, void*);
64 static void write_request(int, short, void*);
65 static void read_reply(int, short, void*);
66 static void parse_reply(struct req*);
67 static void copy_body(int, short, void*);
69 static void handle_get_raw(struct imsg *, size_t);
70 static void handle_cert_status(struct imsg*, size_t);
71 static void handle_proceed(struct imsg*, size_t);
72 static void handle_stop(struct imsg*, size_t);
73 static void handle_quit(struct imsg*, size_t);
74 static void handle_dispatch_imsg(int, short, void*);
76 static int net_send_ui(int, uint32_t, const void *, uint16_t);
78 /* TODO: making this customizable */
79 struct timeval timeout_for_handshake = { 5, 0 };
81 static imsg_handlerfn *handlers[] = {
82 [IMSG_GET_RAW] = handle_get_raw,
83 [IMSG_CERT_STATUS] = handle_cert_status,
84 [IMSG_PROCEED] = handle_proceed,
85 [IMSG_STOP] = handle_stop,
86 [IMSG_QUIT] = handle_quit,
89 typedef void (*statefn)(int, short, void*);
91 TAILQ_HEAD(, req) reqhead;
92 /* a pending request */
102 struct addrinfo *servinfo, *p;
104 struct addrinfo hints;
105 struct event_asr *asrev;
108 TAILQ_ENTRY(req) reqs;
112 yield_r(struct req *req, statefn fn, struct timeval *tv)
114 event_once(req->fd, EV_READ, fn, req, tv);
118 yield_w(struct req *req, statefn fn, struct timeval *tv)
120 event_once(req->fd, EV_WRITE, fn, req, tv);
124 advance_buf(struct req *req, size_t len)
126 assert(len <= req->off);
129 memmove(req->buf, req->buf + len, req->off);
132 static void __attribute__((__noreturn__))
139 try_to_connect(int fd, short ev, void *d)
143 socklen_t len = sizeof(error);
150 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
159 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
161 req->p = req->p->ai_next;
164 mark_nonblock(req->fd);
165 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
167 yield_w(req, try_to_connect, NULL);
172 freeaddrinfo(req->servinfo);
173 close_with_errf(req, "failed to connect to %s",
178 freeaddrinfo(req->servinfo);
184 query_done(struct asr_result *res, void *d)
189 if (res->ar_gai_errno != 0) {
190 close_with_errf(req, "failed to resolve %s: %s",
191 req->url.host, gai_strerror(res->ar_gai_errno));
196 req->servinfo = res->ar_addrinfo;
197 req->p = res->ar_addrinfo;
198 try_to_connect(0, 0, req);
202 async_conn_towards(struct req *req)
205 const char *proto = "1965";
207 if (*req->url.port != '\0')
208 proto = req->url.port;
210 req->hints.ai_family = AF_UNSPEC;
211 req->hints.ai_socktype = SOCK_STREAM;
212 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
213 req->asrev = event_asr_run(q, query_done, req);
217 blocking_conn_towards(struct req *req)
219 struct addrinfo hints;
220 struct phos_uri *url = &req->url;
222 const char *proto = "1965";
224 if (*url->port != '\0')
227 memset(&hints, 0, sizeof(hints));
228 hints.ai_family = AF_UNSPEC;
229 hints.ai_socktype = SOCK_STREAM;
231 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
232 close_with_errf(req, "failed to resolve %s: %s",
233 url->host, gai_strerror(status));
238 req->p = req->servinfo;
239 try_to_connect(0, 0, req);
244 req_by_id(uint32_t id)
248 if ((r = req_by_id_try(id)) == NULL)
254 req_by_id_try(uint32_t id)
258 TAILQ_FOREACH(r, &reqhead, reqs) {
267 close_conn(int fd, short ev, void *d)
272 if (req->asrev != NULL)
273 event_asr_abort(req->asrev);
276 if (req->ctx != NULL) {
277 switch (tls_close(req->ctx)) {
278 case TLS_WANT_POLLIN:
279 yield_r(req, close_conn, NULL);
281 case TLS_WANT_POLLOUT:
282 yield_w(req, close_conn, NULL);
289 TAILQ_REMOVE(&reqhead, req, reqs);
296 close_with_err(struct req *req, const char *err)
298 net_send_ui(IMSG_ERR, req->id, err, strlen(err)+1);
299 close_conn(0, 0, req);
303 close_with_errf(struct req *req, const char *fmt, ...)
309 if (vasprintf(&s, fmt, ap) == -1)
313 close_with_err(req, s);
318 setup_tls(struct req *req)
320 if ((req->ctx = tls_client()) == NULL) {
321 close_with_errf(req, "tls_client: %s", strerror(errno));
324 if (tls_configure(req->ctx, tlsconf) == -1) {
325 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
328 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
329 close_with_errf(req, "tls_connect_socket: %s", tls_error(req->ctx));
332 yield_w(req, do_handshake, &timeout_for_handshake);
336 do_handshake(int fd, short ev, void *d)
341 if (ev == EV_TIMEOUT) {
342 close_with_err(req, "Timeout loading page");
346 switch (tls_handshake(req->ctx)) {
347 case TLS_WANT_POLLIN:
348 yield_r(req, do_handshake, NULL);
350 case TLS_WANT_POLLOUT:
351 yield_w(req, do_handshake, NULL);
355 hash = tls_peer_cert_hash(req->ctx);
357 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
360 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
364 write_request(int fd, short ev, void *d)
370 len = strlen(req->buf);
372 switch (r = tls_write(req->ctx, req->buf, len)) {
374 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
376 case TLS_WANT_POLLIN:
377 yield_r(req, write_request, NULL);
379 case TLS_WANT_POLLOUT:
380 yield_w(req, write_request, NULL);
383 /* assume r == len */
385 yield_r(req, read_reply, NULL);
391 read_reply(int fd, short ev, void *d)
398 buf = req->buf + req->off;
399 len = sizeof(req->buf) - req->off;
401 switch (r = tls_read(req->ctx, buf, len)) {
403 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
405 case TLS_WANT_POLLIN:
406 yield_r(req, read_reply, NULL);
408 case TLS_WANT_POLLOUT:
409 yield_w(req, read_reply, NULL);
414 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
416 else if (req->off == sizeof(req->buf))
417 close_with_err(req, "invalid response");
419 yield_r(req, read_reply, NULL);
425 parse_reply(struct req *req)
434 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
437 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
439 if (!isspace(req->buf[2]))
443 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
449 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
450 net_send_ui(IMSG_GOT_META, req->id, 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 net_send_ui(IMSG_BUF, req->id,
476 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
477 case TLS_WANT_POLLIN:
478 yield_r(req, copy_body, NULL);
480 case TLS_WANT_POLLOUT:
481 yield_w(req, copy_body, NULL);
485 * XXX: should notify the user that the
486 * download was aborted.
490 net_send_ui(IMSG_EOF, req->id, NULL, 0);
491 close_conn(0, 0, req);
500 handle_get_raw(struct imsg *imsg, size_t datalen)
507 if (datalen != sizeof(*r))
510 if ((req = calloc(1, sizeof(*req))) == NULL)
513 req->id = imsg->hdr.peerid;
514 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
516 strlcpy(req->url.host, r->host, sizeof(req->url.host));
517 strlcpy(req->url.port, r->port, sizeof(req->url.port));
518 strlcpy(req->buf, r->req, sizeof(req->buf));
521 async_conn_towards(req);
523 blocking_conn_towards(req);
528 handle_cert_status(struct imsg *imsg, size_t datalen)
533 req = req_by_id(imsg->hdr.peerid);
535 if (datalen < sizeof(is_ok))
537 memcpy(&is_ok, imsg->data, sizeof(is_ok));
540 yield_w(req, write_request, NULL);
542 close_conn(0, 0, req);
546 handle_proceed(struct imsg *imsg, size_t datalen)
548 yield_r(req_by_id(imsg->hdr.peerid),
553 handle_stop(struct imsg *imsg, size_t datalen)
557 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
559 close_conn(0, 0, req);
563 handle_quit(struct imsg *imsg, size_t datalen)
569 handle_dispatch_imsg(int fd, short ev, void *d)
571 struct imsgev *iev = d;
573 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
574 err(1, "connection closed");
578 net_send_ui(int type, uint32_t peerid, const void *data,
581 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
590 TAILQ_INIT(&reqhead);
592 if ((tlsconf = tls_config_new()) == NULL)
594 tls_config_insecure_noverifycert(tlsconf);
595 tls_config_insecure_noverifyname(tlsconf);
599 /* Setup pipe and event handler to the main process */
600 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
602 imsg_init(&iev_ui->ibuf, 3);
603 iev_ui->handler = handle_dispatch_imsg;
604 iev_ui->events = EV_READ;
605 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
606 iev_ui->handler, iev_ui);
607 event_add(&iev_ui->ev, NULL);
609 sandbox_net_process();