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_stop(struct imsg*, size_t);
67 static void handle_quit(struct imsg*, size_t);
69 static imsg_handlerfn *handlers[] = {
70 [IMSG_GET] = handle_get,
71 [IMSG_CERT_STATUS] = handle_cert_status,
72 [IMSG_STOP] = handle_stop,
73 [IMSG_QUIT] = handle_quit,
74 };
76 typedef void (*statefn)(int, short, void*);
78 TAILQ_HEAD(, req) reqhead;
79 /* a pending request */
80 struct req {
81 struct event ev;
82 struct url url;
83 uint32_t id;
84 int fd;
85 struct tls *ctx;
86 char buf[1024];
87 size_t off;
88 TAILQ_ENTRY(req) reqs;
89 };
91 static inline void
92 yield_r(struct req *req, statefn fn, struct timeval *tv)
93 {
94 event_once(req->fd, EV_READ, fn, req, tv);
95 }
97 static inline void
98 yield_w(struct req *req, statefn fn, struct timeval *tv)
99 {
100 event_once(req->fd, EV_WRITE, fn, req, tv);
103 static inline void
104 advance_buf(struct req *req, size_t len)
106 assert(len <= req->off);
108 req->off -= len;
109 memmove(req->buf, req->buf + len, req->off);
112 static void __attribute__((__noreturn__))
113 die(void)
115 abort(); /* TODO */
118 static char *
119 xasprintf(const char *fmt, ...)
121 va_list ap;
122 char *s;
124 va_start(ap, fmt);
125 if (vasprintf(&s, fmt, ap) == -1)
126 s = NULL;
127 va_end(ap);
129 return s;
132 static int
133 conn_towards(struct url *url, char **err)
135 struct addrinfo hints, *servinfo, *p;
136 int status, sock;
137 const char *proto = "1965";
139 *err = NULL;
141 if (*url->port != '\0')
142 proto = url->port;
144 memset(&hints, 0, sizeof(hints));
145 hints.ai_family = AF_UNSPEC;
146 hints.ai_socktype = SOCK_STREAM;
148 if ((status = getaddrinfo(url->host, proto, &hints, &servinfo))) {
149 *err = xasprintf("failed to resolve %s: %s",
150 url->host, gai_strerror(status));
151 return -1;
154 sock = -1;
155 for (p = servinfo; p != NULL; p = p->ai_next) {
156 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
157 continue;
158 if (connect(sock, p->ai_addr, p->ai_addrlen) != -1)
159 break;
160 close(sock);
163 if (sock == -1)
164 *err = xasprintf("couldn't connect to %s", url->host);
165 else
166 mark_nonblock(sock);
168 freeaddrinfo(servinfo);
169 return sock;
172 static struct req *
173 req_by_id(uint32_t id)
175 struct req *r;
177 TAILQ_FOREACH(r, &reqhead, reqs) {
178 if (r->id == id)
179 return r;
182 die();
185 static void
186 close_conn(int fd, short ev, void *d)
188 struct req *req = d;
190 if (req->ctx != NULL) {
191 switch (tls_close(req->ctx)) {
192 case TLS_WANT_POLLIN:
193 yield_r(req, close_conn, NULL);
194 return;
195 case TLS_WANT_POLLOUT:
196 yield_w(req, close_conn, NULL);
197 return;
200 tls_free(req->ctx);
203 TAILQ_REMOVE(&reqhead, req, reqs);
204 if (req->fd != -1)
205 close(req->fd);
206 free(req);
209 static void
210 close_with_err(struct req *req, const char *err)
212 imsg_compose(ibuf, IMSG_ERR, req->id, 0, -1, err, strlen(err)+1);
213 imsg_flush(ibuf);
214 close_conn(0, 0, req);
217 static void
218 do_handshake(int fd, short ev, void *d)
220 struct req *req = d;
221 const char *hash;
223 switch (tls_handshake(req->ctx)) {
224 case TLS_WANT_POLLIN:
225 yield_r(req, do_handshake, NULL);
226 return;
227 case TLS_WANT_POLLOUT:
228 yield_w(req, do_handshake, NULL);
229 return;
232 hash = tls_peer_cert_hash(req->ctx);
233 imsg_compose(ibuf, IMSG_CHECK_CERT, req->id, 0, -1, hash, strlen(hash)+1);
234 imsg_flush(ibuf);
237 static void
238 write_request(int fd, short ev, void *d)
240 struct req *req = d;
241 ssize_t r;
242 size_t len;
243 char buf[1024], *err;
245 strlcpy(buf, "gemini://", sizeof(buf));
246 strlcat(buf, req->url.host, sizeof(buf));
247 strlcat(buf, "/", sizeof(buf));
248 strlcat(buf, req->url.path, sizeof(buf));
250 if (req->url.query[0] != '\0') {
251 strlcat(buf, "?", sizeof(buf));
252 strlcat(buf, req->url.query, sizeof(buf));
255 len = strlcat(buf, "\r\n", sizeof(buf));
257 assert(len <= sizeof(buf));
259 switch (r = tls_write(req->ctx, buf, len)) {
260 case -1:
261 err = xasprintf("tls_write: %s", tls_error(req->ctx));
262 close_with_err(req, err);
263 free(err);
264 break;
265 case TLS_WANT_POLLIN:
266 yield_r(req, write_request, NULL);
267 break;
268 case TLS_WANT_POLLOUT:
269 yield_w(req, write_request, NULL);
270 break;
271 default:
272 /* assume r == len */
273 (void)r;
274 yield_r(req, read_reply, NULL);
275 break;
279 static void
280 read_reply(int fd, short ev, void *d)
282 struct req *req = d;
283 size_t len;
284 ssize_t r;
285 char *buf, *e;
287 buf = req->buf + req->off;
288 len = sizeof(req->buf) - req->off;
290 switch (r = tls_read(req->ctx, buf, len)) {
291 case -1:
292 e = xasprintf("tls_read: %s", tls_error(req->ctx));
293 close_with_err(req, e);
294 free(e);
295 break;
296 case TLS_WANT_POLLIN:
297 yield_r(req, read_reply, NULL);
298 break;
299 case TLS_WANT_POLLOUT:
300 yield_w(req, read_reply, NULL);
301 break;
302 default:
303 req->off += r;
305 /* TODO: really watch for \r\n not \n alone */
306 if ((e = telescope_strnchr(req->buf, '\n', req->off)) != NULL)
307 parse_reply(req);
308 else if (req->off == sizeof(req->buf))
309 close_with_err(req, "invalid response");
310 else
311 yield_r(req, read_reply, NULL);
312 break;
316 static void
317 parse_reply(struct req *req)
319 int code;
320 char *e;
321 size_t len;
323 if (req->off < 4)
324 goto err;
326 if (!isdigit(req->buf[0]) || !isdigit(req->buf[1]))
327 goto err;
329 code = (req->buf[0] - '0')*10 + (req->buf[1] - '0');
331 if (!isspace(req->buf[2]))
332 goto err;
334 advance_buf(req, 3);
335 if ((e = telescope_strnchr(req->buf, '\r', req->off)) == NULL)
336 goto err;
338 *e = '\0';
339 e++;
340 len = e - req->buf;
341 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
342 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1,
343 req->buf, len);
344 imsg_flush(ibuf);
346 yield_r(req, copy_body, NULL);
347 return;
349 err:
350 close_with_err(req, "malformed request");
353 static void
354 copy_body(int fd, short ev, void *d)
356 struct req *req = d;
357 char buf[BUFSIZ];
358 ssize_t r;
360 for (;;) {
361 switch (r = tls_read(req->ctx, buf, sizeof(buf))) {
362 case TLS_WANT_POLLIN:
363 yield_r(req, copy_body, NULL);
364 return;
365 case TLS_WANT_POLLOUT:
366 yield_w(req, copy_body, NULL);
367 return;
368 case -1:
369 case 0:
370 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
371 imsg_flush(ibuf);
372 close_conn(0, 0, req);
373 return;
374 default:
375 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1, buf, r);
376 imsg_flush(ibuf);
377 break;
382 static int
383 serve_special_page(struct req *req, const char *url)
385 int code = 20;
386 const char *meta = "text/gemini";
388 if (strcmp(url, "about:new"))
389 return 0;
391 imsg_compose(ibuf, IMSG_GOT_CODE, req->id, 0, -1, &code, sizeof(code));
392 imsg_compose(ibuf, IMSG_GOT_META, req->id, 0, -1, meta, strlen(meta)+1);
393 imsg_compose(ibuf, IMSG_BUF, req->id, 0, -1, about_new, strlen(about_new));
394 imsg_compose(ibuf, IMSG_EOF, req->id, 0, -1, NULL, 0);
395 imsg_flush(ibuf);
397 /* don't close_page here, since req is not added to requests
398 * queue */
399 free(req);
400 return 1;
403 static void
404 handle_get(struct imsg *imsg, size_t datalen)
406 struct req *req;
407 const char *e;
408 char *data, *err = NULL;
410 data = imsg->data;
412 if (data[datalen-1] != '\0')
413 die();
415 if ((req = calloc(1, sizeof(*req))) == NULL)
416 die();
418 req->id = imsg->hdr.peerid;
420 if (serve_special_page(req, data))
421 return;
423 if (!url_parse(imsg->data, &req->url, &e)) {
424 fprintf(stderr, "failed to parse url: %s\n", e);
425 close_with_err(req, e);
426 return;
429 if ((req->fd = conn_towards(&req->url, &err)) == -1)
430 goto err;
431 if ((req->ctx = tls_client()) == NULL)
432 goto err;
433 if (tls_configure(req->ctx, tlsconf) == -1) {
434 err = xasprintf("tls_configure: %s", tls_error(req->ctx));
435 goto err;
437 if (tls_connect_socket(req->ctx, req->fd, req->url.host) == -1) {
438 err = xasprintf("tls_connect_socket: %s", tls_error(req->ctx));
439 goto err;
442 TAILQ_INSERT_HEAD(&reqhead, req, reqs);
443 yield_w(req, do_handshake, NULL);
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_stop(struct imsg *imsg, size_t datalen)
472 struct req *req;
474 req = req_by_id(imsg->hdr.peerid);
475 close_conn(0, 0, req);
478 static void
479 handle_quit(struct imsg *imsg, size_t datalen)
481 event_loopbreak();
484 static void
485 dispatch_imsg(int fd, short ev, void *d)
487 struct imsgbuf *ibuf = d;
488 struct imsg imsg;
489 ssize_t n;
490 size_t datalen;
492 if ((n = imsg_read(ibuf)) == -1) {
493 if (errno == EAGAIN || errno == EWOULDBLOCK)
494 return;
495 die();
498 if (n == 0)
499 die();
501 for (;;) {
502 if ((n = imsg_get(ibuf, &imsg)) == -1)
503 die();
504 if (n == 0)
505 return;
506 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
507 handlers[imsg.hdr.type](&imsg, datalen);
508 imsg_free(&imsg);
512 int
513 client_main(struct imsgbuf *b)
515 ibuf = b;
517 TAILQ_INIT(&reqhead);
519 if ((tlsconf = tls_config_new()) == NULL)
520 die();
521 tls_config_insecure_noverifycert(tlsconf);
523 event_init();
525 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, dispatch_imsg, ibuf);
526 event_add(&imsgev, NULL);
528 event_dispatch();
529 return 0;