Blob


1 /*
2 * Copyright (c) 2021, 2022 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 #include "gmid.h"
19 #include <sys/stat.h>
20 #include <sys/un.h>
22 #include <assert.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <event.h>
26 #include <fcntl.h>
27 #include <fnmatch.h>
28 #include <limits.h>
29 #include <string.h>
31 #define MIN(a, b) ((a) < (b) ? (a) : (b))
33 int shutting_down;
35 static struct tls *ctx;
37 static struct event e4, e6, imsgev, siginfo, sigusr2;
38 static int has_ipv6, has_siginfo;
40 int connected_clients;
42 static inline int matches(const char*, const char*);
44 static int check_path(struct client*, const char*, int*);
45 static void open_file(struct client*);
46 static void handle_handshake(int, short, void*);
47 static const char *strip_path(const char*, int);
48 static void fmt_sbuf(const char*, struct client*, const char*);
49 static int apply_block_return(struct client*);
50 static int check_matching_certificate(X509_STORE *, struct client *);
51 static int apply_reverse_proxy(struct client *);
52 static int apply_fastcgi(struct client*);
53 static int apply_require_ca(struct client*);
54 static void open_dir(struct client*);
55 static void redirect_canonical_dir(struct client*);
57 static void client_tls_readcb(int, short, void *);
58 static void client_tls_writecb(int, short, void *);
60 static void client_read(struct bufferevent *, void *);
61 void client_write(struct bufferevent *, void *);
62 static void client_error(struct bufferevent *, short, void *);
64 static void client_close_ev(int, short, void *);
66 static void do_accept(int, short, void*);
68 static void handle_dispatch_imsg(int, short, void *);
69 static void handle_siginfo(int, short, void*);
71 static uint32_t server_client_id;
73 struct client_tree_id clients;
75 static inline int
76 matches(const char *pattern, const char *path)
77 {
78 if (*path == '/')
79 path++;
80 return !fnmatch(pattern, path, 0);
81 }
83 const char *
84 vhost_lang(struct vhost *v, const char *path)
85 {
86 struct location *loc;
88 if (v == NULL || path == NULL)
89 return NULL;
91 loc = TAILQ_FIRST(&v->locations);
92 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
93 if (loc->lang != NULL) {
94 if (matches(loc->match, path))
95 return loc->lang;
96 }
97 }
99 return TAILQ_FIRST(&v->locations)->lang;
102 const char *
103 vhost_default_mime(struct vhost *v, const char *path)
105 struct location *loc;
106 const char *default_mime = "application/octet-stream";
108 if (v == NULL || path == NULL)
109 return default_mime;
111 loc = TAILQ_FIRST(&v->locations);
112 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
113 if (loc->default_mime != NULL) {
114 if (matches(loc->match, path))
115 return loc->default_mime;
119 loc = TAILQ_FIRST(&v->locations);
120 if (loc->default_mime != NULL)
121 return loc->default_mime;
122 return default_mime;
125 const char *
126 vhost_index(struct vhost *v, const char *path)
128 struct location *loc;
129 const char *index = "index.gmi";
131 if (v == NULL || path == NULL)
132 return index;
134 loc = TAILQ_FIRST(&v->locations);
135 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
136 if (loc->index != NULL) {
137 if (matches(loc->match, path))
138 return loc->index;
142 loc = TAILQ_FIRST(&v->locations);
143 if (loc->index != NULL)
144 return loc->index;
145 return index;
148 int
149 vhost_auto_index(struct vhost *v, const char *path)
151 struct location *loc;
153 if (v == NULL || path == NULL)
154 return 0;
156 loc = TAILQ_FIRST(&v->locations);
157 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
158 if (loc->auto_index != 0) {
159 if (matches(loc->match, path))
160 return loc->auto_index == 1;
164 loc = TAILQ_FIRST(&v->locations);
165 return loc->auto_index == 1;
168 int
169 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
171 struct location *loc;
173 if (v == NULL || path == NULL)
174 return 0;
176 loc = TAILQ_FIRST(&v->locations);
177 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
178 if (loc->block_code != 0) {
179 if (matches(loc->match, path)) {
180 *code = loc->block_code;
181 *fmt = loc->block_fmt;
182 return 1;
187 loc = TAILQ_FIRST(&v->locations);
188 *code = loc->block_code;
189 *fmt = loc->block_fmt;
190 return loc->block_code != 0;
193 int
194 vhost_fastcgi(struct vhost *v, const char *path)
196 struct location *loc;
198 if (v == NULL || path == NULL)
199 return -1;
201 loc = TAILQ_FIRST(&v->locations);
202 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
203 if (loc->fcgi != -1)
204 if (matches(loc->match, path))
205 return loc->fcgi;
208 loc = TAILQ_FIRST(&v->locations);
209 return loc->fcgi;
212 int
213 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
215 struct location *loc;
216 size_t l = 0;
218 if (v == NULL || path == NULL)
219 return -1;
221 loc = TAILQ_FIRST(&v->locations);
222 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
223 l++;
224 if (loc->dirfd != -1)
225 if (matches(loc->match, path)) {
226 *retloc = l;
227 return loc->dirfd;
231 *retloc = 0;
232 loc = TAILQ_FIRST(&v->locations);
233 return loc->dirfd;
236 int
237 vhost_strip(struct vhost *v, const char *path)
239 struct location *loc;
241 if (v == NULL || path == NULL)
242 return 0;
244 loc = TAILQ_FIRST(&v->locations);
245 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
246 if (loc->strip != 0) {
247 if (matches(loc->match, path))
248 return loc->strip;
252 loc = TAILQ_FIRST(&v->locations);
253 return loc->strip;
256 X509_STORE *
257 vhost_require_ca(struct vhost *v, const char *path)
259 struct location *loc;
261 if (v == NULL || path == NULL)
262 return NULL;
264 loc = TAILQ_FIRST(&v->locations);
265 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
266 if (loc->reqca != NULL) {
267 if (matches(loc->match, path))
268 return loc->reqca;
272 loc = TAILQ_FIRST(&v->locations);
273 return loc->reqca;
276 int
277 vhost_disable_log(struct vhost *v, const char *path)
279 struct location *loc;
281 if (v == NULL || path == NULL)
282 return 0;
284 loc = TAILQ_FIRST(&v->locations);
285 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
286 if (loc->disable_log && matches(loc->match, path))
287 return 1;
290 loc = TAILQ_FIRST(&v->locations);
291 return loc->disable_log;
294 static int
295 check_path(struct client *c, const char *path, int *fd)
297 struct stat sb;
298 const char *p;
299 int dirfd, strip;
301 assert(path != NULL);
303 /*
304 * in send_dir we add an initial / (to be redirect-friendly),
305 * but here we want to skip it
306 */
307 if (*path == '/')
308 path++;
310 strip = vhost_strip(c->host, path);
311 p = strip_path(path, strip);
313 if (*p == '/')
314 p = p+1;
315 if (*p == '\0')
316 p = ".";
318 dirfd = vhost_dirfd(c->host, path, &c->loc);
319 log_debug(c, "check_path: strip=%d path=%s original=%s",
320 strip, p, path);
321 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
322 if (errno == EACCES)
323 log_info(c, "can't open %s: %s", p, strerror(errno));
324 return FILE_MISSING;
327 if (fstat(*fd, &sb) == -1) {
328 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
329 return FILE_MISSING;
332 if (S_ISDIR(sb.st_mode))
333 return FILE_DIRECTORY;
335 return FILE_EXISTS;
338 static void
339 open_file(struct client *c)
341 switch (check_path(c, c->iri.path, &c->pfd)) {
342 case FILE_EXISTS:
343 c->type = REQUEST_FILE;
344 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
345 return;
347 case FILE_DIRECTORY:
348 open_dir(c);
349 return;
351 case FILE_MISSING:
352 start_reply(c, NOT_FOUND, "not found");
353 return;
355 default:
356 /* unreachable */
357 abort();
361 void
362 mark_nonblock(int fd)
364 int flags;
366 if ((flags = fcntl(fd, F_GETFL)) == -1)
367 fatal("fcntl(F_GETFL): %s", strerror(errno));
368 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
369 fatal("fcntl(F_SETFL): %s", strerror(errno));
372 static void
373 handle_handshake(int fd, short ev, void *d)
375 struct client *c = d;
376 struct vhost *h;
377 struct alist *a;
378 const char *servname;
379 const char *parse_err = "unknown error";
381 switch (tls_handshake(c->ctx)) {
382 case 0: /* success */
383 case -1: /* already handshaked */
384 break;
385 case TLS_WANT_POLLIN:
386 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
387 return;
388 case TLS_WANT_POLLOUT:
389 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
390 return;
391 default:
392 /* unreachable */
393 abort();
396 c->bev = bufferevent_new(fd, client_read, client_write,
397 client_error, c);
398 if (c->bev == NULL)
399 fatal("%s: failed to allocate client buffer: %s",
400 __func__, strerror(errno));
402 event_set(&c->bev->ev_read, c->fd, EV_READ,
403 client_tls_readcb, c->bev);
404 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
405 client_tls_writecb, c->bev);
407 #if HAVE_LIBEVENT2
408 evbuffer_unfreeze(c->bev->input, 0);
409 evbuffer_unfreeze(c->bev->output, 1);
410 #endif
412 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
413 log_debug(c, "handshake: missing SNI");
414 goto err;
417 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
418 log_info(c, "puny_decode: %s", parse_err);
419 goto err;
422 TAILQ_FOREACH(h, &hosts, vhosts) {
423 if (matches(h->domain, c->domain))
424 goto found;
425 TAILQ_FOREACH(a, &h->aliases, aliases) {
426 if (matches(a->alias, c->domain))
427 goto found;
431 found:
432 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
433 servname != NULL ? servname : "(null)",
434 c->domain,
435 h != NULL ? h->domain : "(null)");
437 if (h != NULL) {
438 c->host = h;
439 bufferevent_enable(c->bev, EV_READ);
440 return;
443 err:
444 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
447 static const char *
448 strip_path(const char *path, int strip)
450 char *t;
452 while (strip > 0) {
453 if ((t = strchr(path, '/')) == NULL) {
454 path = strchr(path, '\0');
455 break;
457 path = t;
458 strip--;
461 return path;
464 static void
465 fmt_sbuf(const char *fmt, struct client *c, const char *path)
467 size_t i;
468 char buf[32];
470 memset(buf, 0, sizeof(buf));
471 for (i = 0; *fmt; ++fmt) {
472 if (i == sizeof(buf)-1 || *fmt == '%') {
473 strlcat(c->sbuf, buf, sizeof(c->sbuf));
474 memset(buf, 0, sizeof(buf));
475 i = 0;
478 if (*fmt != '%') {
479 buf[i++] = *fmt;
480 continue;
483 switch (*++fmt) {
484 case '%':
485 strlcat(c->sbuf, "%", sizeof(c->sbuf));
486 break;
487 case 'p':
488 if (*path != '/')
489 strlcat(c->sbuf, "/", sizeof(c->sbuf));
490 strlcat(c->sbuf, path, sizeof(c->sbuf));
491 break;
492 case 'q':
493 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
494 break;
495 case 'P':
496 snprintf(buf, sizeof(buf), "%d", conf.port);
497 strlcat(c->sbuf, buf, sizeof(c->sbuf));
498 memset(buf, 0, sizeof(buf));
499 break;
500 case 'N':
501 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
502 break;
503 default:
504 fatal("%s: unknown fmt specifier %c",
505 __func__, *fmt);
509 if (i != 0)
510 strlcat(c->sbuf, buf, sizeof(c->sbuf));
513 /* 1 if a matching `block return' (and apply it), 0 otherwise */
514 static int
515 apply_block_return(struct client *c)
517 const char *fmt, *path;
518 int code;
520 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
521 return 0;
523 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
524 fmt_sbuf(fmt, c, path);
526 start_reply(c, code, c->sbuf);
527 return 1;
530 static struct proxy *
531 matched_proxy(struct client *c)
533 struct proxy *p;
534 const char *proto;
535 const char *host;
536 const char *port;
538 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
539 if ((proto = p->match_proto) == NULL)
540 proto = "gemini";
541 if ((host = p->match_host) == NULL)
542 host = "*";
543 if ((port = p->match_port) == NULL)
544 port = "*";
546 if (matches(proto, c->iri.schema) &&
547 matches(host, c->domain) &&
548 matches(port, c->iri.port))
549 return p;
552 return NULL;
555 static int
556 check_matching_certificate(X509_STORE *store, struct client *c)
558 const uint8_t *cert;
559 size_t len;
561 if (!tls_peer_cert_provided(c->ctx)) {
562 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
563 return 1;
566 cert = tls_peer_cert_chain_pem(c->ctx, &len);
567 if (!validate_against_ca(store, cert, len)) {
568 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
569 return 1;
572 return 0;
575 static int
576 proxy_socket(struct client *c, const char *host, const char *port)
578 struct addrinfo hints, *res, *res0;
579 int r, sock;
581 memset(&hints, 0, sizeof(hints));
582 hints.ai_family = AF_UNSPEC;
583 hints.ai_socktype = SOCK_STREAM;
585 /* XXX: asr_run? :> */
586 r = getaddrinfo(host, port, &hints, &res0);
587 if (r != 0) {
588 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
589 host, port, gai_strerror(r));
590 return -1;
593 for (res = res0; res; res = res->ai_next) {
594 sock = socket(res->ai_family, res->ai_socktype,
595 res->ai_protocol);
596 if (sock == -1)
597 continue;
599 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
600 close(sock);
601 sock = -1;
602 continue;
605 break;
608 freeaddrinfo(res0);
610 if (sock == -1)
611 log_warn(c, "can't connect to %s:%s", host, port);
613 return sock;
616 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
617 static int
618 apply_reverse_proxy(struct client *c)
620 struct proxy *p;
622 if ((p = matched_proxy(c)) == NULL)
623 return 0;
625 c->proxy = p;
627 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
628 return 1;
630 log_debug(c, "opening proxy connection for %s:%s",
631 p->host, p->port);
633 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
634 start_reply(c, PROXY_ERROR, "proxy error");
635 return 1;
638 mark_nonblock(c->pfd);
639 if (proxy_init(c) == -1)
640 start_reply(c, PROXY_ERROR, "proxy error");
642 return 1;
645 static int
646 fcgi_open_sock(struct fcgi *f)
648 struct sockaddr_un addr;
649 int fd;
651 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
652 log_err(NULL, "socket: %s", strerror(errno));
653 return -1;
656 memset(&addr, 0, sizeof(addr));
657 addr.sun_family = AF_UNIX;
658 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
660 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
661 log_warn(NULL, "failed to connect to %s: %s", f->path,
662 strerror(errno));
663 close(fd);
664 return -1;
667 return fd;
670 static int
671 fcgi_open_conn(struct fcgi *f)
673 struct addrinfo hints, *servinfo, *p;
674 int r, sock;
676 memset(&hints, 0, sizeof(hints));
677 hints.ai_family = AF_UNSPEC;
678 hints.ai_socktype = SOCK_STREAM;
679 hints.ai_flags = AI_ADDRCONFIG;
681 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
682 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
683 gai_strerror(r));
684 return -1;
687 for (p = servinfo; p != NULL; p = p->ai_next) {
688 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
689 if (sock == -1)
690 continue;
691 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
692 close(sock);
693 continue;
695 break;
698 if (p == NULL) {
699 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
700 sock = -1;
703 freeaddrinfo(servinfo);
704 return sock;
707 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
708 static int
709 apply_fastcgi(struct client *c)
711 int id;
712 struct fcgi *f;
714 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
715 return 0;
717 f = &fcgi[id];
719 log_debug(c, "opening fastcgi connection for (%s,%s)",
720 f->path, f->port);
722 if (f->port != NULL)
723 c->pfd = fcgi_open_sock(f);
724 else
725 c->pfd = fcgi_open_conn(f);
727 if (c->pfd == -1) {
728 start_reply(c, CGI_ERROR, "CGI error");
729 return 1;
732 mark_nonblock(c->pfd);
734 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
735 fcgi_error, c);
736 if (c->cgibev == NULL) {
737 start_reply(c, TEMP_FAILURE, "internal server error");
738 return 1;
741 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
742 fcgi_req(c);
744 return 1;
747 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
748 static int
749 apply_require_ca(struct client *c)
751 X509_STORE *store;
753 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
754 return 0;
755 return check_matching_certificate(store, c);
758 static void
759 open_dir(struct client *c)
761 size_t len;
762 int dirfd, root;
763 char *before_file;
765 log_debug(c, "in open_dir");
767 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
769 len = strlen(c->iri.path);
770 if (len > 0 && !ends_with(c->iri.path, "/")) {
771 redirect_canonical_dir(c);
772 return;
775 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
776 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
777 if (!ends_with(c->sbuf, "/"))
778 strlcat(c->sbuf, "/", sizeof(c->sbuf));
779 before_file = strchr(c->sbuf, '\0');
780 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
781 sizeof(c->sbuf));
782 if (len >= sizeof(c->sbuf)) {
783 start_reply(c, TEMP_FAILURE, "internal server error");
784 return;
787 c->iri.path = c->sbuf;
789 /* close later unless we have to generate the dir listing */
790 dirfd = c->pfd;
791 c->pfd = -1;
793 switch (check_path(c, c->iri.path, &c->pfd)) {
794 case FILE_EXISTS:
795 c->type = REQUEST_FILE;
796 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
797 break;
799 case FILE_DIRECTORY:
800 start_reply(c, TEMP_REDIRECT, c->sbuf);
801 break;
803 case FILE_MISSING:
804 *before_file = '\0';
806 if (!vhost_auto_index(c->host, c->iri.path)) {
807 start_reply(c, NOT_FOUND, "not found");
808 break;
811 c->type = REQUEST_DIR;
813 c->dirlen = scandir_fd(dirfd, &c->dir,
814 root ? select_non_dotdot : select_non_dot,
815 alphasort);
816 if (c->dirlen == -1) {
817 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
818 c->pfd, c->host->domain, c->iri.path, strerror(errno));
819 start_reply(c, TEMP_FAILURE, "internal server error");
820 return;
822 c->diroff = 0;
823 c->off = 0;
825 start_reply(c, SUCCESS, "text/gemini");
826 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
827 "# Index of %s\n\n", c->iri.path);
828 return;
830 default:
831 /* unreachable */
832 abort();
835 close(dirfd);
838 static void
839 redirect_canonical_dir(struct client *c)
841 size_t len;
843 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
844 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
845 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
847 if (len >= sizeof(c->sbuf)) {
848 start_reply(c, TEMP_FAILURE, "internal server error");
849 return;
852 start_reply(c, TEMP_REDIRECT, c->sbuf);
855 static void
856 client_tls_readcb(int fd, short event, void *d)
858 struct bufferevent *bufev = d;
859 struct client *client = bufev->cbarg;
860 ssize_t ret;
861 size_t len;
862 int what = EVBUFFER_READ;
863 int howmuch = IBUF_READ_SIZE;
864 char buf[IBUF_READ_SIZE];
866 if (event == EV_TIMEOUT) {
867 what |= EVBUFFER_TIMEOUT;
868 goto err;
871 if (bufev->wm_read.high != 0)
872 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
874 switch (ret = tls_read(client->ctx, buf, howmuch)) {
875 case TLS_WANT_POLLIN:
876 case TLS_WANT_POLLOUT:
877 goto retry;
878 case -1:
879 what |= EVBUFFER_ERROR;
880 goto err;
882 len = ret;
884 if (len == 0) {
885 what |= EVBUFFER_EOF;
886 goto err;
889 if (evbuffer_add(bufev->input, buf, len) == -1) {
890 what |= EVBUFFER_ERROR;
891 goto err;
894 event_add(&bufev->ev_read, NULL);
895 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
896 return;
897 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
898 /*
899 * here we could implement a read pressure policy.
900 */
903 if (bufev->readcb != NULL)
904 (*bufev->readcb)(bufev, bufev->cbarg);
906 return;
908 retry:
909 event_add(&bufev->ev_read, NULL);
910 return;
912 err:
913 (*bufev->errorcb)(bufev, what, bufev->cbarg);
916 static void
917 client_tls_writecb(int fd, short event, void *d)
919 struct bufferevent *bufev = d;
920 struct client *client = bufev->cbarg;
921 ssize_t ret;
922 size_t len;
923 short what = EVBUFFER_WRITE;
925 if (event == EV_TIMEOUT) {
926 what |= EVBUFFER_TIMEOUT;
927 goto err;
930 if (EVBUFFER_LENGTH(bufev->output) != 0) {
931 ret = tls_write(client->ctx,
932 EVBUFFER_DATA(bufev->output),
933 EVBUFFER_LENGTH(bufev->output));
934 switch (ret) {
935 case TLS_WANT_POLLIN:
936 case TLS_WANT_POLLOUT:
937 goto retry;
938 case -1:
939 what |= EVBUFFER_ERROR;
940 goto err;
942 len = ret;
943 evbuffer_drain(bufev->output, len);
946 if (EVBUFFER_LENGTH(bufev->output) != 0)
947 event_add(&bufev->ev_write, NULL);
949 if (bufev->writecb != NULL &&
950 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
951 (*bufev->writecb)(bufev, bufev->cbarg);
952 return;
954 retry:
955 event_add(&bufev->ev_write, NULL);
956 return;
957 err:
958 log_err(client, "tls error: %s", tls_error(client->ctx));
959 (*bufev->errorcb)(bufev, what, bufev->cbarg);
962 static void
963 client_read(struct bufferevent *bev, void *d)
965 struct client *c = d;
966 struct evbuffer *src = EVBUFFER_INPUT(bev);
967 const char *parse_err = "invalid request";
968 char decoded[DOMAIN_NAME_LEN];
969 size_t len;
971 bufferevent_disable(bev, EVBUFFER_READ);
973 /*
974 * libevent2 can still somehow call this function, even
975 * though I never enable EV_READ in the bufferevent. If
976 * that's the case, bail out.
977 */
978 if (c->type != REQUEST_UNDECIDED)
979 return;
981 /* max url len + \r\n */
982 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
983 log_err(c, "too much data received");
984 start_reply(c, BAD_REQUEST, "bad request");
985 return;
988 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
989 if (c->req == NULL) {
990 /* not enough data yet. */
991 bufferevent_enable(bev, EVBUFFER_READ);
992 return;
994 c->reqlen = strlen(c->req);
995 if (c->reqlen > 1024+2) {
996 log_err(c, "URL too long");
997 start_reply(c, BAD_REQUEST, "bad request");
998 return;
1001 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1002 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1003 log_err(c, "IRI parse error: %s", parse_err);
1004 start_reply(c, BAD_REQUEST, "bad request");
1005 return;
1008 if (apply_reverse_proxy(c))
1009 return;
1011 /* ignore the port number */
1012 if (strcmp(c->iri.schema, "gemini") ||
1013 strcmp(decoded, c->domain)) {
1014 start_reply(c, PROXY_REFUSED, "won't proxy request");
1015 return;
1018 if (apply_require_ca(c) ||
1019 apply_block_return(c)||
1020 apply_fastcgi(c))
1021 return;
1023 open_file(c);
1026 void
1027 client_write(struct bufferevent *bev, void *d)
1029 struct client *c = d;
1030 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1031 char nam[PATH_MAX];
1032 char buf[BUFSIZ];
1033 ssize_t r;
1035 switch (c->type) {
1036 case REQUEST_UNDECIDED:
1038 * Ignore spurious calls when we still don't have idea
1039 * what to do with the request.
1041 break;
1043 case REQUEST_FILE:
1044 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1045 log_warn(c, "read: %s", strerror(errno));
1046 client_error(bev, EVBUFFER_ERROR, c);
1047 return;
1048 } else if (r == 0) {
1049 client_close(c);
1050 return;
1051 } else if (r != sizeof(buf))
1052 c->type = REQUEST_DONE;
1053 bufferevent_write(bev, buf, r);
1054 break;
1056 case REQUEST_DIR:
1057 /* TODO: handle big big directories better */
1058 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1059 const char *sufx = "";
1061 encode_path(nam, sizeof(nam),
1062 c->dir[c->diroff]->d_name);
1063 if (c->dir[c->diroff]->d_type == DT_DIR)
1064 sufx = "/";
1065 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1066 free(c->dir[c->diroff]);
1068 free(c->dir);
1069 c->dir = NULL;
1071 c->type = REQUEST_DONE;
1073 event_add(&c->bev->ev_write, NULL);
1074 break;
1076 case REQUEST_FCGI:
1077 case REQUEST_PROXY:
1079 * Here we depend on fastcgi or proxy connection to
1080 * provide data.
1082 break;
1084 case REQUEST_DONE:
1085 if (EVBUFFER_LENGTH(out) == 0)
1086 client_close(c);
1087 break;
1091 static void
1092 client_error(struct bufferevent *bev, short error, void *d)
1094 struct client *c = d;
1096 c->type = REQUEST_DONE;
1098 if (error & EVBUFFER_TIMEOUT) {
1099 log_warn(c, "timeout reached, "
1100 "forcefully closing the connection");
1101 if (c->code == 0)
1102 start_reply(c, BAD_REQUEST, "timeout");
1103 else
1104 client_close(c);
1105 return;
1108 if (error & EVBUFFER_EOF) {
1109 client_close(c);
1110 return;
1113 log_err(c, "unknown bufferevent error %x", error);
1114 client_close(c);
1117 void
1118 start_reply(struct client *c, int code, const char *meta)
1120 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1121 const char *lang;
1122 int r, rr;
1124 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1126 c->code = code;
1127 c->meta = meta;
1129 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1130 if (r == -1)
1131 goto err;
1133 /* 2 digit status + space + 1024 max reply */
1134 if (r > 1027)
1135 goto overflow;
1137 if (c->type != REQUEST_FCGI &&
1138 c->type != REQUEST_PROXY &&
1139 !strcmp(meta, "text/gemini") &&
1140 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1141 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1142 if (rr == -1)
1143 goto err;
1144 if (r + rr > 1027)
1145 goto overflow;
1148 bufferevent_write(c->bev, "\r\n", 2);
1150 if (!vhost_disable_log(c->host, c->iri.path))
1151 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1153 if (code != 20)
1154 c->type = REQUEST_DONE;
1156 return;
1158 err:
1159 log_err(c, "evbuffer_add_printf error: no memory");
1160 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1161 client_close(c);
1162 return;
1164 overflow:
1165 log_warn(c, "reply header overflow");
1166 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1167 start_reply(c, TEMP_FAILURE, "internal error");
1170 static void
1171 client_close_ev(int fd, short event, void *d)
1173 struct client *c = d;
1175 switch (tls_close(c->ctx)) {
1176 case TLS_WANT_POLLIN:
1177 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1178 break;
1179 case TLS_WANT_POLLOUT:
1180 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1181 break;
1184 connected_clients--;
1186 free(c->req);
1188 tls_free(c->ctx);
1189 c->ctx = NULL;
1191 free(c->header);
1193 if (c->pfd != -1)
1194 close(c->pfd);
1196 if (c->dir != NULL)
1197 free(c->dir);
1199 close(c->fd);
1200 c->fd = -1;
1203 static void
1204 client_proxy_close(int fd, short event, void *d)
1206 struct tls *ctx = d;
1208 if (ctx == NULL) {
1209 close(fd);
1210 return;
1213 switch (tls_close(ctx)) {
1214 case TLS_WANT_POLLIN:
1215 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1216 break;
1217 case TLS_WANT_POLLOUT:
1218 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1219 break;
1222 tls_free(ctx);
1223 close(fd);
1226 void
1227 client_close(struct client *c)
1230 * We may end up calling client_close in various situations
1231 * and for the most unexpected reasons. Therefore, we need to
1232 * ensure that everything gets properly released once we reach
1233 * this point.
1236 SPLAY_REMOVE(client_tree_id, &clients, c);
1238 if (c->cgibev != NULL) {
1239 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1240 bufferevent_free(c->cgibev);
1241 c->cgibev = NULL;
1242 close(c->pfd);
1243 c->pfd = -1;
1246 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1247 bufferevent_free(c->bev);
1248 c->bev = NULL;
1250 if (c->proxyevset &&
1251 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1252 c->proxyevset = 0;
1253 event_del(&c->proxyev);
1256 if (c->pfd != -1 && c->proxyctx != NULL) {
1257 /* shut down the proxy TLS connection */
1258 client_proxy_close(c->pfd, 0, c->proxyctx);
1259 c->pfd = -1;
1262 if (c->proxybev != NULL)
1263 bufferevent_free(c->proxybev);
1265 client_close_ev(c->fd, 0, c);
1268 static void
1269 do_accept(int sock, short et, void *d)
1271 struct client *c;
1272 struct sockaddr_storage addr;
1273 struct sockaddr *saddr;
1274 socklen_t len;
1275 int fd;
1277 saddr = (struct sockaddr*)&addr;
1278 len = sizeof(addr);
1279 if ((fd = accept(sock, saddr, &len)) == -1) {
1280 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1281 errno == ECONNABORTED)
1282 return;
1283 fatal("accept: %s", strerror(errno));
1286 mark_nonblock(fd);
1288 c = xcalloc(1, sizeof(*c));
1289 c->id = ++server_client_id;
1290 c->fd = fd;
1291 c->pfd = -1;
1292 c->addr = addr;
1294 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1295 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1296 close(c->fd);
1297 free(c);
1298 return;
1301 SPLAY_INSERT(client_tree_id, &clients, c);
1302 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1303 connected_clients++;
1306 struct client *
1307 client_by_id(int id)
1309 struct client find;
1311 find.id = id;
1312 return SPLAY_FIND(client_tree_id, &clients, &find);
1315 static void
1316 handle_dispatch_imsg(int fd, short ev, void *d)
1318 struct imsgbuf *ibuf = d;
1319 struct imsg imsg;
1320 ssize_t n;
1322 if ((n = imsg_read(ibuf)) == -1) {
1323 if (errno == EAGAIN || errno == EWOULDBLOCK)
1324 return;
1325 fatal("imsg_read");
1328 if (n == 0)
1329 fatal("connection closed."); /* XXX: fatalx */
1331 for (;;) {
1332 if ((n = imsg_get(ibuf, &imsg)) == -1)
1333 fatal("imsg_get");
1334 if (n == 0)
1335 return;
1337 switch (imsg.hdr.type) {
1338 case IMSG_QUIT:
1340 * Don't call event_loopbreak since we want to
1341 * finish handling the ongoing connections.
1343 shutting_down = 1;
1345 event_del(&e4);
1346 if (has_ipv6)
1347 event_del(&e6);
1348 if (has_siginfo)
1349 signal_del(&siginfo);
1350 event_del(&imsgev);
1351 signal_del(&sigusr2);
1352 break;
1353 default:
1354 /* XXX: fatalx */
1355 fatal("Unknown message %d", imsg.hdr.type);
1357 imsg_free(&imsg);
1361 static void
1362 handle_siginfo(int fd, short ev, void *d)
1364 log_info(NULL, "%d connected clients", connected_clients);
1367 void
1368 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1370 ctx = ctx_;
1372 SPLAY_INIT(&clients);
1374 event_init();
1376 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1377 event_add(&e4, NULL);
1379 if (sock6 != -1) {
1380 has_ipv6 = 1;
1381 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1382 event_add(&e6, NULL);
1385 if (ibuf) {
1386 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1387 handle_dispatch_imsg, ibuf);
1388 event_add(&imsgev, NULL);
1391 #ifdef SIGINFO
1392 has_siginfo = 1;
1393 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1394 signal_add(&siginfo, NULL);
1395 #endif
1396 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1397 signal_add(&sigusr2, NULL);
1399 sandbox_server_process(conf.can_open_sockets);
1400 event_dispatch();
1401 _exit(0);
1404 int
1405 client_tree_cmp(struct client *a, struct client *b)
1407 if (a->id == b->id)
1408 return 0;
1409 else if (a->id < b->id)
1410 return -1;
1411 else
1412 return +1;
1415 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)