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>
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);
56 static void do_handshake(int, short, void*);
57 static void write_request(int, short, void*);
58 static void read_reply(int, short, void*);
59 static void parse_reply(struct req*);
60 static void copy_body(int, short, void*);
62 static void check_special_page(struct req*, const char*);
64 static void handle_get(struct imsg*, size_t);
65 static void handle_cert_status(struct imsg*, size_t);
66 static void handle_stop(struct imsg*, size_t);
67 static void handle_quit(struct imsg*, size_t);
69 static imsg_handlerfn *handlers[] = {
70 [IMSG_GET] = handle_get,
71 [IMSG_CERT_STATUS] = handle_cert_status,
72 [IMSG_STOP] = handle_stop,
73 [IMSG_QUIT] = handle_quit,
76 typedef void (*statefn)(int, short, void*);
78 TAILQ_HEAD(, req) reqhead;
79 /* a pending request */
88 TAILQ_ENTRY(req) reqs;
92 yield_r(struct req *req, statefn fn, struct timeval *tv)
94 event_once(req->fd, EV_READ, fn, req, tv);
98 yield_w(struct req *req, statefn fn, struct timeval *tv)
100 event_once(req->fd, EV_WRITE, fn, req, tv);
104 advance_buf(struct req *req, size_t len)
106 assert(len <= req->off);
109 memmove(req->buf, req->buf + len, req->off);
112 static void __attribute__((__noreturn__))
119 xasprintf(const char *fmt, ...)
125 if (vasprintf(&s, fmt, ap) == -1)
133 conn_towards(struct url *url, char **err)
135 struct addrinfo hints, *servinfo, *p;
137 const char *proto = "1965";
141 if (*url->port != '\0')
144 memset(&hints, 0, sizeof(hints));
145 hints.ai_family = AF_UNSPEC;
146 hints.ai_socktype = SOCK_STREAM;
148 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
149 *err = xasprintf("failed to resolve %s: %s",
150 url->host, gai_strerror(status));
155 for (p = servinfo; p != NULL; p = p->ai_next) {
156 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
158 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
164 *err = xasprintf("couldn't connect to %s", url->host);
168 freeaddrinfo(servinfo);
173 req_by_id(uint32_t id)
177 TAILQ_FOREACH(r, &reqhead, reqs) {
186 close_conn(int fd, short ev, void *d)
190 if (req->ctx != NULL) {
191 switch (tls_close(req->ctx)) {
192 case TLS_WANT_POLLIN:
193 yield_r(req, close_conn, NULL);
195 case TLS_WANT_POLLOUT:
196 yield_w(req, close_conn, NULL);
203 TAILQ_REMOVE(&reqhead, req, reqs);
210 close_with_err(struct req *req, const char *err)
212 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
214 close_conn(0, 0, req);
218 do_handshake(int fd, short ev, void *d)
223 switch (tls_handshake(req->ctx)) {
224 case TLS_WANT_POLLIN:
225 yield_r(req, do_handshake, NULL);
227 case TLS_WANT_POLLOUT:
228 yield_w(req, do_handshake, NULL);
232 hash = tls_peer_cert_hash(req->ctx);
233 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
238 write_request(int fd, short ev, void *d)
243 char buf[1024], *err;
245 strlcpy(buf, "gemini://", sizeof(buf));
246 strlcat(buf, req->url.host, sizeof(buf));
247 strlcat(buf, "/", sizeof(buf));
248 strlcat(buf, req->url.path, sizeof(buf));
250 if (req->url.query[0] != '\0') {
251 strlcat(buf, "?", sizeof(buf));
252 strlcat(buf, req->url.query, sizeof(buf));
255 len = strlcat(buf, "\r\n", sizeof(buf));
257 assert(len <= sizeof(buf));
259 switch (r = tls_write(req->ctx, buf, len)) {
261 err = xasprintf("tls_write: %s", tls_error(req->ctx));
262 close_with_err(req, err);
265 case TLS_WANT_POLLIN:
266 yield_r(req, write_request, NULL);
268 case TLS_WANT_POLLOUT:
269 yield_w(req, write_request, NULL);
272 /* assume r == len */
274 yield_r(req, read_reply, NULL);
280 read_reply(int fd, short ev, void *d)
287 buf = req->buf + req->off;
288 len = sizeof(req->buf) - req->off;
290 switch (r = tls_read(req->ctx, buf, len)) {
292 e = xasprintf("tls_read: %s", tls_error(req->ctx));
293 close_with_err(req, e);
296 case TLS_WANT_POLLIN:
297 yield_r(req, read_reply, NULL);
299 case TLS_WANT_POLLOUT:
300 yield_w(req, read_reply, NULL);
305 /* TODO: really watch for \r\n not \n alone */
306 if ((e = telescope_strnchr(req->buf, '\n', req->off)) != NULL)
308 else if (req->off == sizeof(req->buf))
309 close_with_err(req, "invalid response");
311 yield_r(req, read_reply, NULL);
317 parse_reply(struct req *req)
326 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
329 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
331 if (!isspace(req->buf[2]))
335 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
341 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
342 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
346 yield_r(req, copy_body, NULL);
350 close_with_err(req, "malformed request");
354 copy_body(int fd, short ev, void *d)
361 switch (r = tls_read(req->ctx, buf, sizeof(buf))) {
362 case TLS_WANT_POLLIN:
363 yield_r(req, copy_body, NULL);
365 case TLS_WANT_POLLOUT:
366 yield_w(req, copy_body, NULL);
370 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
372 close_conn(0, 0, req);
375 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1, buf, r);
383 serve_special_page(struct req *req, const char *url)
386 const char *meta = "text/gemini";
388 if (strcmp(url, "about:new"))
391 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
392 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1, meta, strlen(meta)+1);
393 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1, about_new, strlen(about_new));
394 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
397 /* don't close_page here, since req is not added to requests
404 handle_get(struct imsg *imsg, size_t datalen)
408 char *data, *err = NULL;
412 if (data[datalen-1] != '\0')
415 if ((req = calloc(1, sizeof(*req))) == NULL)
418 req->id = imsg->hdr.peerid;
420 if (serve_special_page(req, data))
423 if (!url_parse(imsg->data, &req->url, &e)) {
424 fprintf(stderr, "failed to parse url: %s\n", e);
425 close_with_err(req, e);
429 if ((req->fd = conn_towards(&req->url, &err)) == -1)
431 if ((req->ctx = tls_client()) == NULL)
433 if (tls_configure(req->ctx, tlsconf) == -1) {
434 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
437 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
438 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
442 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
443 yield_w(req, do_handshake, NULL);
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_stop(struct imsg *imsg, size_t datalen)
474 req = req_by_id(imsg->hdr.peerid);
475 close_conn(0, 0, req);
479 handle_quit(struct imsg *imsg, size_t datalen)
485 dispatch_imsg(int fd, short ev, void *d)
487 struct imsgbuf *ibuf = d;
492 if ((n = imsg_read(ibuf)) == -1) {
493 if (errno == EAGAIN || errno == EWOULDBLOCK)
502 if ((n = imsg_get(ibuf, &imsg)) == -1)
506 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
507 handlers[imsg.hdr.type](&imsg, datalen);
513 client_main(struct imsgbuf *b)
517 TAILQ_INIT(&reqhead);
519 if ((tlsconf = tls_config_new()) == NULL)
521 tls_config_insecure_noverifycert(tlsconf);
525 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, dispatch_imsg, ibuf);
526 event_add(&imsgev, NULL);