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 *err);
54 static struct req *req_by_id(uint32_t);
55 static struct req *req_by_id_try(uint32_t);
57 static void do_handshake(int, short, void*);
58 static void write_request(int, short, void*);
59 static void read_reply(int, short, void*);
60 static void parse_reply(struct req*);
61 static void copy_body(int, short, void*);
63 static void handle_get(struct imsg*, size_t);
64 static void handle_cert_status(struct imsg*, size_t);
65 static void handle_proceed(struct imsg*, size_t);
66 static void handle_stop(struct imsg*, size_t);
67 static void handle_quit(struct imsg*, size_t);
69 /* TODO: making this customizable */
70 struct timeval timeout_for_handshake = { 5, 0 };
72 static imsg_handlerfn *handlers[] = {
73 [IMSG_GET] = handle_get,
74 [IMSG_CERT_STATUS] = handle_cert_status,
75 [IMSG_PROCEED] = handle_proceed,
76 [IMSG_STOP] = handle_stop,
77 [IMSG_QUIT] = handle_quit,
78 };
80 typedef void (*statefn)(int, short, void*);
82 TAILQ_HEAD(, req) reqhead;
83 /* a pending request */
84 struct req {
85 struct event ev;
86 struct url url;
87 uint32_t id;
88 int fd;
89 struct tls *ctx;
90 char buf[1024];
91 size_t off;
92 TAILQ_ENTRY(req) reqs;
93 };
95 static inline void
96 yield_r(struct req *req, statefn fn, struct timeval *tv)
97 {
98 event_once(req->fd, EV_READ, fn, req, tv);
99 }
101 static inline void
102 yield_w(struct req *req, statefn fn, struct timeval *tv)
104 event_once(req->fd, EV_WRITE, fn, req, tv);
107 static inline void
108 advance_buf(struct req *req, size_t len)
110 assert(len <= req->off);
112 req->off -= len;
113 memmove(req->buf, req->buf + len, req->off);
116 static void __attribute__((__noreturn__))
117 die(void)
119 abort(); /* TODO */
122 static char *
123 xasprintf(const char *fmt, ...)
125 va_list ap;
126 char *s;
128 va_start(ap, fmt);
129 if (vasprintf(&s, fmt, ap) == -1)
130 s = NULL;
131 va_end(ap);
133 return s;
136 static int
137 conn_towards(struct url *url, char **err)
139 struct addrinfo hints, *servinfo, *p;
140 int status, sock;
141 const char *proto = "1965";
143 *err = NULL;
145 if (*url->port != '\0')
146 proto = url->port;
148 memset(&hints, 0, sizeof(hints));
149 hints.ai_family = AF_UNSPEC;
150 hints.ai_socktype = SOCK_STREAM;
152 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
153 *err = xasprintf("failed to resolve %s: %s",
154 url->host, gai_strerror(status));
155 return -1;
158 sock = -1;
159 for (p = servinfo; p != NULL; p = p->ai_next) {
160 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
161 continue;
162 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
163 break;
164 close(sock);
167 if (sock == -1)
168 *err = xasprintf("couldn't connect to %s", url->host);
169 else
170 mark_nonblock(sock);
172 freeaddrinfo(servinfo);
173 return sock;
176 static struct req *
177 req_by_id(uint32_t id)
179 struct req *r;
181 if ((r = req_by_id_try(id)) == NULL)
182 die();
183 return r;
186 static struct req *
187 req_by_id_try(uint32_t id)
189 struct req *r;
191 TAILQ_FOREACH(r, &reqhead, reqs) {
192 if (r->id == id)
193 return r;
196 return NULL;
199 static void
200 close_conn(int fd, short ev, void *d)
202 struct req *req = d;
204 if (req->ctx != NULL) {
205 switch (tls_close(req->ctx)) {
206 case TLS_WANT_POLLIN:
207 yield_r(req, close_conn, NULL);
208 return;
209 case TLS_WANT_POLLOUT:
210 yield_w(req, close_conn, NULL);
211 return;
214 tls_free(req->ctx);
217 TAILQ_REMOVE(&reqhead, req, reqs);
218 if (req->fd != -1)
219 close(req->fd);
220 free(req);
223 static void
224 close_with_err(struct req *req, const char *err)
226 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
227 imsg_flush(ibuf);
228 close_conn(0, 0, req);
231 static void
232 do_handshake(int fd, short ev, void *d)
234 struct req *req = d;
235 const char *hash;
237 if (ev == EV_TIMEOUT) {
238 close_with_err(req, "Timeout loading page");
239 return;
242 switch (tls_handshake(req->ctx)) {
243 case TLS_WANT_POLLIN:
244 yield_r(req, do_handshake, NULL);
245 return;
246 case TLS_WANT_POLLOUT:
247 yield_w(req, do_handshake, NULL);
248 return;
251 hash = tls_peer_cert_hash(req->ctx);
252 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
253 imsg_flush(ibuf);
256 static void
257 write_request(int fd, short ev, void *d)
259 struct req *req = d;
260 ssize_t r;
261 size_t len;
262 char buf[1024], *err;
264 strlcpy(buf, "gemini://", sizeof(buf));
265 strlcat(buf, req->url.host, sizeof(buf));
266 strlcat(buf, "/", sizeof(buf));
267 strlcat(buf, req->url.path, sizeof(buf));
269 if (req->url.query[0] != '\0') {
270 strlcat(buf, "?", sizeof(buf));
271 strlcat(buf, req->url.query, sizeof(buf));
274 len = strlcat(buf, "\r\n", sizeof(buf));
276 assert(len <= sizeof(buf));
278 switch (r = tls_write(req->ctx, buf, len)) {
279 case -1:
280 err = xasprintf("tls_write: %s", tls_error(req->ctx));
281 close_with_err(req, err);
282 free(err);
283 break;
284 case TLS_WANT_POLLIN:
285 yield_r(req, write_request, NULL);
286 break;
287 case TLS_WANT_POLLOUT:
288 yield_w(req, write_request, NULL);
289 break;
290 default:
291 /* assume r == len */
292 (void)r;
293 yield_r(req, read_reply, NULL);
294 break;
298 static void
299 read_reply(int fd, short ev, void *d)
301 struct req *req = d;
302 size_t len;
303 ssize_t r;
304 char *buf, *e;
306 buf = req->buf + req->off;
307 len = sizeof(req->buf) - req->off;
309 switch (r = tls_read(req->ctx, buf, len)) {
310 case -1:
311 e = xasprintf("tls_read: %s", tls_error(req->ctx));
312 close_with_err(req, e);
313 free(e);
314 break;
315 case TLS_WANT_POLLIN:
316 yield_r(req, read_reply, NULL);
317 break;
318 case TLS_WANT_POLLOUT:
319 yield_w(req, read_reply, NULL);
320 break;
321 default:
322 req->off += r;
324 /* TODO: really watch for \r\n not \n alone */
325 if ((e = telescope_strnchr(req->buf, '\n', req->off)) != NULL)
326 parse_reply(req);
327 else if (req->off == sizeof(req->buf))
328 close_with_err(req, "invalid response");
329 else
330 yield_r(req, read_reply, NULL);
331 break;
335 static void
336 parse_reply(struct req *req)
338 int code;
339 char *e;
340 size_t len;
342 if (req->off < 4)
343 goto err;
345 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
346 goto err;
348 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
350 if (!isspace(req->buf[2]))
351 goto err;
353 advance_buf(req, 3);
354 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
355 goto err;
357 *e = '\0';
358 e++;
359 len = e - req->buf;
360 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
361 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
362 req->buf, len);
363 imsg_flush(ibuf);
365 if (code != 20)
366 close_conn(0, 0, req);
367 advance_buf(req, len+1); /* skip \n too */
369 return;
371 err:
372 close_with_err(req, "malformed request");
375 static void
376 copy_body(int fd, short ev, void *d)
378 struct req *req = d;
379 ssize_t r;
381 for (;;) {
382 if (req->off != 0) {
383 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1,
384 req->buf, req->off);
385 imsg_flush(ibuf);
386 req->off = 0;
389 switch (r = tls_read(req->ctx, req->buf, sizeof(req->buf))) {
390 case TLS_WANT_POLLIN:
391 yield_r(req, copy_body, NULL);
392 return;
393 case TLS_WANT_POLLOUT:
394 yield_w(req, copy_body, NULL);
395 return;
396 case 0:
397 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
398 imsg_flush(ibuf);
399 close_conn(0, 0, req);
400 return;
401 default:
402 req->off = r;
407 static void
408 handle_get(struct imsg *imsg, size_t datalen)
410 struct req *req;
411 const char *e;
412 char *data, *err = NULL;
414 data = imsg->data;
416 if (data[datalen-1] != '\0')
417 die();
419 if ((req = calloc(1, sizeof(*req))) == NULL)
420 die();
422 req->id = imsg->hdr.peerid;
423 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
425 if (!url_parse(imsg->data, &req->url, &e)) {
426 close_with_err(req, e);
427 return;
430 if ((req->fd = conn_towards(&req->url, &err)) == -1)
431 goto err;
432 if ((req->ctx = tls_client()) == NULL)
433 goto err;
434 if (tls_configure(req->ctx, tlsconf) == -1) {
435 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
436 goto err;
438 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
439 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
440 goto err;
443 yield_w(req, do_handshake, &timeout_for_handshake);
444 return;
446 err:
447 close_with_err(req, err);
448 free(err);
451 static void
452 handle_cert_status(struct imsg *imsg, size_t datalen)
454 struct req *req;
455 int is_ok;
457 req = req_by_id(imsg->hdr.peerid);
459 if (datalen < sizeof(is_ok))
460 die();
461 memcpy(&is_ok, imsg->data, sizeof(is_ok));
463 if (is_ok)
464 yield_w(req, write_request, NULL);
465 else
466 close_conn(0, 0, req);
469 static void
470 handle_proceed(struct imsg *imsg, size_t datalen)
472 yield_r(req_by_id(imsg->hdr.peerid),
473 copy_body, NULL);
476 static void
477 handle_stop(struct imsg *imsg, size_t datalen)
479 struct req *req;
481 if ((req = req_by_id_try(imsg->hdr.peerid)) == NULL)
482 return;
483 close_conn(0, 0, req);
486 static void
487 handle_quit(struct imsg *imsg, size_t datalen)
489 event_loopbreak();
492 static void
493 dispatch_imsg(int fd, short ev, void *d)
495 struct imsgbuf *ibuf = d;
496 struct imsg imsg;
497 ssize_t n;
498 size_t datalen;
500 if ((n = imsg_read(ibuf)) == -1) {
501 if (errno == EAGAIN || errno == EWOULDBLOCK)
502 return;
503 _exit(1);
506 if (n == 0)
507 _exit(1);
509 for (;;) {
510 if ((n = imsg_get(ibuf, &imsg)) == -1)
511 _exit(1);
512 if (n == 0)
513 return;
514 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
515 handlers[imsg.hdr.type](&imsg, datalen);
516 imsg_free(&imsg);
520 int
521 client_main(struct imsgbuf *b)
523 ibuf = b;
525 TAILQ_INIT(&reqhead);
527 if ((tlsconf = tls_config_new()) == NULL)
528 die();
529 tls_config_insecure_noverifycert(tlsconf);
531 event_init();
533 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, dispatch_imsg, ibuf);
534 event_add(&imsgev, NULL);
536 sandbox_network_process();
538 event_dispatch();
539 return 0;