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 static imsg_handlerfn *handlers[] = {
71 [IMSG_GET] = handle_get,
72 [IMSG_CERT_STATUS] = handle_cert_status,
73 [IMSG_PROCEED] = handle_proceed,
74 [IMSG_STOP] = handle_stop,
75 [IMSG_QUIT] = handle_quit,
76 };
78 typedef void (*statefn)(int, short, void*);
80 TAILQ_HEAD(, req) reqhead;
81 /* a pending request */
82 struct req {
83 struct event ev;
84 struct url url;
85 uint32_t id;
86 int fd;
87 struct tls *ctx;
88 char buf[1024];
89 size_t off;
90 TAILQ_ENTRY(req) reqs;
91 };
93 static inline void
94 yield_r(struct req *req, statefn fn, struct timeval *tv)
95 {
96 event_once(req->fd, EV_READ, fn, req, tv);
97 }
99 static inline void
100 yield_w(struct req *req, statefn fn, struct timeval *tv)
102 event_once(req->fd, EV_WRITE, fn, req, tv);
105 static inline void
106 advance_buf(struct req *req, size_t len)
108 assert(len <= req->off);
110 req->off -= len;
111 memmove(req->buf, req->buf + len, req->off);
114 static void __attribute__((__noreturn__))
115 die(void)
117 abort(); /* TODO */
120 static char *
121 xasprintf(const char *fmt, ...)
123 va_list ap;
124 char *s;
126 va_start(ap, fmt);
127 if (vasprintf(&s, fmt, ap) == -1)
128 s = NULL;
129 va_end(ap);
131 return s;
134 static int
135 conn_towards(struct url *url, char **err)
137 struct addrinfo hints, *servinfo, *p;
138 int status, sock;
139 const char *proto = "1965";
141 *err = NULL;
143 if (*url->port != '\0')
144 proto = url->port;
146 memset(&hints, 0, sizeof(hints));
147 hints.ai_family = AF_UNSPEC;
148 hints.ai_socktype = SOCK_STREAM;
150 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
151 *err = xasprintf("failed to resolve %s: %s",
152 url->host, gai_strerror(status));
153 return -1;
156 sock = -1;
157 for (p = servinfo; p != NULL; p = p->ai_next) {
158 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
159 continue;
160 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
161 break;
162 close(sock);
165 if (sock == -1)
166 *err = xasprintf("couldn't connect to %s", url->host);
167 else
168 mark_nonblock(sock);
170 freeaddrinfo(servinfo);
171 return sock;
174 static struct req *
175 req_by_id(uint32_t id)
177 struct req *r;
179 TAILQ_FOREACH(r, &reqhead, reqs) {
180 if (r->id == id)
181 return r;
184 die();
187 static void
188 close_conn(int fd, short ev, void *d)
190 struct req *req = d;
192 if (req->ctx != NULL) {
193 switch (tls_close(req->ctx)) {
194 case TLS_WANT_POLLIN:
195 yield_r(req, close_conn, NULL);
196 return;
197 case TLS_WANT_POLLOUT:
198 yield_w(req, close_conn, NULL);
199 return;
202 tls_free(req->ctx);
205 TAILQ_REMOVE(&reqhead, req, reqs);
206 if (req->fd != -1)
207 close(req->fd);
208 free(req);
211 static void
212 close_with_err(struct req *req, const char *err)
214 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
215 imsg_flush(ibuf);
216 close_conn(0, 0, req);
219 static void
220 do_handshake(int fd, short ev, void *d)
222 struct req *req = d;
223 const char *hash;
225 switch (tls_handshake(req->ctx)) {
226 case TLS_WANT_POLLIN:
227 yield_r(req, do_handshake, NULL);
228 return;
229 case TLS_WANT_POLLOUT:
230 yield_w(req, do_handshake, NULL);
231 return;
234 hash = tls_peer_cert_hash(req->ctx);
235 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
236 imsg_flush(ibuf);
239 static void
240 write_request(int fd, short ev, void *d)
242 struct req *req = d;
243 ssize_t r;
244 size_t len;
245 char buf[1024], *err;
247 strlcpy(buf, "gemini://", sizeof(buf));
248 strlcat(buf, req->url.host, sizeof(buf));
249 strlcat(buf, "/", sizeof(buf));
250 strlcat(buf, req->url.path, sizeof(buf));
252 if (req->url.query[0] != '\0') {
253 strlcat(buf, "?", sizeof(buf));
254 strlcat(buf, req->url.query, sizeof(buf));
257 len = strlcat(buf, "\r\n", sizeof(buf));
259 assert(len <= sizeof(buf));
261 switch (r = tls_write(req->ctx, buf, len)) {
262 case -1:
263 err = xasprintf("tls_write: %s", tls_error(req->ctx));
264 close_with_err(req, err);
265 free(err);
266 break;
267 case TLS_WANT_POLLIN:
268 yield_r(req, write_request, NULL);
269 break;
270 case TLS_WANT_POLLOUT:
271 yield_w(req, write_request, NULL);
272 break;
273 default:
274 /* assume r == len */
275 (void)r;
276 yield_r(req, read_reply, NULL);
277 break;
281 static void
282 read_reply(int fd, short ev, void *d)
284 struct req *req = d;
285 size_t len;
286 ssize_t r;
287 char *buf, *e;
289 buf = req->buf + req->off;
290 len = sizeof(req->buf) - req->off;
292 switch (r = tls_read(req->ctx, buf, len)) {
293 case -1:
294 e = xasprintf("tls_read: %s", tls_error(req->ctx));
295 close_with_err(req, e);
296 free(e);
297 break;
298 case TLS_WANT_POLLIN:
299 yield_r(req, read_reply, NULL);
300 break;
301 case TLS_WANT_POLLOUT:
302 yield_w(req, read_reply, NULL);
303 break;
304 default:
305 req->off += r;
307 /* TODO: really watch for \r\n not \n alone */
308 if ((e = telescope_strnchr(req->buf, '\n', req->off)) != NULL)
309 parse_reply(req);
310 else if (req->off == sizeof(req->buf))
311 close_with_err(req, "invalid response");
312 else
313 yield_r(req, read_reply, NULL);
314 break;
318 static void
319 parse_reply(struct req *req)
321 int code;
322 char *e;
323 size_t len;
325 if (req->off < 4)
326 goto err;
328 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
329 goto err;
331 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
333 if (!isspace(req->buf[2]))
334 goto err;
336 advance_buf(req, 3);
337 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
338 goto err;
340 *e = '\0';
341 e++;
342 len = e - req->buf;
343 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
344 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
345 req->buf, len);
346 imsg_flush(ibuf);
348 return;
350 err:
351 close_with_err(req, "malformed request");
354 static void
355 copy_body(int fd, short ev, void *d)
357 struct req *req = d;
358 char buf[BUFSIZ];
359 ssize_t r;
361 for (;;) {
362 switch (r = tls_read(req->ctx, buf, sizeof(buf))) {
363 case TLS_WANT_POLLIN:
364 yield_r(req, copy_body, NULL);
365 return;
366 case TLS_WANT_POLLOUT:
367 yield_w(req, copy_body, NULL);
368 return;
369 case -1:
370 case 0:
371 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
372 imsg_flush(ibuf);
373 close_conn(0, 0, req);
374 return;
375 default:
376 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1, buf, r);
377 imsg_flush(ibuf);
378 break;
383 static void
384 handle_get(struct imsg *imsg, size_t datalen)
386 struct req *req;
387 const char *e;
388 char *data, *err = NULL;
390 data = imsg->data;
392 if (data[datalen-1] != '\0')
393 die();
395 if ((req = calloc(1, sizeof(*req))) == NULL)
396 die();
398 req->id = imsg->hdr.peerid;
400 if (!url_parse(imsg->data, &req->url, &e)) {
401 fprintf(stderr, "failed to parse url: %s\n", e);
402 close_with_err(req, e);
403 return;
406 if ((req->fd = conn_towards(&req->url, &err)) == -1)
407 goto err;
408 if ((req->ctx = tls_client()) == NULL)
409 goto err;
410 if (tls_configure(req->ctx, tlsconf) == -1) {
411 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
412 goto err;
414 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
415 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
416 goto err;
419 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
420 yield_w(req, do_handshake, NULL);
421 return;
423 err:
424 close_with_err(req, err);
425 free(err);
428 static void
429 handle_cert_status(struct imsg *imsg, size_t datalen)
431 struct req *req;
432 int is_ok;
434 req = req_by_id(imsg->hdr.peerid);
436 if (datalen < sizeof(is_ok))
437 die();
438 memcpy(&is_ok, imsg->data, sizeof(is_ok));
440 if (is_ok)
441 yield_w(req, write_request, NULL);
442 else
443 close_conn(0, 0, req);
446 static void
447 handle_proceed(struct imsg *imsg, size_t datalen)
449 struct req *req;
451 req = req_by_id(imsg->hdr.peerid);
452 yield_r(req, copy_body, NULL);
455 static void
456 handle_stop(struct imsg *imsg, size_t datalen)
458 struct req *req;
460 req = req_by_id(imsg->hdr.peerid);
461 close_conn(0, 0, req);
464 static void
465 handle_quit(struct imsg *imsg, size_t datalen)
467 event_loopbreak();
470 static void
471 dispatch_imsg(int fd, short ev, void *d)
473 struct imsgbuf *ibuf = d;
474 struct imsg imsg;
475 ssize_t n;
476 size_t datalen;
478 if ((n = imsg_read(ibuf)) == -1) {
479 if (errno == EAGAIN || errno == EWOULDBLOCK)
480 return;
481 die();
484 if (n == 0)
485 die();
487 for (;;) {
488 if ((n = imsg_get(ibuf, &imsg)) == -1)
489 die();
490 if (n == 0)
491 return;
492 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
493 handlers[imsg.hdr.type](&imsg, datalen);
494 imsg_free(&imsg);
498 int
499 client_main(struct imsgbuf *b)
501 ibuf = b;
503 TAILQ_INIT(&reqhead);
505 if ((tlsconf = tls_config_new()) == NULL)
506 die();
507 tls_config_insecure_noverifycert(tlsconf);
509 event_init();
511 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, dispatch_imsg, ibuf);
512 event_add(&imsgev, NULL);
514 event_dispatch();
515 return 0;