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;
253 char *e;
255 if (ev == EV_TIMEOUT) {
256 close_with_err(req, "Timeout loading page");
257 return;
260 switch (tls_handshake(req->ctx)) {
261 case TLS_WANT_POLLIN:
262 yield_r(req, do_handshake, NULL);
263 return;
264 case TLS_WANT_POLLOUT:
265 yield_w(req, do_handshake, NULL);
266 return;
269 hash = tls_peer_cert_hash(req->ctx);
270 if (hash == NULL) {
271 close_with_errf(req, "handshake failed: %s", tls_error(req->ctx));
272 return;
274 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
275 imsg_flush(ibuf);
278 static void
279 write_request(int fd, short ev, void *d)
281 struct req *req = d;
282 ssize_t r;
283 size_t len;
284 char buf[1024];
286 strlcpy(buf, "gemini://", sizeof(buf));
287 strlcat(buf, req->url.host, sizeof(buf));
288 strlcat(buf, "/", sizeof(buf));
289 strlcat(buf, req->url.path, sizeof(buf));
291 if (req->url.query[0] != '\0') {
292 strlcat(buf, "?", sizeof(buf));
293 strlcat(buf, req->url.query, sizeof(buf));
296 len = strlcat(buf, "\r\n", sizeof(buf));
298 assert(len <= sizeof(buf));
300 switch (r = tls_write(req->ctx, buf, len)) {
301 case -1:
302 close_with_errf(req, "tls_write: %s", tls_error(req->ctx));
303 break;
304 case TLS_WANT_POLLIN:
305 yield_r(req, write_request, NULL);
306 break;
307 case TLS_WANT_POLLOUT:
308 yield_w(req, write_request, NULL);
309 break;
310 default:
311 /* assume r == len */
312 (void)r;
313 yield_r(req, read_reply, NULL);
314 break;
318 static void
319 read_reply(int fd, short ev, void *d)
321 struct req *req = d;
322 size_t len;
323 ssize_t r;
324 char *buf;
326 buf = req->buf + req->off;
327 len = sizeof(req->buf) - req->off;
329 switch (r = tls_read(req->ctx, buf, len)) {
330 case -1:
331 close_with_errf(req, "tls_read: %s", tls_error(req->ctx));
332 break;
333 case TLS_WANT_POLLIN:
334 yield_r(req, read_reply, NULL);
335 break;
336 case TLS_WANT_POLLOUT:
337 yield_w(req, read_reply, NULL);
338 break;
339 default:
340 req->off += r;
342 /* TODO: really watch for \r\n not \n alone */
343 if (telescope_strnchr(req->buf, '\n', req->off) != NULL)
344 parse_reply(req);
345 else if (req->off == sizeof(req->buf))
346 close_with_err(req, "invalid response");
347 else
348 yield_r(req, read_reply, NULL);
349 break;
353 static void
354 parse_reply(struct req *req)
356 int code;
357 char *e;
358 size_t len;
360 if (req->off < 4)
361 goto err;
363 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
364 goto err;
366 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
368 if (!isspace(req->buf[2]))
369 goto err;
371 advance_buf(req, 3);
372 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
373 goto err;
375 *e = '\0';
376 e++;
377 len = e - req->buf;
378 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
379 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
380 req->buf, len);
381 imsg_flush(ibuf);
383 if (code != 20)
384 close_conn(0, 0, req);
385 advance_buf(req, len+1); /* skip \n too */
387 return;
389 err:
390 close_with_err(req, "malformed request");
393 static void
394 copy_body(int fd, short ev, void *d)
396 struct req *req = d;
397 ssize_t r;
399 for (;;) {
400 if (req->off != 0) {
401 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
402 req->buf, req->off);
403 imsg_flush(ibuf);
404 req->off = 0;
407 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
408 case TLS_WANT_POLLIN:
409 yield_r(req, copy_body, NULL);
410 return;
411 case TLS_WANT_POLLOUT:
412 yield_w(req, copy_body, NULL);
413 return;
414 case 0:
415 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
416 imsg_flush(ibuf);
417 close_conn(0, 0, req);
418 return;
419 default:
420 req->off = r;
425 static void
426 handle_get(struct imsg *imsg, size_t datalen)
428 struct req *req;
429 const char *e;
430 char *data, *err = NULL;
432 data = imsg->data;
434 if (data[datalen-1] != '\0')
435 die();
437 if ((req = calloc(1, sizeof(*req))) == NULL)
438 die();
440 req->id = imsg->hdr.peerid;
441 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
443 if (!url_parse(imsg->data, &req->url, &e)) {
444 close_with_err(req, e);
445 return;
448 if ((req->fd = conn_towards(&req->url, &err)) == -1)
449 goto err;
450 if ((req->ctx = tls_client()) == NULL)
451 goto err;
452 if (tls_configure(req->ctx, tlsconf) == -1) {
453 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
454 goto err;
456 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
457 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
458 goto err;
461 yield_w(req, do_handshake, &timeout_for_handshake);
462 return;
464 err:
465 close_with_err(req, err);
466 free(err);
469 static void
470 handle_cert_status(struct imsg *imsg, size_t datalen)
472 struct req *req;
473 int is_ok;
475 req = req_by_id(imsg->hdr.peerid);
477 if (datalen < sizeof(is_ok))
478 die();
479 memcpy(&is_ok, imsg->data, sizeof(is_ok));
481 if (is_ok)
482 yield_w(req, write_request, NULL);
483 else
484 close_conn(0, 0, req);
487 static void
488 handle_proceed(struct imsg *imsg, size_t datalen)
490 yield_r(req_by_id(imsg->hdr.peerid),
491 copy_body, NULL);
494 static void
495 handle_stop(struct imsg *imsg, size_t datalen)
497 struct req *req;
499 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
500 return;
501 close_conn(0, 0, req);
504 static void
505 handle_quit(struct imsg *imsg, size_t datalen)
507 event_loopbreak();
510 static void
511 handle_dispatch_imsg(int fd, short ev, void *d)
513 struct imsgbuf *ibuf = d;
514 dispatch_imsg(ibuf, handlers, sizeof(handlers));
517 int
518 client_main(struct imsgbuf *b)
520 ibuf = b;
522 TAILQ_INIT(&reqhead);
524 if ((tlsconf = tls_config_new()) == NULL)
525 die();
526 tls_config_insecure_noverifycert(tlsconf);
528 event_init();
530 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
531 event_add(&imsgev, NULL);
533 sandbox_network_process();
535 event_dispatch();
536 return 0;