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 event imsgev;
40 static struct tls_config *tlsconf;
41 static struct imsgbuf *ibuf;
43 struct req;
45 static void die(void) __attribute__((__noreturn__));
47 static void try_to_connect(int, short, void*);
49 #if HAVE_ASR_RUN
50 static void query_done(struct asr_result*, void*);
51 static void async_conn_towards(struct req*);
52 #else
53 static void blocking_conn_towards(struct req*);
54 #endif
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,
84 };
86 typedef void (*statefn)(int, short, void*);
88 TAILQ_HEAD(, req) reqhead;
89 /* a pending request */
90 struct req {
91 struct event ev;
92 struct phos_uri url;
93 uint32_t id;
94 int fd;
95 struct tls *ctx;
96 char buf[1024];
97 size_t off;
99 struct addrinfo *servinfo, *p;
100 #if HAVE_ASR_RUN
101 struct addrinfo hints;
102 struct event_asr *asrev;
103 #endif
105 TAILQ_ENTRY(req) reqs;
106 };
108 static inline void
109 yield_r(struct req *req, statefn fn, struct timeval *tv)
111 event_once(req->fd, EV_READ, fn, req, tv);
114 static inline void
115 yield_w(struct req *req, statefn fn, struct timeval *tv)
117 event_once(req->fd, EV_WRITE, fn, req, tv);
120 static inline void
121 advance_buf(struct req *req, size_t len)
123 assert(len <= req->off);
125 req->off -= len;
126 memmove(req->buf, req->buf + len, req->off);
129 static void __attribute__((__noreturn__))
130 die(void)
132 abort(); /* TODO */
135 static void
136 try_to_connect(int fd, short ev, void *d)
138 struct req *req = d;
139 int error = 0;
140 socklen_t len = sizeof(error);
142 again:
143 if (req->p == NULL)
144 goto err;
146 if (req->fd != -1) {
147 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
148 goto err;
149 if (error != 0) {
150 errno = error;
151 goto err;
153 goto done;
156 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
157 if (req->fd == -1) {
158 req->p = req->p->ai_next;
159 goto again;
160 } else {
161 mark_nonblock(req->fd);
162 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
163 goto done;
164 yield_w(req, try_to_connect, NULL);
166 return;
168 err:
169 freeaddrinfo(req->servinfo);
170 close_with_errf(req, "failed to connect to %s",
171 req->url.host);
172 return;
174 done:
175 freeaddrinfo(req->servinfo);
176 setup_tls(req);
179 #if HAVE_ASR_RUN
180 static void
181 query_done(struct asr_result *res, void *d)
183 struct req *req = d;
185 req->asrev = NULL;
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));
189 return;
192 req->fd = -1;
193 req->servinfo = res->ar_addrinfo;
194 req->p = res->ar_addrinfo;
195 try_to_connect(0, 0, req);
198 static void
199 async_conn_towards(struct req *req)
201 struct asr_query *q;
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);
212 #else
213 static void
214 blocking_conn_towards(struct req *req)
216 struct addrinfo hints;
217 struct phos_uri *url = &req->url;
218 int status;
219 const char *proto = "1965";
221 if (*url->port != '\0')
222 proto = url->port;
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));
231 return;
234 req->fd = -1;
235 req->p = req->servinfo;
236 try_to_connect(0, 0, req);
238 #endif
240 static struct req *
241 req_by_id(uint32_t id)
243 struct req *r;
245 if ((r = req_by_id_try(id)) == NULL)
246 die();
247 return r;
250 static struct req *
251 req_by_id_try(uint32_t id)
253 struct req *r;
255 TAILQ_FOREACH(r, &reqhead, reqs) {
256 if (r->id == id)
257 return r;
260 return NULL;
263 static void
264 close_conn(int fd, short ev, void *d)
266 struct req *req = d;
268 #if HAVE_ASR_RUN
269 if (req->asrev != NULL)
270 event_asr_abort(req->asrev);
271 #endif
273 if (req->ctx != NULL) {
274 switch (tls_close(req->ctx)) {
275 case TLS_WANT_POLLIN:
276 yield_r(req, close_conn, NULL);
277 return;
278 case TLS_WANT_POLLOUT:
279 yield_w(req, close_conn, NULL);
280 return;
283 tls_free(req->ctx);
286 TAILQ_REMOVE(&reqhead, req, reqs);
287 if (req->fd != -1)
288 close(req->fd);
289 free(req);
292 static void
293 close_with_err(struct req *req, const char *err)
295 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
296 imsg_flush(ibuf);
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 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
359 imsg_flush(ibuf);
362 static void
363 write_request(int fd, short ev, void *d)
365 struct req *req = d;
366 ssize_t r;
367 size_t len;
369 len = strlen(req->buf);
371 switch (r = tls_write(req->ctx, req->buf, len)) {
372 case -1:
373 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
374 break;
375 case TLS_WANT_POLLIN:
376 yield_r(req, write_request, NULL);
377 break;
378 case TLS_WANT_POLLOUT:
379 yield_w(req, write_request, NULL);
380 break;
381 default:
382 /* assume r == len */
383 (void)r;
384 yield_r(req, read_reply, NULL);
385 break;
389 static void
390 read_reply(int fd, short ev, void *d)
392 struct req *req = d;
393 size_t len;
394 ssize_t r;
395 char *buf;
397 buf = req->buf + req->off;
398 len = sizeof(req->buf) - req->off;
400 switch (r = tls_read(req->ctx, buf, len)) {
401 case -1:
402 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
403 break;
404 case TLS_WANT_POLLIN:
405 yield_r(req, read_reply, NULL);
406 break;
407 case TLS_WANT_POLLOUT:
408 yield_w(req, read_reply, NULL);
409 break;
410 default:
411 req->off += r;
413 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
414 parse_reply(req);
415 else if (req->off == sizeof(req->buf))
416 close_with_err(req, "invalid response");
417 else
418 yield_r(req, read_reply, NULL);
419 break;
423 static void
424 parse_reply(struct req *req)
426 int code;
427 char *e;
428 size_t len;
430 if (req->off < 4)
431 goto err;
433 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
434 goto err;
436 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
438 if (!isspace(req->buf[2]))
439 goto err;
441 advance_buf(req, 3);
442 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
443 goto err;
445 *e = '\0';
446 e++;
447 len = e - req->buf;
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);
450 imsg_flush(ibuf);
452 if (20 <= code && code < 30)
453 advance_buf(req, len+1); /* skip \n too */
454 else
455 close_conn(0, 0, req);
457 return;
459 err:
460 close_with_err(req, "malformed request");
463 static void
464 copy_body(int fd, short ev, void *d)
466 struct req *req = d;
467 ssize_t r;
469 for (;;) {
470 if (req->off != 0) {
471 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
472 req->buf, req->off);
473 imsg_flush(ibuf);
474 req->off = 0;
477 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
478 case TLS_WANT_POLLIN:
479 yield_r(req, copy_body, NULL);
480 return;
481 case TLS_WANT_POLLOUT:
482 yield_w(req, copy_body, NULL);
483 return;
484 case 0:
485 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
486 imsg_flush(ibuf);
487 close_conn(0, 0, req);
488 return;
489 default:
490 req->off = r;
495 static void
496 handle_get_raw(struct imsg *imsg, size_t datalen)
498 struct req *req;
499 struct get_req *r;
501 r = imsg->data;
503 if (datalen != sizeof(*r))
504 die();
506 if ((req = calloc(1, sizeof(*req))) == NULL)
507 die();
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));
516 #if HAVE_ASR_RUN
517 async_conn_towards(req);
518 #else
519 blocking_conn_towards(req);
520 #endif
523 static void
524 handle_cert_status(struct imsg *imsg, size_t datalen)
526 struct req *req;
527 int is_ok;
529 req = req_by_id(imsg->hdr.peerid);
531 if (datalen < sizeof(is_ok))
532 die();
533 memcpy(&is_ok, imsg->data, sizeof(is_ok));
535 if (is_ok)
536 yield_w(req, write_request, NULL);
537 else
538 close_conn(0, 0, req);
541 static void
542 handle_proceed(struct imsg *imsg, size_t datalen)
544 yield_r(req_by_id(imsg->hdr.peerid),
545 copy_body, NULL);
548 static void
549 handle_stop(struct imsg *imsg, size_t datalen)
551 struct req *req;
553 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
554 return;
555 close_conn(0, 0, req);
558 static void
559 handle_quit(struct imsg *imsg, size_t datalen)
561 event_loopbreak();
564 static void
565 handle_dispatch_imsg(int fd, short ev, void *d)
567 struct imsgbuf *ibuf = d;
568 dispatch_imsg(ibuf, handlers, sizeof(handlers));
571 int
572 client_main(void)
574 setproctitle("net");
576 TAILQ_INIT(&reqhead);
578 if ((tlsconf = tls_config_new()) == NULL)
579 die();
580 tls_config_insecure_noverifycert(tlsconf);
581 tls_config_insecure_noverifyname(tlsconf);
583 event_init();
585 /* Setup pipe and event handler to the main process */
586 if ((ibuf = calloc(1, sizeof(*ibuf))) == NULL)
587 die();
588 imsg_init(ibuf, 3);
589 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
590 event_add(&imsgev, NULL);
592 sandbox_net_process();
594 event_dispatch();
595 return 0;