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 static void try_to_connect(int, short, void*);
57 #if HAVE_ASR_RUN
58 static void query_done(struct asr_result*, void*);
59 static void async_conn_towards(struct req*);
60 #else
61 static void blocking_conn_towards(struct req*);
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 phos_uri url;
101 uint32_t id;
102 int fd;
103 struct tls *ctx;
104 char buf[1024];
105 size_t off;
107 struct addrinfo *servinfo, *p;
108 #if HAVE_ASR_RUN
109 struct addrinfo hints;
110 struct event_asr *asrev;
111 #endif
113 TAILQ_ENTRY(req) reqs;
114 };
116 static inline void
117 yield_r(struct req *req, statefn fn, struct timeval *tv)
119 event_once(req->fd, EV_READ, fn, req, tv);
122 static inline void
123 yield_w(struct req *req, statefn fn, struct timeval *tv)
125 event_once(req->fd, EV_WRITE, fn, req, tv);
128 static inline void
129 advance_buf(struct req *req, size_t len)
131 assert(len <= req->off);
133 req->off -= len;
134 memmove(req->buf, req->buf + len, req->off);
137 static void __attribute__((__noreturn__))
138 die(void)
140 abort(); /* TODO */
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 again:
151 if (req->p == NULL)
152 goto err;
154 if (req->fd != -1) {
155 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
156 goto err;
157 if (error != 0) {
158 errno = error;
159 goto err;
161 goto done;
164 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
165 if (req->fd == -1) {
166 req->p = req->p->ai_next;
167 goto again;
168 } else {
169 mark_nonblock(req->fd);
170 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
171 goto done;
172 yield_w(req, try_to_connect, NULL);
174 return;
176 err:
177 freeaddrinfo(req->servinfo);
178 close_with_errf(req, "failed to connect to %s",
179 req->url.host);
180 return;
182 done:
183 freeaddrinfo(req->servinfo);
184 setup_tls(req);
187 #if HAVE_ASR_RUN
188 static void
189 query_done(struct asr_result *res, void *d)
191 struct req *req = d;
193 req->asrev = NULL;
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));
197 return;
200 req->fd = -1;
201 req->servinfo = res->ar_addrinfo;
202 req->p = res->ar_addrinfo;
203 try_to_connect(0, 0, req);
206 static void
207 async_conn_towards(struct req *req)
209 struct asr_query *q;
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);
220 #else
221 static void
222 blocking_conn_towards(struct req *req)
224 struct addrinfo hints;
225 struct phos_uri *url = &req->url;
226 int status;
227 const char *proto = "1965";
229 if (*url->port != '\0')
230 proto = url->port;
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));
239 return;
242 req->fd = -1;
243 req->p = req->servinfo;
244 try_to_connect(0, 0, req);
246 #endif
248 static struct req *
249 req_by_id(uint32_t id)
251 struct req *r;
253 if ((r = req_by_id_try(id)) == NULL)
254 die();
255 return r;
258 static struct req *
259 req_by_id_try(uint32_t id)
261 struct req *r;
263 TAILQ_FOREACH(r, &reqhead, reqs) {
264 if (r->id == id)
265 return r;
268 return NULL;
271 static void
272 close_conn(int fd, short ev, void *d)
274 struct req *req = d;
276 #if HAVE_ASR_RUN
277 if (req->asrev != NULL)
278 event_asr_abort(req->asrev);
279 #endif
281 if (req->ctx != NULL) {
282 switch (tls_close(req->ctx)) {
283 case TLS_WANT_POLLIN:
284 yield_r(req, close_conn, NULL);
285 return;
286 case TLS_WANT_POLLOUT:
287 yield_w(req, close_conn, NULL);
288 return;
291 tls_free(req->ctx);
294 TAILQ_REMOVE(&reqhead, req, reqs);
295 if (req->fd != -1)
296 close(req->fd);
297 free(req);
300 static void
301 close_with_err(struct req *req, const char *err)
303 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
304 imsg_flush(ibuf);
305 close_conn(0, 0, req);
308 static void
309 close_with_errf(struct req *req, const char *fmt, ...)
311 va_list ap;
312 char *s;
314 va_start(ap, fmt);
315 if (vasprintf(&s, fmt, ap) == -1)
316 abort();
317 va_end(ap);
319 close_with_err(req, s);
320 free(s);
323 static void
324 setup_tls(struct req *req)
326 if ((req->ctx = tls_client()) == NULL) {
327 close_with_errf(req, "tls_client: %s", strerror(errno));
328 return;
330 if (tls_configure(req->ctx, tlsconf) == -1) {
331 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
332 return;
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));
336 return;
338 yield_w(req, do_handshake, &timeout_for_handshake);
341 static void
342 do_handshake(int fd, short ev, void *d)
344 struct req *req = d;
345 const char *hash;
347 if (ev == EV_TIMEOUT) {
348 close_with_err(req, "Timeout loading page");
349 return;
352 switch (tls_handshake(req->ctx)) {
353 case TLS_WANT_POLLIN:
354 yield_r(req, do_handshake, NULL);
355 return;
356 case TLS_WANT_POLLOUT:
357 yield_w(req, do_handshake, NULL);
358 return;
361 hash = tls_peer_cert_hash(req->ctx);
362 if (hash == NULL) {
363 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
364 return;
366 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
367 imsg_flush(ibuf);
370 static void
371 write_request(int fd, short ev, void *d)
373 struct req *req = d;
374 ssize_t r;
375 size_t len;
376 char buf[1027]; /* URL + \r\n\0 */
378 if (!phos_serialize_uri(&req->url, buf, sizeof(buf)))
379 die();
381 len = strlcat(buf, "\r\n", sizeof(buf));
383 assert(len <= sizeof(buf));
385 switch (r = tls_write(req->ctx, buf, len)) {
386 case -1:
387 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
388 break;
389 case TLS_WANT_POLLIN:
390 yield_r(req, write_request, NULL);
391 break;
392 case TLS_WANT_POLLOUT:
393 yield_w(req, write_request, NULL);
394 break;
395 default:
396 /* assume r == len */
397 (void)r;
398 yield_r(req, read_reply, NULL);
399 break;
403 static void
404 read_reply(int fd, short ev, void *d)
406 struct req *req = d;
407 size_t len;
408 ssize_t r;
409 char *buf;
411 buf = req->buf + req->off;
412 len = sizeof(req->buf) - req->off;
414 switch (r = tls_read(req->ctx, buf, len)) {
415 case -1:
416 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
417 break;
418 case TLS_WANT_POLLIN:
419 yield_r(req, read_reply, NULL);
420 break;
421 case TLS_WANT_POLLOUT:
422 yield_w(req, read_reply, NULL);
423 break;
424 default:
425 req->off += r;
427 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
428 parse_reply(req);
429 else if (req->off == sizeof(req->buf))
430 close_with_err(req, "invalid response");
431 else
432 yield_r(req, read_reply, NULL);
433 break;
437 static void
438 parse_reply(struct req *req)
440 int code;
441 char *e;
442 size_t len;
444 if (req->off < 4)
445 goto err;
447 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
448 goto err;
450 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
452 if (!isspace(req->buf[2]))
453 goto err;
455 advance_buf(req, 3);
456 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
457 goto err;
459 *e = '\0';
460 e++;
461 len = e - req->buf;
462 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
463 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1, req->buf, len);
464 imsg_flush(ibuf);
466 if (20 <= code && code < 30)
467 advance_buf(req, len+1); /* skip \n too */
468 else
469 close_conn(0, 0, req);
471 return;
473 err:
474 close_with_err(req, "malformed request");
477 static void
478 copy_body(int fd, short ev, void *d)
480 struct req *req = d;
481 ssize_t r;
483 for (;;) {
484 if (req->off != 0) {
485 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
486 req->buf, req->off);
487 imsg_flush(ibuf);
488 req->off = 0;
491 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
492 case TLS_WANT_POLLIN:
493 yield_r(req, copy_body, NULL);
494 return;
495 case TLS_WANT_POLLOUT:
496 yield_w(req, copy_body, NULL);
497 return;
498 case 0:
499 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
500 imsg_flush(ibuf);
501 close_conn(0, 0, req);
502 return;
503 default:
504 req->off = r;
509 static void
510 handle_get(struct imsg *imsg, size_t datalen)
512 struct req *req;
513 char *data;
515 data = imsg->data;
517 if (data[datalen-1] != '\0')
518 die();
520 if ((req = calloc(1, sizeof(*req))) == NULL)
521 die();
523 req->id = imsg->hdr.peerid;
524 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
526 if (!phos_parse_absolute_uri(data, &req->url)) {
527 close_with_err(req, "Can't parse URI");
528 return;
531 #if HAVE_ASR_RUN
532 async_conn_towards(req);
533 #else
534 blocking_conn_towards(req);
535 #endif
538 static void
539 handle_cert_status(struct imsg *imsg, size_t datalen)
541 struct req *req;
542 int is_ok;
544 req = req_by_id(imsg->hdr.peerid);
546 if (datalen < sizeof(is_ok))
547 die();
548 memcpy(&is_ok, imsg->data, sizeof(is_ok));
550 if (is_ok)
551 yield_w(req, write_request, NULL);
552 else
553 close_conn(0, 0, req);
556 static void
557 handle_proceed(struct imsg *imsg, size_t datalen)
559 yield_r(req_by_id(imsg->hdr.peerid),
560 copy_body, NULL);
563 static void
564 handle_stop(struct imsg *imsg, size_t datalen)
566 struct req *req;
568 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
569 return;
570 close_conn(0, 0, req);
573 static void
574 handle_quit(struct imsg *imsg, size_t datalen)
576 event_loopbreak();
579 static void
580 handle_dispatch_imsg(int fd, short ev, void *d)
582 struct imsgbuf *ibuf = d;
583 dispatch_imsg(ibuf, handlers, sizeof(handlers));
586 int
587 client_main(struct imsgbuf *b)
589 ibuf = b;
591 TAILQ_INIT(&reqhead);
593 if ((tlsconf = tls_config_new()) == NULL)
594 die();
595 tls_config_insecure_noverifycert(tlsconf);
596 tls_config_insecure_noverifyname(tlsconf);
598 event_init();
600 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
601 event_add(&imsgev, NULL);
603 sandbox_network_process();
605 event_dispatch();
606 return 0;