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 "telescope.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 static struct imsgev *iev_ui;
40 static struct tls_config *tlsconf;
42 struct req;
44 static void die(void) __attribute__((__noreturn__));
46 static void try_to_connect(int, short, void*);
48 #if HAVE_ASR_RUN
49 static void query_done(struct asr_result*, void*);
50 static void async_conn_towards(struct req*);
51 #else
52 static void blocking_conn_towards(struct req*);
53 #endif
55 static void close_with_err(struct req*, const char*);
56 static void close_with_errf(struct req*, const char*, ...) __attribute__((format(printf, 2, 3)));
57 static struct req *req_by_id(uint32_t);
58 static struct req *req_by_id_try(uint32_t);
60 static void setup_tls(struct req*);
61 static void do_handshake(int, short, void*);
62 static void write_request(int, short, void*);
63 static void read_reply(int, short, void*);
64 static void parse_reply(struct req*);
65 static void copy_body(int, short, void*);
67 static void handle_get_raw(struct imsg *, size_t);
68 static void handle_cert_status(struct imsg*, size_t);
69 static void handle_proceed(struct imsg*, size_t);
70 static void handle_stop(struct imsg*, size_t);
71 static void handle_quit(struct imsg*, size_t);
72 static void handle_dispatch_imsg(int, short, void*);
74 static int net_send_ui(int, uint32_t, const void *, uint16_t);
76 /* TODO: making this customizable */
77 struct timeval timeout_for_handshake = { 5, 0 };
79 static imsg_handlerfn *handlers[] = {
80 [IMSG_GET_RAW] = handle_get_raw,
81 [IMSG_CERT_STATUS] = handle_cert_status,
82 [IMSG_PROCEED] = handle_proceed,
83 [IMSG_STOP] = handle_stop,
84 [IMSG_QUIT] = handle_quit,
85 };
87 typedef void (*statefn)(int, short, void*);
89 TAILQ_HEAD(, req) reqhead;
90 /* a pending request */
91 struct req {
92 struct event ev;
93 struct phos_uri url;
94 uint32_t id;
95 int fd;
96 struct tls *ctx;
97 char buf[1024];
98 size_t off;
100 struct addrinfo *servinfo, *p;
101 #if HAVE_ASR_RUN
102 struct addrinfo hints;
103 struct event_asr *asrev;
104 #endif
106 TAILQ_ENTRY(req) reqs;
107 };
109 static inline void
110 yield_r(struct req *req, statefn fn, struct timeval *tv)
112 event_once(req->fd, EV_READ, fn, req, tv);
115 static inline void
116 yield_w(struct req *req, statefn fn, struct timeval *tv)
118 event_once(req->fd, EV_WRITE, fn, req, tv);
121 static inline void
122 advance_buf(struct req *req, size_t len)
124 assert(len <= req->off);
126 req->off -= len;
127 memmove(req->buf, req->buf + len, req->off);
130 static void __attribute__((__noreturn__))
131 die(void)
133 abort(); /* TODO */
136 static void
137 try_to_connect(int fd, short ev, void *d)
139 struct req *req = d;
140 int error = 0;
141 socklen_t len = sizeof(error);
143 again:
144 if (req->p == NULL)
145 goto err;
147 if (req->fd != -1) {
148 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
149 goto err;
150 if (error != 0) {
151 errno = error;
152 goto err;
154 goto done;
157 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
158 if (req->fd == -1) {
159 req->p = req->p->ai_next;
160 goto again;
161 } else {
162 mark_nonblock(req->fd);
163 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
164 goto done;
165 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);
177 setup_tls(req);
180 #if HAVE_ASR_RUN
181 static void
182 query_done(struct asr_result *res, void *d)
184 struct req *req = d;
186 req->asrev = NULL;
187 if (res->ar_gai_errno != 0) {
188 close_with_errf(req, "failed to resolve %s: %s",
189 req->url.host, gai_strerror(res->ar_gai_errno));
190 return;
193 req->fd = -1;
194 req->servinfo = res->ar_addrinfo;
195 req->p = res->ar_addrinfo;
196 try_to_connect(0, 0, req);
199 static void
200 async_conn_towards(struct req *req)
202 struct asr_query *q;
203 const char *proto = "1965";
205 if (*req->url.port != '\0')
206 proto = req->url.port;
208 req->hints.ai_family = AF_UNSPEC;
209 req->hints.ai_socktype = SOCK_STREAM;
210 q = getaddrinfo_async(req->url.host, proto, &req->hints, NULL);
211 req->asrev = event_asr_run(q, query_done, req);
213 #else
214 static void
215 blocking_conn_towards(struct req *req)
217 struct addrinfo hints;
218 struct phos_uri *url = &req->url;
219 int status;
220 const char *proto = "1965";
222 if (*url->port != '\0')
223 proto = url->port;
225 memset(&hints, 0, sizeof(hints));
226 hints.ai_family = AF_UNSPEC;
227 hints.ai_socktype = SOCK_STREAM;
229 if ((status = getaddrinfo(url->host, proto, &hints, &req->servinfo))) {
230 close_with_errf(req, "failed to resolve %s: %s",
231 url->host, gai_strerror(status));
232 return;
235 req->fd = -1;
236 req->p = req->servinfo;
237 try_to_connect(0, 0, req);
239 #endif
241 static struct req *
242 req_by_id(uint32_t id)
244 struct req *r;
246 if ((r = req_by_id_try(id)) == NULL)
247 die();
248 return r;
251 static struct req *
252 req_by_id_try(uint32_t id)
254 struct req *r;
256 TAILQ_FOREACH(r, &reqhead, reqs) {
257 if (r->id == id)
258 return r;
261 return NULL;
264 static void
265 close_conn(int fd, short ev, void *d)
267 struct req *req = d;
269 #if HAVE_ASR_RUN
270 if (req->asrev != NULL)
271 event_asr_abort(req->asrev);
272 #endif
274 if (req->ctx != NULL) {
275 switch (tls_close(req->ctx)) {
276 case TLS_WANT_POLLIN:
277 yield_r(req, close_conn, NULL);
278 return;
279 case TLS_WANT_POLLOUT:
280 yield_w(req, close_conn, NULL);
281 return;
284 tls_free(req->ctx);
287 TAILQ_REMOVE(&reqhead, req, reqs);
288 if (req->fd != -1)
289 close(req->fd);
290 free(req);
293 static void
294 close_with_err(struct req *req, const char *err)
296 net_send_ui(IMSG_ERR, req->id, err, strlen(err)+1);
297 close_conn(0, 0, req);
300 static void
301 close_with_errf(struct req *req, const char *fmt, ...)
303 va_list ap;
304 char *s;
306 va_start(ap, fmt);
307 if (vasprintf(&s, fmt, ap) == -1)
308 abort();
309 va_end(ap);
311 close_with_err(req, s);
312 free(s);
315 static void
316 setup_tls(struct req *req)
318 if ((req->ctx = tls_client()) == NULL) {
319 close_with_errf(req, "tls_client: %s", strerror(errno));
320 return;
322 if (tls_configure(req->ctx, tlsconf) == -1) {
323 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
324 return;
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));
328 return;
330 yield_w(req, do_handshake, &timeout_for_handshake);
333 static void
334 do_handshake(int fd, short ev, void *d)
336 struct req *req = d;
337 const char *hash;
339 if (ev == EV_TIMEOUT) {
340 close_with_err(req, "Timeout loading page");
341 return;
344 switch (tls_handshake(req->ctx)) {
345 case TLS_WANT_POLLIN:
346 yield_r(req, do_handshake, NULL);
347 return;
348 case TLS_WANT_POLLOUT:
349 yield_w(req, do_handshake, NULL);
350 return;
353 hash = tls_peer_cert_hash(req->ctx);
354 if (hash == NULL) {
355 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
356 return;
358 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
361 static void
362 write_request(int fd, short ev, void *d)
364 struct req *req = d;
365 ssize_t r;
366 size_t len;
368 len = strlen(req->buf);
370 switch (r = tls_write(req->ctx, req->buf, len)) {
371 case -1:
372 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
373 break;
374 case TLS_WANT_POLLIN:
375 yield_r(req, write_request, NULL);
376 break;
377 case TLS_WANT_POLLOUT:
378 yield_w(req, write_request, NULL);
379 break;
380 default:
381 /* assume r == len */
382 (void)r;
383 yield_r(req, read_reply, NULL);
384 break;
388 static void
389 read_reply(int fd, short ev, void *d)
391 struct req *req = d;
392 size_t len;
393 ssize_t r;
394 char *buf;
396 buf = req->buf + req->off;
397 len = sizeof(req->buf) - req->off;
399 switch (r = tls_read(req->ctx, buf, len)) {
400 case -1:
401 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
402 break;
403 case TLS_WANT_POLLIN:
404 yield_r(req, read_reply, NULL);
405 break;
406 case TLS_WANT_POLLOUT:
407 yield_w(req, read_reply, NULL);
408 break;
409 default:
410 req->off += r;
412 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
413 parse_reply(req);
414 else if (req->off == sizeof(req->buf))
415 close_with_err(req, "invalid response");
416 else
417 yield_r(req, read_reply, NULL);
418 break;
422 static void
423 parse_reply(struct req *req)
425 int code;
426 char *e;
427 size_t len;
429 if (req->off < 4)
430 goto err;
432 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
433 goto err;
435 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
437 if (!isspace(req->buf[2]))
438 goto err;
440 advance_buf(req, 3);
441 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
442 goto err;
444 *e = '\0';
445 e++;
446 len = e - req->buf;
447 net_send_ui(IMSG_GOT_CODE, req->id, &code, sizeof(code));
448 net_send_ui(IMSG_GOT_META, req->id, req->buf, len);
450 if (20 <= code && code < 30)
451 advance_buf(req, len+1); /* skip \n too */
452 else
453 close_conn(0, 0, req);
455 return;
457 err:
458 close_with_err(req, "malformed request");
461 static void
462 copy_body(int fd, short ev, void *d)
464 struct req *req = d;
465 ssize_t r;
467 for (;;) {
468 if (req->off != 0) {
469 net_send_ui(IMSG_BUF, req->id,
470 req->buf, req->off);
471 req->off = 0;
474 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
475 case TLS_WANT_POLLIN:
476 yield_r(req, copy_body, NULL);
477 return;
478 case TLS_WANT_POLLOUT:
479 yield_w(req, copy_body, NULL);
480 return;
481 case 0:
482 net_send_ui(IMSG_EOF, req->id, NULL, 0);
483 close_conn(0, 0, req);
484 return;
485 default:
486 req->off = r;
491 static void
492 handle_get_raw(struct imsg *imsg, size_t datalen)
494 struct req *req;
495 struct get_req *r;
497 r = imsg->data;
499 if (datalen != sizeof(*r))
500 die();
502 if ((req = calloc(1, sizeof(*req))) == NULL)
503 die();
505 req->id = imsg->hdr.peerid;
506 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
508 strlcpy(req->url.host, r->host, sizeof(req->url.host));
509 strlcpy(req->url.port, r->port, sizeof(req->url.port));
510 strlcpy(req->buf, r->req, sizeof(req->buf));
512 #if HAVE_ASR_RUN
513 async_conn_towards(req);
514 #else
515 blocking_conn_towards(req);
516 #endif
519 static void
520 handle_cert_status(struct imsg *imsg, size_t datalen)
522 struct req *req;
523 int is_ok;
525 req = req_by_id(imsg->hdr.peerid);
527 if (datalen < sizeof(is_ok))
528 die();
529 memcpy(&is_ok, imsg->data, sizeof(is_ok));
531 if (is_ok)
532 yield_w(req, write_request, NULL);
533 else
534 close_conn(0, 0, req);
537 static void
538 handle_proceed(struct imsg *imsg, size_t datalen)
540 yield_r(req_by_id(imsg->hdr.peerid),
541 copy_body, NULL);
544 static void
545 handle_stop(struct imsg *imsg, size_t datalen)
547 struct req *req;
549 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
550 return;
551 close_conn(0, 0, req);
554 static void
555 handle_quit(struct imsg *imsg, size_t datalen)
557 event_loopbreak();
560 static void
561 handle_dispatch_imsg(int fd, short ev, void *d)
563 struct imsgev *iev = d;
564 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
567 static int
568 net_send_ui(int type, uint32_t peerid, const void *data,
569 uint16_t datalen)
571 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
572 data, datalen);
575 int
576 client_main(void)
578 setproctitle("net");
580 TAILQ_INIT(&reqhead);
582 if ((tlsconf = tls_config_new()) == NULL)
583 die();
584 tls_config_insecure_noverifycert(tlsconf);
585 tls_config_insecure_noverifyname(tlsconf);
587 event_init();
589 /* Setup pipe and event handler to the main process */
590 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
591 die();
592 imsg_init(&iev_ui->ibuf, 3);
593 iev_ui->handler = handle_dispatch_imsg;
594 iev_ui->events = EV_READ;
595 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
596 iev_ui->handler, iev_ui);
597 event_add(&iev_ui->ev, NULL);
599 sandbox_net_process();
601 event_dispatch();
602 return 0;