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 <event.h>
36 #include <netdb.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <tls.h>
42 #include <unistd.h>
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 *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_proceed(struct imsg*, size_t);
67 static void handle_stop(struct imsg*, size_t);
68 static void handle_quit(struct imsg*, size_t);
70 /* TODO: making this customizable */
71 struct timeval timeout_for_handshake = { 5, 0 };
73 static imsg_handlerfn *handlers[] = {
74 [IMSG_GET] = handle_get,
75 [IMSG_CERT_STATUS] = handle_cert_status,
76 [IMSG_PROCEED] = handle_proceed,
77 [IMSG_STOP] = handle_stop,
78 [IMSG_QUIT] = handle_quit,
79 };
81 typedef void (*statefn)(int, short, void*);
83 TAILQ_HEAD(, req) reqhead;
84 /* a pending request */
85 struct req {
86 struct event ev;
87 struct url url;
88 uint32_t id;
89 int fd;
90 struct tls *ctx;
91 char buf[1024];
92 size_t off;
93 TAILQ_ENTRY(req) reqs;
94 };
96 static inline void
97 yield_r(struct req *req, statefn fn, struct timeval *tv)
98 {
99 event_once(req->fd, EV_READ, fn, req, tv);
102 static inline void
103 yield_w(struct req *req, statefn fn, struct timeval *tv)
105 event_once(req->fd, EV_WRITE, fn, req, tv);
108 static inline void
109 advance_buf(struct req *req, size_t len)
111 assert(len <= req->off);
113 req->off -= len;
114 memmove(req->buf, req->buf + len, req->off);
117 static void __attribute__((__noreturn__))
118 die(void)
120 abort(); /* TODO */
123 static char *
124 xasprintf(const char *fmt, ...)
126 va_list ap;
127 char *s;
129 va_start(ap, fmt);
130 if (vasprintf(&s, fmt, ap) == -1)
131 s = NULL;
132 va_end(ap);
134 return s;
137 static int
138 conn_towards(struct url *url, char **err)
140 struct addrinfo hints, *servinfo, *p;
141 int status, sock;
142 const char *proto = "1965";
144 *err = NULL;
146 if (*url->port != '\0')
147 proto = url->port;
149 memset(&hints, 0, sizeof(hints));
150 hints.ai_family = AF_UNSPEC;
151 hints.ai_socktype = SOCK_STREAM;
153 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
154 *err = xasprintf("failed to resolve %s: %s",
155 url->host, gai_strerror(status));
156 return -1;
159 sock = -1;
160 for (p = servinfo; p != NULL; p = p->ai_next) {
161 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
162 continue;
163 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
164 break;
165 close(sock);
168 if (sock == -1)
169 *err = xasprintf("couldn't connect to %s", url->host);
170 else
171 mark_nonblock(sock);
173 freeaddrinfo(servinfo);
174 return sock;
177 static struct req *
178 req_by_id(uint32_t id)
180 struct req *r;
182 TAILQ_FOREACH(r, &reqhead, reqs) {
183 if (r->id == id)
184 return r;
187 die();
190 static void
191 close_conn(int fd, short ev, void *d)
193 struct req *req = d;
195 if (req->ctx != NULL) {
196 switch (tls_close(req->ctx)) {
197 case TLS_WANT_POLLIN:
198 yield_r(req, close_conn, NULL);
199 return;
200 case TLS_WANT_POLLOUT:
201 yield_w(req, close_conn, NULL);
202 return;
205 tls_free(req->ctx);
208 TAILQ_REMOVE(&reqhead, req, reqs);
209 if (req->fd != -1)
210 close(req->fd);
211 free(req);
214 static void
215 close_with_err(struct req *req, const char *err)
217 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
218 imsg_flush(ibuf);
219 close_conn(0, 0, req);
222 static void
223 do_handshake(int fd, short ev, void *d)
225 struct req *req = d;
226 const char *hash;
228 if (ev == EV_TIMEOUT) {
229 close_with_err(req, "Timeout loading page");
230 return;
233 switch (tls_handshake(req->ctx)) {
234 case TLS_WANT_POLLIN:
235 yield_r(req, do_handshake, NULL);
236 return;
237 case TLS_WANT_POLLOUT:
238 yield_w(req, do_handshake, NULL);
239 return;
242 hash = tls_peer_cert_hash(req->ctx);
243 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
244 imsg_flush(ibuf);
247 static void
248 write_request(int fd, short ev, void *d)
250 struct req *req = d;
251 ssize_t r;
252 size_t len;
253 char buf[1024], *err;
255 strlcpy(buf, "gemini://", sizeof(buf));
256 strlcat(buf, req->url.host, sizeof(buf));
257 strlcat(buf, "/", sizeof(buf));
258 strlcat(buf, req->url.path, sizeof(buf));
260 if (req->url.query[0] != '\0') {
261 strlcat(buf, "?", sizeof(buf));
262 strlcat(buf, req->url.query, sizeof(buf));
265 len = strlcat(buf, "\r\n", sizeof(buf));
267 assert(len <= sizeof(buf));
269 switch (r = tls_write(req->ctx, buf, len)) {
270 case -1:
271 err = xasprintf("tls_write: %s", tls_error(req->ctx));
272 close_with_err(req, err);
273 free(err);
274 break;
275 case TLS_WANT_POLLIN:
276 yield_r(req, write_request, NULL);
277 break;
278 case TLS_WANT_POLLOUT:
279 yield_w(req, write_request, NULL);
280 break;
281 default:
282 /* assume r == len */
283 (void)r;
284 yield_r(req, read_reply, NULL);
285 break;
289 static void
290 read_reply(int fd, short ev, void *d)
292 struct req *req = d;
293 size_t len;
294 ssize_t r;
295 char *buf, *e;
297 buf = req->buf + req->off;
298 len = sizeof(req->buf) - req->off;
300 switch (r = tls_read(req->ctx, buf, len)) {
301 case -1:
302 e = xasprintf("tls_read: %s", tls_error(req->ctx));
303 close_with_err(req, e);
304 free(e);
305 break;
306 case TLS_WANT_POLLIN:
307 yield_r(req, read_reply, NULL);
308 break;
309 case TLS_WANT_POLLOUT:
310 yield_w(req, read_reply, NULL);
311 break;
312 default:
313 req->off += r;
315 /* TODO: really watch for \r\n not \n alone */
316 if ((e = telescope_strnchr(req->buf, '\n', req->off)) != NULL)
317 parse_reply(req);
318 else if (req->off == sizeof(req->buf))
319 close_with_err(req, "invalid response");
320 else
321 yield_r(req, read_reply, NULL);
322 break;
326 static void
327 parse_reply(struct req *req)
329 int code;
330 char *e;
331 size_t len;
333 if (req->off < 4)
334 goto err;
336 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
337 goto err;
339 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
341 if (!isspace(req->buf[2]))
342 goto err;
344 advance_buf(req, 3);
345 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
346 goto err;
348 *e = '\0';
349 e++;
350 len = e - req->buf;
351 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
352 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
353 req->buf, len);
354 imsg_flush(ibuf);
356 if (code != 20)
357 close_conn(0, 0, req);
359 return;
361 err:
362 close_with_err(req, "malformed request");
365 static void
366 copy_body(int fd, short ev, void *d)
368 struct req *req = d;
369 char buf[BUFSIZ];
370 ssize_t r;
372 for (;;) {
373 switch (r = tls_read(req->ctx, buf, sizeof(buf))) {
374 case TLS_WANT_POLLIN:
375 yield_r(req, copy_body, NULL);
376 return;
377 case TLS_WANT_POLLOUT:
378 yield_w(req, copy_body, NULL);
379 return;
380 case -1:
381 case 0:
382 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
383 imsg_flush(ibuf);
384 close_conn(0, 0, req);
385 return;
386 default:
387 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1, buf, r);
388 imsg_flush(ibuf);
389 break;
394 static void
395 handle_get(struct imsg *imsg, size_t datalen)
397 struct req *req;
398 const char *e;
399 char *data, *err = NULL;
401 data = imsg->data;
403 if (data[datalen-1] != '\0')
404 die();
406 if ((req = calloc(1, sizeof(*req))) == NULL)
407 die();
409 req->id = imsg->hdr.peerid;
411 if (!url_parse(imsg->data, &req->url, &e)) {
412 fprintf(stderr, "failed to parse url: %s\n", e);
413 close_with_err(req, e);
414 return;
417 if ((req->fd = conn_towards(&req->url, &err)) == -1)
418 goto err;
419 if ((req->ctx = tls_client()) == NULL)
420 goto err;
421 if (tls_configure(req->ctx, tlsconf) == -1) {
422 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
423 goto err;
425 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
426 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
427 goto err;
430 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
431 yield_w(req, do_handshake, &timeout_for_handshake);
432 return;
434 err:
435 close_with_err(req, err);
436 free(err);
439 static void
440 handle_cert_status(struct imsg *imsg, size_t datalen)
442 struct req *req;
443 int is_ok;
445 req = req_by_id(imsg->hdr.peerid);
447 if (datalen < sizeof(is_ok))
448 die();
449 memcpy(&is_ok, imsg->data, sizeof(is_ok));
451 if (is_ok)
452 yield_w(req, write_request, NULL);
453 else
454 close_conn(0, 0, req);
457 static void
458 handle_proceed(struct imsg *imsg, size_t datalen)
460 struct req *req;
462 req = req_by_id(imsg->hdr.peerid);
463 yield_r(req, copy_body, NULL);
466 static void
467 handle_stop(struct imsg *imsg, size_t datalen)
469 struct req *req;
471 req = req_by_id(imsg->hdr.peerid);
472 close_conn(0, 0, req);
475 static void
476 handle_quit(struct imsg *imsg, size_t datalen)
478 event_loopbreak();
481 static void
482 dispatch_imsg(int fd, short ev, void *d)
484 struct imsgbuf *ibuf = d;
485 struct imsg imsg;
486 ssize_t n;
487 size_t datalen;
489 if ((n = imsg_read(ibuf)) == -1) {
490 if (errno == EAGAIN || errno == EWOULDBLOCK)
491 return;
492 _exit(1);
495 if (n == 0)
496 _exit(1);
498 for (;;) {
499 if ((n = imsg_get(ibuf, &imsg)) == -1)
500 _exit(1);
501 if (n == 0)
502 return;
503 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
504 handlers[imsg.hdr.type](&imsg, datalen);
505 imsg_free(&imsg);
509 int
510 client_main(struct imsgbuf *b)
512 ibuf = b;
514 TAILQ_INIT(&reqhead);
516 if ((tlsconf = tls_config_new()) == NULL)
517 die();
518 tls_config_insecure_noverifycert(tlsconf);
520 event_init();
522 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, dispatch_imsg, ibuf);
523 event_add(&imsgev, NULL);
525 event_dispatch();
526 return 0;