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 "compat.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 #include "telescope.h"
41 static struct imsgev *iev_ui;
42 static struct tls_config *tlsconf;
44 struct req;
46 static void die(void) __attribute__((__noreturn__));
48 static void try_to_connect(int, short, void*);
50 #if HAVE_ASR_RUN
51 static void query_done(struct asr_result*, void*);
52 static void async_conn_towards(struct req*);
53 #else
54 static void blocking_conn_towards(struct req*);
55 #endif
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,
87 };
89 typedef void (*statefn)(int, short, void*);
91 TAILQ_HEAD(, req) reqhead;
92 /* a pending request */
93 struct req {
94 struct event ev;
95 struct phos_uri url;
96 uint32_t id;
97 int fd;
98 struct tls *ctx;
99 char buf[1024];
100 size_t off;
102 struct addrinfo *servinfo, *p;
103 #if HAVE_ASR_RUN
104 struct addrinfo hints;
105 struct event_asr *asrev;
106 #endif
108 TAILQ_ENTRY(req) reqs;
109 };
111 static inline void
112 yield_r(struct req *req, statefn fn, struct timeval *tv)
114 event_once(req->fd, EV_READ, fn, req, tv);
117 static inline void
118 yield_w(struct req *req, statefn fn, struct timeval *tv)
120 event_once(req->fd, EV_WRITE, fn, req, tv);
123 static inline void
124 advance_buf(struct req *req, size_t len)
126 assert(len <= req->off);
128 req->off -= len;
129 memmove(req->buf, req->buf + len, req->off);
132 static void __attribute__((__noreturn__))
133 die(void)
135 abort(); /* TODO */
138 static void
139 try_to_connect(int fd, short ev, void *d)
141 struct req *req = d;
142 int error = 0;
143 socklen_t len = sizeof(error);
145 again:
146 if (req->p == NULL)
147 goto err;
149 if (req->fd != -1) {
150 if (getsockopt(req->fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
151 goto err;
152 if (error != 0) {
153 errno = error;
154 goto err;
156 goto done;
159 req->fd = socket(req->p->ai_family, req->p->ai_socktype, req->p->ai_protocol);
160 if (req->fd == -1) {
161 req->p = req->p->ai_next;
162 goto again;
163 } else {
164 mark_nonblock(req->fd);
165 if (connect(req->fd, req->p->ai_addr, req->p->ai_addrlen) == 0)
166 goto done;
167 yield_w(req, try_to_connect, NULL);
169 return;
171 err:
172 freeaddrinfo(req->servinfo);
173 close_with_errf(req, "failed to connect to %s",
174 req->url.host);
175 return;
177 done:
178 freeaddrinfo(req->servinfo);
179 setup_tls(req);
182 #if HAVE_ASR_RUN
183 static void
184 query_done(struct asr_result *res, void *d)
186 struct req *req = d;
188 req->asrev = NULL;
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));
192 return;
195 req->fd = -1;
196 req->servinfo = res->ar_addrinfo;
197 req->p = res->ar_addrinfo;
198 try_to_connect(0, 0, req);
201 static void
202 async_conn_towards(struct req *req)
204 struct asr_query *q;
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);
215 #else
216 static void
217 blocking_conn_towards(struct req *req)
219 struct addrinfo hints;
220 struct phos_uri *url = &req->url;
221 int status;
222 const char *proto = "1965";
224 if (*url->port != '\0')
225 proto = url->port;
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));
234 return;
237 req->fd = -1;
238 req->p = req->servinfo;
239 try_to_connect(0, 0, req);
241 #endif
243 static struct req *
244 req_by_id(uint32_t id)
246 struct req *r;
248 if ((r = req_by_id_try(id)) == NULL)
249 die();
250 return r;
253 static struct req *
254 req_by_id_try(uint32_t id)
256 struct req *r;
258 TAILQ_FOREACH(r, &reqhead, reqs) {
259 if (r->id == id)
260 return r;
263 return NULL;
266 static void
267 close_conn(int fd, short ev, void *d)
269 struct req *req = d;
271 #if HAVE_ASR_RUN
272 if (req->asrev != NULL)
273 event_asr_abort(req->asrev);
274 #endif
276 if (req->ctx != NULL) {
277 switch (tls_close(req->ctx)) {
278 case TLS_WANT_POLLIN:
279 yield_r(req, close_conn, NULL);
280 return;
281 case TLS_WANT_POLLOUT:
282 yield_w(req, close_conn, NULL);
283 return;
286 tls_free(req->ctx);
289 TAILQ_REMOVE(&reqhead, req, reqs);
290 if (req->fd != -1)
291 close(req->fd);
292 free(req);
295 static void
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);
302 static void
303 close_with_errf(struct req *req, const char *fmt, ...)
305 va_list ap;
306 char *s;
308 va_start(ap, fmt);
309 if (vasprintf(&s, fmt, ap) == -1)
310 abort();
311 va_end(ap);
313 close_with_err(req, s);
314 free(s);
317 static void
318 setup_tls(struct req *req)
320 if ((req->ctx = tls_client()) == NULL) {
321 close_with_errf(req, "tls_client: %s", strerror(errno));
322 return;
324 if (tls_configure(req->ctx, tlsconf) == -1) {
325 close_with_errf(req, "tls_configure: %s", tls_error(req->ctx));
326 return;
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));
330 return;
332 yield_w(req, do_handshake, &timeout_for_handshake);
335 static void
336 do_handshake(int fd, short ev, void *d)
338 struct req *req = d;
339 const char *hash;
341 if (ev == EV_TIMEOUT) {
342 close_with_err(req, "Timeout loading page");
343 return;
346 switch (tls_handshake(req->ctx)) {
347 case TLS_WANT_POLLIN:
348 yield_r(req, do_handshake, NULL);
349 return;
350 case TLS_WANT_POLLOUT:
351 yield_w(req, do_handshake, NULL);
352 return;
355 hash = tls_peer_cert_hash(req->ctx);
356 if (hash == NULL) {
357 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
358 return;
360 net_send_ui(IMSG_CHECK_CERT, req->id, hash, strlen(hash)+1);
363 static void
364 write_request(int fd, short ev, void *d)
366 struct req *req = d;
367 ssize_t r;
368 size_t len;
370 len = strlen(req->buf);
372 switch (r = tls_write(req->ctx, req->buf, len)) {
373 case -1:
374 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
375 break;
376 case TLS_WANT_POLLIN:
377 yield_r(req, write_request, NULL);
378 break;
379 case TLS_WANT_POLLOUT:
380 yield_w(req, write_request, NULL);
381 break;
382 default:
383 /* assume r == len */
384 (void)r;
385 yield_r(req, read_reply, NULL);
386 break;
390 static void
391 read_reply(int fd, short ev, void *d)
393 struct req *req = d;
394 size_t len;
395 ssize_t r;
396 char *buf;
398 buf = req->buf + req->off;
399 len = sizeof(req->buf) - req->off;
401 switch (r = tls_read(req->ctx, buf, len)) {
402 case -1:
403 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
404 break;
405 case TLS_WANT_POLLIN:
406 yield_r(req, read_reply, NULL);
407 break;
408 case TLS_WANT_POLLOUT:
409 yield_w(req, read_reply, NULL);
410 break;
411 default:
412 req->off += r;
414 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
415 parse_reply(req);
416 else if (req->off == sizeof(req->buf))
417 close_with_err(req, "invalid response");
418 else
419 yield_r(req, read_reply, NULL);
420 break;
424 static void
425 parse_reply(struct req *req)
427 int code;
428 char *e;
429 size_t len;
431 if (req->off < 4)
432 goto err;
434 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
435 goto err;
437 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
439 if (!isspace(req->buf[2]))
440 goto err;
442 advance_buf(req, 3);
443 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
444 goto err;
446 *e = '\0';
447 e++;
448 len = e - req->buf;
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 */
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 net_send_ui(IMSG_BUF, req->id,
472 req->buf, req->off);
473 req->off = 0;
476 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
477 case TLS_WANT_POLLIN:
478 yield_r(req, copy_body, NULL);
479 return;
480 case TLS_WANT_POLLOUT:
481 yield_w(req, copy_body, NULL);
482 return;
483 case -1:
484 /*
485 * XXX: should notify the user that the
486 * download was aborted.
487 */
488 /* fallthrough */
489 case 0:
490 net_send_ui(IMSG_EOF, req->id, NULL, 0);
491 close_conn(0, 0, req);
492 return;
493 default:
494 req->off = r;
499 static void
500 handle_get_raw(struct imsg *imsg, size_t datalen)
502 struct req *req;
503 struct get_req *r;
505 r = imsg->data;
507 if (datalen != sizeof(*r))
508 die();
510 if ((req = calloc(1, sizeof(*req))) == NULL)
511 die();
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));
520 #if HAVE_ASR_RUN
521 async_conn_towards(req);
522 #else
523 blocking_conn_towards(req);
524 #endif
527 static void
528 handle_cert_status(struct imsg *imsg, size_t datalen)
530 struct req *req;
531 int is_ok;
533 req = req_by_id(imsg->hdr.peerid);
535 if (datalen < sizeof(is_ok))
536 die();
537 memcpy(&is_ok, imsg->data, sizeof(is_ok));
539 if (is_ok)
540 yield_w(req, write_request, NULL);
541 else
542 close_conn(0, 0, req);
545 static void
546 handle_proceed(struct imsg *imsg, size_t datalen)
548 yield_r(req_by_id(imsg->hdr.peerid),
549 copy_body, NULL);
552 static void
553 handle_stop(struct imsg *imsg, size_t datalen)
555 struct req *req;
557 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
558 return;
559 close_conn(0, 0, req);
562 static void
563 handle_quit(struct imsg *imsg, size_t datalen)
565 event_loopbreak();
568 static void
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");
577 static int
578 net_send_ui(int type, uint32_t peerid, const void *data,
579 uint16_t datalen)
581 return imsg_compose_event(iev_ui, type, peerid, 0, -1,
582 data, datalen);
585 int
586 client_main(void)
588 setproctitle("net");
590 TAILQ_INIT(&reqhead);
592 if ((tlsconf = tls_config_new()) == NULL)
593 die();
594 tls_config_insecure_noverifycert(tlsconf);
595 tls_config_insecure_noverifyname(tlsconf);
597 event_init();
599 /* Setup pipe and event handler to the main process */
600 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
601 die();
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();
611 event_dispatch();
612 return 0;