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 static struct event imsgev;
44 static struct tls_config *tlsconf;
45 static struct imsgbuf *ibuf;
47 struct req;
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*);
54 static void close_with_errf(struct req*, const char*, ...) __attribute__((format(printf, 2, 3)));
55 static struct req *req_by_id(uint32_t);
56 static struct req *req_by_id_try(uint32_t);
58 static void do_handshake(int, short, void*);
59 static void write_request(int, short, void*);
60 static void read_reply(int, short, void*);
61 static void parse_reply(struct req*);
62 static void copy_body(int, short, void*);
64 static void handle_get(struct imsg*, size_t);
65 static void handle_cert_status(struct imsg*, size_t);
66 static void handle_proceed(struct imsg*, size_t);
67 static void handle_stop(struct imsg*, size_t);
68 static void handle_quit(struct imsg*, size_t);
69 static void handle_dispatch_imsg(int, short, void*);
71 /* TODO: making this customizable */
72 struct timeval timeout_for_handshake = { 5, 0 };
74 static imsg_handlerfn *handlers[] = {
75 [IMSG_GET] = handle_get,
76 [IMSG_CERT_STATUS] = handle_cert_status,
77 [IMSG_PROCEED] = handle_proceed,
78 [IMSG_STOP] = handle_stop,
79 [IMSG_QUIT] = handle_quit,
80 };
82 typedef void (*statefn)(int, short, void*);
84 TAILQ_HEAD(, req) reqhead;
85 /* a pending request */
86 struct req {
87 struct event ev;
88 struct url url;
89 uint32_t id;
90 int fd;
91 struct tls *ctx;
92 char buf[1024];
93 size_t off;
94 TAILQ_ENTRY(req) reqs;
95 };
97 static inline void
98 yield_r(struct req *req, statefn fn, struct timeval *tv)
99 {
100 event_once(req->fd, EV_READ, fn, req, tv);
103 static inline void
104 yield_w(struct req *req, statefn fn, struct timeval *tv)
106 event_once(req->fd, EV_WRITE, fn, req, tv);
109 static inline void
110 advance_buf(struct req *req, size_t len)
112 assert(len <= req->off);
114 req->off -= len;
115 memmove(req->buf, req->buf + len, req->off);
118 static void __attribute__((__noreturn__))
119 die(void)
121 abort(); /* TODO */
124 static char *
125 xasprintf(const char *fmt, ...)
127 va_list ap;
128 char *s;
130 va_start(ap, fmt);
131 if (vasprintf(&s, fmt, ap) == -1)
132 s = NULL;
133 va_end(ap);
135 return s;
138 static int
139 conn_towards(struct url *url, char **err)
141 struct addrinfo hints, *servinfo, *p;
142 int status, sock;
143 const char *proto = "1965";
145 *err = NULL;
147 if (*url->port != '\0')
148 proto = url->port;
150 memset(&hints, 0, sizeof(hints));
151 hints.ai_family = AF_UNSPEC;
152 hints.ai_socktype = SOCK_STREAM;
154 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
155 *err = xasprintf("failed to resolve %s: %s",
156 url->host, gai_strerror(status));
157 return -1;
160 sock = -1;
161 for (p = servinfo; p != NULL; p = p->ai_next) {
162 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
163 continue;
164 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
165 break;
166 close(sock);
169 if (sock == -1)
170 *err = xasprintf("couldn't connect to %s", url->host);
171 else
172 mark_nonblock(sock);
174 freeaddrinfo(servinfo);
175 return sock;
178 static struct req *
179 req_by_id(uint32_t id)
181 struct req *r;
183 if ((r = req_by_id_try(id)) == NULL)
184 die();
185 return r;
188 static struct req *
189 req_by_id_try(uint32_t id)
191 struct req *r;
193 TAILQ_FOREACH(r, &reqhead, reqs) {
194 if (r->id == id)
195 return r;
198 return NULL;
201 static void
202 close_conn(int fd, short ev, void *d)
204 struct req *req = d;
206 if (req->ctx != NULL) {
207 switch (tls_close(req->ctx)) {
208 case TLS_WANT_POLLIN:
209 yield_r(req, close_conn, NULL);
210 return;
211 case TLS_WANT_POLLOUT:
212 yield_w(req, close_conn, NULL);
213 return;
216 tls_free(req->ctx);
219 TAILQ_REMOVE(&reqhead, req, reqs);
220 if (req->fd != -1)
221 close(req->fd);
222 free(req);
225 static void
226 close_with_err(struct req *req, const char *err)
228 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
229 imsg_flush(ibuf);
230 close_conn(0, 0, req);
233 static void
234 close_with_errf(struct req *req, const char *fmt, ...)
236 va_list ap;
237 char *s;
239 va_start(ap, fmt);
240 if (vasprintf(&s, fmt, ap) == -1)
241 abort();
242 va_end(ap);
244 close_with_err(req, s);
245 free(s);
248 static void
249 do_handshake(int fd, short ev, void *d)
251 struct req *req = d;
252 const char *hash;
254 if (ev == EV_TIMEOUT) {
255 close_with_err(req, "Timeout loading page");
256 return;
259 switch (tls_handshake(req->ctx)) {
260 case TLS_WANT_POLLIN:
261 yield_r(req, do_handshake, NULL);
262 return;
263 case TLS_WANT_POLLOUT:
264 yield_w(req, do_handshake, NULL);
265 return;
268 hash = tls_peer_cert_hash(req->ctx);
269 if (hash == NULL) {
270 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
271 return;
273 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
274 imsg_flush(ibuf);
277 static void
278 write_request(int fd, short ev, void *d)
280 struct req *req = d;
281 ssize_t r;
282 size_t len;
283 char buf[1024];
285 strlcpy(buf, "gemini://", sizeof(buf));
286 strlcat(buf, req->url.host, sizeof(buf));
287 strlcat(buf, "/", sizeof(buf));
288 strlcat(buf, req->url.path, sizeof(buf));
290 if (req->url.query[0] != '\0') {
291 strlcat(buf, "?", sizeof(buf));
292 strlcat(buf, req->url.query, sizeof(buf));
295 len = strlcat(buf, "\r\n", sizeof(buf));
297 assert(len <= sizeof(buf));
299 switch (r = tls_write(req->ctx, buf, len)) {
300 case -1:
301 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
302 break;
303 case TLS_WANT_POLLIN:
304 yield_r(req, write_request, NULL);
305 break;
306 case TLS_WANT_POLLOUT:
307 yield_w(req, write_request, NULL);
308 break;
309 default:
310 /* assume r == len */
311 (void)r;
312 yield_r(req, read_reply, NULL);
313 break;
317 static void
318 read_reply(int fd, short ev, void *d)
320 struct req *req = d;
321 size_t len;
322 ssize_t r;
323 char *buf;
325 buf = req->buf + req->off;
326 len = sizeof(req->buf) - req->off;
328 switch (r = tls_read(req->ctx, buf, len)) {
329 case -1:
330 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
331 break;
332 case TLS_WANT_POLLIN:
333 yield_r(req, read_reply, NULL);
334 break;
335 case TLS_WANT_POLLOUT:
336 yield_w(req, read_reply, NULL);
337 break;
338 default:
339 req->off += r;
341 /* TODO: really watch for \r\n not \n alone */
342 if (memmem(req->buf, req->off, "\r\n", 2) != NULL)
343 parse_reply(req);
344 else if (req->off == sizeof(req->buf))
345 close_with_err(req, "invalid response");
346 else
347 yield_r(req, read_reply, NULL);
348 break;
352 static void
353 parse_reply(struct req *req)
355 int code;
356 char *e;
357 size_t len;
359 if (req->off < 4)
360 goto err;
362 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
363 goto err;
365 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
367 if (!isspace(req->buf[2]))
368 goto err;
370 advance_buf(req, 3);
371 if ((e = memmem(req->buf, req->off, "\r\n", 2)) == NULL)
372 goto err;
374 *e = '\0';
375 e++;
376 len = e - req->buf;
377 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
378 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
379 req->buf, len);
380 imsg_flush(ibuf);
382 if (code != 20)
383 close_conn(0, 0, req);
384 advance_buf(req, len+1); /* skip \n too */
386 return;
388 err:
389 close_with_err(req, "malformed request");
392 static void
393 copy_body(int fd, short ev, void *d)
395 struct req *req = d;
396 ssize_t r;
398 for (;;) {
399 if (req->off != 0) {
400 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
401 req->buf, req->off);
402 imsg_flush(ibuf);
403 req->off = 0;
406 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
407 case TLS_WANT_POLLIN:
408 yield_r(req, copy_body, NULL);
409 return;
410 case TLS_WANT_POLLOUT:
411 yield_w(req, copy_body, NULL);
412 return;
413 case 0:
414 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
415 imsg_flush(ibuf);
416 close_conn(0, 0, req);
417 return;
418 default:
419 req->off = r;
424 static void
425 handle_get(struct imsg *imsg, size_t datalen)
427 struct req *req;
428 const char *e;
429 char *data, *err = NULL;
431 data = imsg->data;
433 if (data[datalen-1] != '\0')
434 die();
436 if ((req = calloc(1, sizeof(*req))) == NULL)
437 die();
439 req->id = imsg->hdr.peerid;
440 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
442 if (!url_parse(imsg->data, &req->url, &e)) {
443 close_with_err(req, e);
444 return;
447 if ((req->fd = conn_towards(&req->url, &err)) == -1)
448 goto err;
449 if ((req->ctx = tls_client()) == NULL)
450 goto err;
451 if (tls_configure(req->ctx, tlsconf) == -1) {
452 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
453 goto err;
455 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
456 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
457 goto err;
460 yield_w(req, do_handshake, &timeout_for_handshake);
461 return;
463 err:
464 close_with_err(req, err);
465 free(err);
468 static void
469 handle_cert_status(struct imsg *imsg, size_t datalen)
471 struct req *req;
472 int is_ok;
474 req = req_by_id(imsg->hdr.peerid);
476 if (datalen < sizeof(is_ok))
477 die();
478 memcpy(&is_ok, imsg->data, sizeof(is_ok));
480 if (is_ok)
481 yield_w(req, write_request, NULL);
482 else
483 close_conn(0, 0, req);
486 static void
487 handle_proceed(struct imsg *imsg, size_t datalen)
489 yield_r(req_by_id(imsg->hdr.peerid),
490 copy_body, NULL);
493 static void
494 handle_stop(struct imsg *imsg, size_t datalen)
496 struct req *req;
498 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
499 return;
500 close_conn(0, 0, req);
503 static void
504 handle_quit(struct imsg *imsg, size_t datalen)
506 event_loopbreak();
509 static void
510 handle_dispatch_imsg(int fd, short ev, void *d)
512 struct imsgbuf *ibuf = d;
513 dispatch_imsg(ibuf, handlers, sizeof(handlers));
516 int
517 client_main(struct imsgbuf *b)
519 ibuf = b;
521 TAILQ_INIT(&reqhead);
523 if ((tlsconf = tls_config_new()) == NULL)
524 die();
525 tls_config_insecure_noverifycert(tlsconf);
527 event_init();
529 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
530 event_add(&imsgev, NULL);
532 sandbox_network_process();
534 event_dispatch();
535 return 0;