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.
22 * to something more asynchronous
25 #include <telescope.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
30 #include <netinet/in.h>
43 static struct event imsgev;
44 static struct tls_config *tlsconf;
45 static struct imsgbuf *ibuf;
49 static void die(void) __attribute__((__noreturn__));
50 static char *xasprintf(const char*, ...);
51 static int conn_towards(struct url*, char**);
53 static void close_with_err(struct req*, const char *err);
54 static struct req *req_by_id(uint32_t);
55 static struct req *req_by_id_try(uint32_t);
57 static void do_handshake(int, short, void*);
58 static void write_request(int, short, void*);
59 static void read_reply(int, short, void*);
60 static void parse_reply(struct req*);
61 static void copy_body(int, short, void*);
63 static void handle_get(struct imsg*, size_t);
64 static void handle_cert_status(struct imsg*, size_t);
65 static void handle_proceed(struct imsg*, size_t);
66 static void handle_stop(struct imsg*, size_t);
67 static void handle_quit(struct imsg*, size_t);
69 /* TODO: making this customizable */
70 struct timeval timeout_for_handshake = { 5, 0 };
72 static imsg_handlerfn *handlers[] = {
73 [IMSG_GET] = handle_get,
74 [IMSG_CERT_STATUS] = handle_cert_status,
75 [IMSG_PROCEED] = handle_proceed,
76 [IMSG_STOP] = handle_stop,
77 [IMSG_QUIT] = handle_quit,
80 typedef void (*statefn)(int, short, void*);
82 TAILQ_HEAD(, req) reqhead;
83 /* a pending request */
92 TAILQ_ENTRY(req) reqs;
96 yield_r(struct req *req, statefn fn, struct timeval *tv)
98 event_once(req->fd, EV_READ, fn, req, tv);
102 yield_w(struct req *req, statefn fn, struct timeval *tv)
104 event_once(req->fd, EV_WRITE, fn, req, tv);
108 advance_buf(struct req *req, size_t len)
110 assert(len <= req->off);
113 memmove(req->buf, req->buf + len, req->off);
116 static void __attribute__((__noreturn__))
123 xasprintf(const char *fmt, ...)
129 if (vasprintf(&s, fmt, ap) == -1)
137 conn_towards(struct url *url, char **err)
139 struct addrinfo hints, *servinfo, *p;
141 const char *proto = "1965";
145 if (*url->port != '\0')
148 memset(&hints, 0, sizeof(hints));
149 hints.ai_family = AF_UNSPEC;
150 hints.ai_socktype = SOCK_STREAM;
152 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
153 *err = xasprintf("failed to resolve %s: %s",
154 url->host, gai_strerror(status));
159 for (p = servinfo; p != NULL; p = p->ai_next) {
160 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
162 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
168 *err = xasprintf("couldn't connect to %s", url->host);
172 freeaddrinfo(servinfo);
177 req_by_id(uint32_t id)
181 if ((r = req_by_id_try(id)) == NULL)
187 req_by_id_try(uint32_t id)
191 TAILQ_FOREACH(r, &reqhead, reqs) {
200 close_conn(int fd, short ev, void *d)
204 if (req->ctx != NULL) {
205 switch (tls_close(req->ctx)) {
206 case TLS_WANT_POLLIN:
207 yield_r(req, close_conn, NULL);
209 case TLS_WANT_POLLOUT:
210 yield_w(req, close_conn, NULL);
217 TAILQ_REMOVE(&reqhead, req, reqs);
224 close_with_err(struct req *req, const char *err)
226 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
228 close_conn(0, 0, req);
232 do_handshake(int fd, short ev, void *d)
237 if (ev == EV_TIMEOUT) {
238 close_with_err(req, "Timeout loading page");
242 switch (tls_handshake(req->ctx)) {
243 case TLS_WANT_POLLIN:
244 yield_r(req, do_handshake, NULL);
246 case TLS_WANT_POLLOUT:
247 yield_w(req, do_handshake, NULL);
251 hash = tls_peer_cert_hash(req->ctx);
252 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
257 write_request(int fd, short ev, void *d)
262 char buf[1024], *err;
264 strlcpy(buf, "gemini://", sizeof(buf));
265 strlcat(buf, req->url.host, sizeof(buf));
266 strlcat(buf, "/", sizeof(buf));
267 strlcat(buf, req->url.path, sizeof(buf));
269 if (req->url.query[0] != '\0') {
270 strlcat(buf, "?", sizeof(buf));
271 strlcat(buf, req->url.query, sizeof(buf));
274 len = strlcat(buf, "\r\n", sizeof(buf));
276 assert(len <= sizeof(buf));
278 switch (r = tls_write(req->ctx, buf, len)) {
280 err = xasprintf("tls_write: %s", tls_error(req->ctx));
281 close_with_err(req, err);
284 case TLS_WANT_POLLIN:
285 yield_r(req, write_request, NULL);
287 case TLS_WANT_POLLOUT:
288 yield_w(req, write_request, NULL);
291 /* assume r == len */
293 yield_r(req, read_reply, NULL);
299 read_reply(int fd, short ev, void *d)
306 buf = req->buf + req->off;
307 len = sizeof(req->buf) - req->off;
309 switch (r = tls_read(req->ctx, buf, len)) {
311 e = xasprintf("tls_read: %s", tls_error(req->ctx));
312 close_with_err(req, e);
315 case TLS_WANT_POLLIN:
316 yield_r(req, read_reply, NULL);
318 case TLS_WANT_POLLOUT:
319 yield_w(req, read_reply, NULL);
324 /* TODO: really watch for \r\n not \n alone */
325 if ((e = telescope_strnchr(req->buf, '\n', req->off)) != NULL)
327 else if (req->off == sizeof(req->buf))
328 close_with_err(req, "invalid response");
330 yield_r(req, read_reply, NULL);
336 parse_reply(struct req *req)
345 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
348 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
350 if (!isspace(req->buf[2]))
354 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
360 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
361 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
366 close_conn(0, 0, req);
367 advance_buf(req, len+1); /* skip \n too */
372 close_with_err(req, "malformed request");
376 copy_body(int fd, short ev, void *d)
383 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
389 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
390 case TLS_WANT_POLLIN:
391 yield_r(req, copy_body, NULL);
393 case TLS_WANT_POLLOUT:
394 yield_w(req, copy_body, NULL);
397 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
399 close_conn(0, 0, req);
408 handle_get(struct imsg *imsg, size_t datalen)
412 char *data, *err = NULL;
416 if (data[datalen-1] != '\0')
419 if ((req = calloc(1, sizeof(*req))) == NULL)
422 req->id = imsg->hdr.peerid;
423 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
425 if (!url_parse(imsg->data, &req->url, &e)) {
426 close_with_err(req, e);
430 if ((req->fd = conn_towards(&req->url, &err)) == -1)
432 if ((req->ctx = tls_client()) == NULL)
434 if (tls_configure(req->ctx, tlsconf) == -1) {
435 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
438 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
439 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
443 yield_w(req, do_handshake, &timeout_for_handshake);
447 close_with_err(req, err);
452 handle_cert_status(struct imsg *imsg, size_t datalen)
457 req = req_by_id(imsg->hdr.peerid);
459 if (datalen < sizeof(is_ok))
461 memcpy(&is_ok, imsg->data, sizeof(is_ok));
464 yield_w(req, write_request, NULL);
466 close_conn(0, 0, req);
470 handle_proceed(struct imsg *imsg, size_t datalen)
472 yield_r(req_by_id(imsg->hdr.peerid),
477 handle_stop(struct imsg *imsg, size_t datalen)
481 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
483 close_conn(0, 0, req);
487 handle_quit(struct imsg *imsg, size_t datalen)
493 dispatch_imsg(int fd, short ev, void *d)
495 struct imsgbuf *ibuf = d;
500 if ((n = imsg_read(ibuf)) == -1) {
501 if (errno == EAGAIN || errno == EWOULDBLOCK)
510 if ((n = imsg_get(ibuf, &imsg)) == -1)
514 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
515 handlers[imsg.hdr.type](&imsg, datalen);
521 client_main(struct imsgbuf *b)
525 TAILQ_INIT(&reqhead);
527 if ((tlsconf = tls_config_new()) == NULL)
529 tls_config_insecure_noverifycert(tlsconf);
533 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, dispatch_imsg, ibuf);
534 event_add(&imsgev, NULL);
536 sandbox_network_process();