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 #include "log.h"
32 #include "proc.h"
34 #define MIN(a, b) ((a) < (b) ? (a) : (b))
36 #ifndef nitems
37 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
38 #endif
40 int shutting_down;
42 static struct tls *ctx;
44 static struct event siginfo, sigusr2;
45 static int has_siginfo;
47 int connected_clients;
49 static inline int matches(const char*, const char*);
51 static int check_path(struct client*, const char*, int*);
52 static void open_file(struct client*);
53 static void handle_handshake(int, short, void*);
54 static const char *strip_path(const char*, int);
55 static void fmt_sbuf(const char*, struct client*, const char*);
56 static int apply_block_return(struct client*);
57 static int check_matching_certificate(X509_STORE *, struct client *);
58 static int apply_reverse_proxy(struct client *);
59 static int apply_fastcgi(struct client*);
60 static int apply_require_ca(struct client*);
61 static void open_dir(struct client*);
62 static void redirect_canonical_dir(struct client*);
64 static void client_tls_readcb(int, short, void *);
65 static void client_tls_writecb(int, short, void *);
67 static void client_read(struct bufferevent *, void *);
68 void client_write(struct bufferevent *, void *);
69 static void client_error(struct bufferevent *, short, void *);
71 static void client_close_ev(int, short, void *);
73 static void handle_siginfo(int, short, void*);
75 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
76 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
78 static struct privsep_proc procs[] = {
79 { "parent", PROC_PARENT, server_dispatch_parent },
80 { "logger", PROC_LOGGER, server_dispatch_logger },
81 };
83 static uint32_t server_client_id;
85 struct client_tree_id clients;
87 static inline int
88 matches(const char *pattern, const char *path)
89 {
90 if (*path == '/')
91 path++;
92 return !fnmatch(pattern, path, 0);
93 }
95 const char *
96 vhost_lang(struct vhost *v, const char *path)
97 {
98 struct location *loc;
100 if (v == NULL || path == NULL)
101 return NULL;
103 loc = TAILQ_FIRST(&v->locations);
104 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
105 if (*loc->lang != '\0') {
106 if (matches(loc->match, path))
107 return loc->lang;
111 loc = TAILQ_FIRST(&v->locations);
112 if (*loc->lang == '\0')
113 return NULL;
114 return loc->lang;
117 const char *
118 vhost_default_mime(struct vhost *v, const char *path)
120 struct location *loc;
121 const char *default_mime = "application/octet-stream";
123 if (v == NULL || path == NULL)
124 return default_mime;
126 loc = TAILQ_FIRST(&v->locations);
127 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
128 if (*loc->default_mime != '\0') {
129 if (matches(loc->match, path))
130 return loc->default_mime;
134 loc = TAILQ_FIRST(&v->locations);
135 if (*loc->default_mime != '\0')
136 return loc->default_mime;
137 return default_mime;
140 const char *
141 vhost_index(struct vhost *v, const char *path)
143 struct location *loc;
144 const char *index = "index.gmi";
146 if (v == NULL || path == NULL)
147 return index;
149 loc = TAILQ_FIRST(&v->locations);
150 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
151 if (*loc->index != '\0') {
152 if (matches(loc->match, path))
153 return loc->index;
157 loc = TAILQ_FIRST(&v->locations);
158 if (*loc->index != '\0')
159 return loc->index;
160 return index;
163 int
164 vhost_auto_index(struct vhost *v, const char *path)
166 struct location *loc;
168 if (v == NULL || path == NULL)
169 return 0;
171 loc = TAILQ_FIRST(&v->locations);
172 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
173 if (loc->auto_index != 0) {
174 if (matches(loc->match, path))
175 return loc->auto_index == 1;
179 loc = TAILQ_FIRST(&v->locations);
180 return loc->auto_index == 1;
183 int
184 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
186 struct location *loc;
188 if (v == NULL || path == NULL)
189 return 0;
191 loc = TAILQ_FIRST(&v->locations);
192 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
193 if (loc->block_code != 0) {
194 if (matches(loc->match, path)) {
195 *code = loc->block_code;
196 *fmt = loc->block_fmt;
197 return 1;
202 loc = TAILQ_FIRST(&v->locations);
203 *code = loc->block_code;
204 *fmt = loc->block_fmt;
205 return loc->block_code != 0;
208 int
209 vhost_fastcgi(struct vhost *v, const char *path)
211 struct location *loc;
213 if (v == NULL || path == NULL)
214 return -1;
216 loc = TAILQ_FIRST(&v->locations);
217 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
218 if (loc->fcgi != -1)
219 if (matches(loc->match, path))
220 return loc->fcgi;
223 loc = TAILQ_FIRST(&v->locations);
224 return loc->fcgi;
227 int
228 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
230 struct location *loc;
231 size_t l = 0;
233 if (v == NULL || path == NULL)
234 return -1;
236 loc = TAILQ_FIRST(&v->locations);
237 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
238 l++;
239 if (loc->dirfd != -1)
240 if (matches(loc->match, path)) {
241 *retloc = l;
242 return loc->dirfd;
246 *retloc = 0;
247 loc = TAILQ_FIRST(&v->locations);
248 return loc->dirfd;
251 int
252 vhost_strip(struct vhost *v, const char *path)
254 struct location *loc;
256 if (v == NULL || path == NULL)
257 return 0;
259 loc = TAILQ_FIRST(&v->locations);
260 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
261 if (loc->strip != 0) {
262 if (matches(loc->match, path))
263 return loc->strip;
267 loc = TAILQ_FIRST(&v->locations);
268 return loc->strip;
271 X509_STORE *
272 vhost_require_ca(struct vhost *v, const char *path)
274 struct location *loc;
276 if (v == NULL || path == NULL)
277 return NULL;
279 loc = TAILQ_FIRST(&v->locations);
280 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
281 if (loc->reqca != NULL) {
282 if (matches(loc->match, path))
283 return loc->reqca;
287 loc = TAILQ_FIRST(&v->locations);
288 return loc->reqca;
291 int
292 vhost_disable_log(struct vhost *v, const char *path)
294 struct location *loc;
296 if (v == NULL || path == NULL)
297 return 0;
299 loc = TAILQ_FIRST(&v->locations);
300 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
301 if (loc->disable_log && matches(loc->match, path))
302 return 1;
305 loc = TAILQ_FIRST(&v->locations);
306 return loc->disable_log;
309 static int
310 check_path(struct client *c, const char *path, int *fd)
312 struct stat sb;
313 const char *p;
314 int dirfd, strip;
316 assert(path != NULL);
318 /*
319 * in send_dir we add an initial / (to be redirect-friendly),
320 * but here we want to skip it
321 */
322 if (*path == '/')
323 path++;
325 strip = vhost_strip(c->host, path);
326 p = strip_path(path, strip);
328 if (*p == '/')
329 p = p+1;
330 if (*p == '\0')
331 p = ".";
333 dirfd = vhost_dirfd(c->host, path, &c->loc);
334 log_debug("check_path: strip=%d path=%s original=%s",
335 strip, p, path);
336 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
337 if (errno == EACCES)
338 log_info("can't open %s: %s", p, strerror(errno));
339 return FILE_MISSING;
342 if (fstat(*fd, &sb) == -1) {
343 log_warn("fstat %s", path);
344 return FILE_MISSING;
347 if (S_ISDIR(sb.st_mode))
348 return FILE_DIRECTORY;
350 return FILE_EXISTS;
353 static void
354 open_file(struct client *c)
356 switch (check_path(c, c->iri.path, &c->pfd)) {
357 case FILE_EXISTS:
358 c->type = REQUEST_FILE;
359 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
360 return;
362 case FILE_DIRECTORY:
363 open_dir(c);
364 return;
366 case FILE_MISSING:
367 start_reply(c, NOT_FOUND, "not found");
368 return;
370 default:
371 /* unreachable */
372 abort();
376 void
377 mark_nonblock(int fd)
379 int flags;
381 if ((flags = fcntl(fd, F_GETFL)) == -1)
382 fatal("fcntl(F_GETFL)");
383 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
384 fatal("fcntl(F_SETFL)");
387 static void
388 handle_handshake(int fd, short ev, void *d)
390 struct client *c = d;
391 struct conf *conf = c->conf;
392 struct vhost *h;
393 struct alist *a;
394 const char *servname;
395 const char *parse_err = "unknown error";
397 switch (tls_handshake(c->ctx)) {
398 case 0: /* success */
399 case -1: /* already handshaked */
400 break;
401 case TLS_WANT_POLLIN:
402 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
403 return;
404 case TLS_WANT_POLLOUT:
405 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
406 return;
407 default:
408 /* unreachable */
409 abort();
412 c->bev = bufferevent_new(fd, client_read, client_write,
413 client_error, c);
414 if (c->bev == NULL)
415 fatal("%s: failed to allocate client buffer", __func__);
417 event_set(&c->bev->ev_read, c->fd, EV_READ,
418 client_tls_readcb, c->bev);
419 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
420 client_tls_writecb, c->bev);
422 #if HAVE_LIBEVENT2
423 evbuffer_unfreeze(c->bev->input, 0);
424 evbuffer_unfreeze(c->bev->output, 1);
425 #endif
427 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
428 log_debug("handshake: missing SNI");
429 goto err;
432 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
433 log_info("puny_decode: %s", parse_err);
434 goto err;
437 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
438 if (matches(h->domain, c->domain))
439 goto found;
440 TAILQ_FOREACH(a, &h->aliases, aliases) {
441 if (matches(a->alias, c->domain))
442 goto found;
446 found:
447 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
448 servname != NULL ? servname : "(null)",
449 c->domain,
450 h != NULL ? h->domain : "(null)");
452 if (h != NULL) {
453 c->host = h;
454 bufferevent_enable(c->bev, EV_READ);
455 return;
458 err:
459 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
462 static const char *
463 strip_path(const char *path, int strip)
465 char *t;
467 while (strip > 0) {
468 if ((t = strchr(path, '/')) == NULL) {
469 path = strchr(path, '\0');
470 break;
472 path = t;
473 strip--;
476 return path;
479 static void
480 fmt_sbuf(const char *fmt, struct client *c, const char *path)
482 struct conf *conf = c->conf;
483 size_t i;
484 char buf[32];
486 memset(buf, 0, sizeof(buf));
487 for (i = 0; *fmt; ++fmt) {
488 if (i == sizeof(buf)-1 || *fmt == '%') {
489 strlcat(c->sbuf, buf, sizeof(c->sbuf));
490 memset(buf, 0, sizeof(buf));
491 i = 0;
494 if (*fmt != '%') {
495 buf[i++] = *fmt;
496 continue;
499 switch (*++fmt) {
500 case '%':
501 strlcat(c->sbuf, "%", sizeof(c->sbuf));
502 break;
503 case 'p':
504 if (*path != '/')
505 strlcat(c->sbuf, "/", sizeof(c->sbuf));
506 strlcat(c->sbuf, path, sizeof(c->sbuf));
507 break;
508 case 'q':
509 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
510 break;
511 case 'P':
512 snprintf(buf, sizeof(buf), "%d", conf->port);
513 strlcat(c->sbuf, buf, sizeof(c->sbuf));
514 memset(buf, 0, sizeof(buf));
515 break;
516 case 'N':
517 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
518 break;
519 default:
520 fatalx("%s: unknown fmt specifier %c",
521 __func__, *fmt);
525 if (i != 0)
526 strlcat(c->sbuf, buf, sizeof(c->sbuf));
529 /* 1 if a matching `block return' (and apply it), 0 otherwise */
530 static int
531 apply_block_return(struct client *c)
533 const char *fmt, *path;
534 int code;
536 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
537 return 0;
539 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
540 fmt_sbuf(fmt, c, path);
542 start_reply(c, code, c->sbuf);
543 return 1;
546 static struct proxy *
547 matched_proxy(struct client *c)
549 struct proxy *p;
550 const char *proto;
551 const char *host;
552 const char *port;
554 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
555 if (*(proto = p->match_proto) == '\0')
556 proto = "gemini";
557 if (*(host = p->match_host) == '\0')
558 host = "*";
559 if (*(port = p->match_port) == '\0')
560 port = "*";
562 if (matches(proto, c->iri.schema) &&
563 matches(host, c->domain) &&
564 matches(port, c->iri.port))
565 return p;
568 return NULL;
571 static int
572 check_matching_certificate(X509_STORE *store, struct client *c)
574 const uint8_t *cert;
575 size_t len;
577 if (!tls_peer_cert_provided(c->ctx)) {
578 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
579 return 1;
582 cert = tls_peer_cert_chain_pem(c->ctx, &len);
583 if (!validate_against_ca(store, cert, len)) {
584 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
585 return 1;
588 return 0;
591 static int
592 proxy_socket(struct client *c, const char *host, const char *port)
594 struct addrinfo hints, *res, *res0;
595 int r, sock, save_errno;
596 const char *cause = NULL;
598 memset(&hints, 0, sizeof(hints));
599 hints.ai_family = AF_UNSPEC;
600 hints.ai_socktype = SOCK_STREAM;
602 /* XXX: asr_run? :> */
603 r = getaddrinfo(host, port, &hints, &res0);
604 if (r != 0) {
605 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
606 host, port, gai_strerror(r));
607 return -1;
610 for (res = res0; res; res = res->ai_next) {
611 sock = socket(res->ai_family, res->ai_socktype,
612 res->ai_protocol);
613 if (sock == -1) {
614 cause = "socket";
615 continue;
618 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
619 cause = "connect";
620 save_errno = errno;
621 close(sock);
622 errno = save_errno;
623 sock = -1;
624 continue;
627 break;
630 if (sock == -1)
631 log_warn("can't connect to %s:%s: %s", host, port, cause);
633 freeaddrinfo(res0);
635 return sock;
638 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
639 static int
640 apply_reverse_proxy(struct client *c)
642 struct proxy *p;
644 if ((p = matched_proxy(c)) == NULL)
645 return 0;
647 c->proxy = p;
649 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
650 return 1;
652 log_debug("opening proxy connection for %s:%s",
653 p->host, p->port);
655 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
656 start_reply(c, PROXY_ERROR, "proxy error");
657 return 1;
660 mark_nonblock(c->pfd);
661 if (proxy_init(c) == -1)
662 start_reply(c, PROXY_ERROR, "proxy error");
664 return 1;
667 static int
668 fcgi_open_sock(struct fcgi *f)
670 struct sockaddr_un addr;
671 int fd;
673 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
674 log_warn("socket");
675 return -1;
678 memset(&addr, 0, sizeof(addr));
679 addr.sun_family = AF_UNIX;
680 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
682 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
683 log_warn("failed to connect to %s", f->path);
684 close(fd);
685 return -1;
688 return fd;
691 static int
692 fcgi_open_conn(struct fcgi *f)
694 struct addrinfo hints, *servinfo, *p;
695 int r, sock, save_errno;
696 const char *cause = NULL;
698 memset(&hints, 0, sizeof(hints));
699 hints.ai_family = AF_UNSPEC;
700 hints.ai_socktype = SOCK_STREAM;
701 hints.ai_flags = AI_ADDRCONFIG;
703 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
704 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
705 gai_strerror(r));
706 return -1;
709 for (p = servinfo; p != NULL; p = p->ai_next) {
710 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
711 if (sock == -1) {
712 cause = "socket";
713 continue;
715 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
716 cause = "connect";
717 save_errno = errno;
718 close(sock);
719 errno = save_errno;
720 continue;
722 break;
725 if (p == NULL) {
726 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
727 cause);
728 sock = -1;
731 freeaddrinfo(servinfo);
732 return sock;
735 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
736 static int
737 apply_fastcgi(struct client *c)
739 int id, i = 0;
740 struct fcgi *f;
742 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
743 return 0;
745 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
746 if (i == id)
747 break;
748 ++i;
751 if (f == NULL) {
752 log_warnx("can't find fcgi #%d", id);
753 return 0;
756 log_debug("opening fastcgi connection for (%s,%s)",
757 f->path, f->port);
759 if (*f->port == '\0')
760 c->pfd = fcgi_open_sock(f);
761 else
762 c->pfd = fcgi_open_conn(f);
764 if (c->pfd == -1) {
765 start_reply(c, CGI_ERROR, "CGI error");
766 return 1;
769 mark_nonblock(c->pfd);
771 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
772 fcgi_error, c);
773 if (c->cgibev == NULL) {
774 start_reply(c, TEMP_FAILURE, "internal server error");
775 return 1;
778 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
779 fcgi_req(c);
781 return 1;
784 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
785 static int
786 apply_require_ca(struct client *c)
788 X509_STORE *store;
790 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
791 return 0;
792 return check_matching_certificate(store, c);
795 static void
796 open_dir(struct client *c)
798 size_t len;
799 int dirfd, root;
800 char *before_file;
802 log_debug("in open_dir");
804 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
806 len = strlen(c->iri.path);
807 if (len > 0 && !ends_with(c->iri.path, "/")) {
808 redirect_canonical_dir(c);
809 return;
812 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
813 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
814 if (!ends_with(c->sbuf, "/"))
815 strlcat(c->sbuf, "/", sizeof(c->sbuf));
816 before_file = strchr(c->sbuf, '\0');
817 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
818 sizeof(c->sbuf));
819 if (len >= sizeof(c->sbuf)) {
820 start_reply(c, TEMP_FAILURE, "internal server error");
821 return;
824 c->iri.path = c->sbuf;
826 /* close later unless we have to generate the dir listing */
827 dirfd = c->pfd;
828 c->pfd = -1;
830 switch (check_path(c, c->iri.path, &c->pfd)) {
831 case FILE_EXISTS:
832 c->type = REQUEST_FILE;
833 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
834 break;
836 case FILE_DIRECTORY:
837 start_reply(c, TEMP_REDIRECT, c->sbuf);
838 break;
840 case FILE_MISSING:
841 *before_file = '\0';
843 if (!vhost_auto_index(c->host, c->iri.path)) {
844 start_reply(c, NOT_FOUND, "not found");
845 break;
848 c->type = REQUEST_DIR;
850 c->dirlen = scandir_fd(dirfd, &c->dir,
851 root ? select_non_dotdot : select_non_dot,
852 alphasort);
853 if (c->dirlen == -1) {
854 log_warn("scandir_fd(%d) (vhost:%s) %s",
855 c->pfd, c->host->domain, c->iri.path);
856 start_reply(c, TEMP_FAILURE, "internal server error");
857 return;
859 c->diroff = 0;
860 c->off = 0;
862 start_reply(c, SUCCESS, "text/gemini");
863 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
864 "# Index of %s\n\n", c->iri.path);
865 return;
867 default:
868 /* unreachable */
869 abort();
872 close(dirfd);
875 static void
876 redirect_canonical_dir(struct client *c)
878 size_t len;
880 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
881 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
882 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
884 if (len >= sizeof(c->sbuf)) {
885 start_reply(c, TEMP_FAILURE, "internal server error");
886 return;
889 start_reply(c, TEMP_REDIRECT, c->sbuf);
892 static void
893 client_tls_readcb(int fd, short event, void *d)
895 struct bufferevent *bufev = d;
896 struct client *client = bufev->cbarg;
897 ssize_t ret;
898 size_t len;
899 int what = EVBUFFER_READ;
900 int howmuch = IBUF_READ_SIZE;
901 char buf[IBUF_READ_SIZE];
903 if (event == EV_TIMEOUT) {
904 what |= EVBUFFER_TIMEOUT;
905 goto err;
908 if (bufev->wm_read.high != 0)
909 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
911 switch (ret = tls_read(client->ctx, buf, howmuch)) {
912 case TLS_WANT_POLLIN:
913 case TLS_WANT_POLLOUT:
914 goto retry;
915 case -1:
916 what |= EVBUFFER_ERROR;
917 goto err;
919 len = ret;
921 if (len == 0) {
922 what |= EVBUFFER_EOF;
923 goto err;
926 if (evbuffer_add(bufev->input, buf, len) == -1) {
927 what |= EVBUFFER_ERROR;
928 goto err;
931 event_add(&bufev->ev_read, NULL);
932 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
933 return;
934 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
935 /*
936 * here we could implement a read pressure policy.
937 */
940 if (bufev->readcb != NULL)
941 (*bufev->readcb)(bufev, bufev->cbarg);
943 return;
945 retry:
946 event_add(&bufev->ev_read, NULL);
947 return;
949 err:
950 (*bufev->errorcb)(bufev, what, bufev->cbarg);
953 static void
954 client_tls_writecb(int fd, short event, void *d)
956 struct bufferevent *bufev = d;
957 struct client *client = bufev->cbarg;
958 ssize_t ret;
959 size_t len;
960 short what = EVBUFFER_WRITE;
962 if (event == EV_TIMEOUT) {
963 what |= EVBUFFER_TIMEOUT;
964 goto err;
967 if (EVBUFFER_LENGTH(bufev->output) != 0) {
968 ret = tls_write(client->ctx,
969 EVBUFFER_DATA(bufev->output),
970 EVBUFFER_LENGTH(bufev->output));
971 switch (ret) {
972 case TLS_WANT_POLLIN:
973 case TLS_WANT_POLLOUT:
974 goto retry;
975 case -1:
976 what |= EVBUFFER_ERROR;
977 goto err;
979 len = ret;
980 evbuffer_drain(bufev->output, len);
983 if (EVBUFFER_LENGTH(bufev->output) != 0)
984 event_add(&bufev->ev_write, NULL);
986 if (bufev->writecb != NULL &&
987 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
988 (*bufev->writecb)(bufev, bufev->cbarg);
989 return;
991 retry:
992 event_add(&bufev->ev_write, NULL);
993 return;
994 err:
995 log_warnx("tls error: %s", tls_error(client->ctx));
996 (*bufev->errorcb)(bufev, what, bufev->cbarg);
999 static void
1000 client_read(struct bufferevent *bev, void *d)
1002 struct client *c = d;
1003 struct evbuffer *src = EVBUFFER_INPUT(bev);
1004 const char *parse_err = "invalid request";
1005 char decoded[DOMAIN_NAME_LEN];
1006 size_t len;
1008 bufferevent_disable(bev, EVBUFFER_READ);
1011 * libevent2 can still somehow call this function, even
1012 * though I never enable EV_READ in the bufferevent. If
1013 * that's the case, bail out.
1015 if (c->type != REQUEST_UNDECIDED)
1016 return;
1018 /* max url len + \r\n */
1019 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1020 log_debug("too much data received");
1021 start_reply(c, BAD_REQUEST, "bad request");
1022 return;
1025 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1026 if (c->req == NULL) {
1027 /* not enough data yet. */
1028 bufferevent_enable(bev, EVBUFFER_READ);
1029 return;
1031 c->reqlen = strlen(c->req);
1032 if (c->reqlen > 1024+2) {
1033 log_debug("URL too long");
1034 start_reply(c, BAD_REQUEST, "bad request");
1035 return;
1038 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1039 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1040 log_debug("IRI parse error: %s", parse_err);
1041 start_reply(c, BAD_REQUEST, "bad request");
1042 return;
1045 if (apply_reverse_proxy(c))
1046 return;
1048 /* ignore the port number */
1049 if (strcmp(c->iri.schema, "gemini") ||
1050 strcmp(decoded, c->domain)) {
1051 start_reply(c, PROXY_REFUSED, "won't proxy request");
1052 return;
1055 if (apply_require_ca(c) ||
1056 apply_block_return(c)||
1057 apply_fastcgi(c))
1058 return;
1060 open_file(c);
1063 void
1064 client_write(struct bufferevent *bev, void *d)
1066 struct client *c = d;
1067 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1068 char nam[PATH_MAX];
1069 char buf[BUFSIZ];
1070 ssize_t r;
1072 switch (c->type) {
1073 case REQUEST_UNDECIDED:
1075 * Ignore spurious calls when we still don't have idea
1076 * what to do with the request.
1078 break;
1080 case REQUEST_FILE:
1081 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1082 log_warn("read");
1083 client_error(bev, EVBUFFER_ERROR, c);
1084 return;
1085 } else if (r == 0) {
1086 client_close(c);
1087 return;
1088 } else if (r != sizeof(buf))
1089 c->type = REQUEST_DONE;
1090 bufferevent_write(bev, buf, r);
1091 break;
1093 case REQUEST_DIR:
1094 /* TODO: handle big big directories better */
1095 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1096 const char *sufx = "";
1098 encode_path(nam, sizeof(nam),
1099 c->dir[c->diroff]->d_name);
1100 if (c->dir[c->diroff]->d_type == DT_DIR)
1101 sufx = "/";
1102 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1103 free(c->dir[c->diroff]);
1105 free(c->dir);
1106 c->dir = NULL;
1108 c->type = REQUEST_DONE;
1110 event_add(&c->bev->ev_write, NULL);
1111 break;
1113 case REQUEST_FCGI:
1114 case REQUEST_PROXY:
1116 * Here we depend on fastcgi or proxy connection to
1117 * provide data.
1119 break;
1121 case REQUEST_DONE:
1122 if (EVBUFFER_LENGTH(out) == 0)
1123 client_close(c);
1124 break;
1128 static void
1129 client_error(struct bufferevent *bev, short error, void *d)
1131 struct client *c = d;
1133 c->type = REQUEST_DONE;
1135 if (error & EVBUFFER_TIMEOUT) {
1136 log_debug("timeout; forcefully closing the connection");
1137 if (c->code == 0)
1138 start_reply(c, BAD_REQUEST, "timeout");
1139 else
1140 client_close(c);
1141 return;
1144 if (error & EVBUFFER_EOF) {
1145 client_close(c);
1146 return;
1149 log_warnx("unknown bufferevent error 0x%x", error);
1150 client_close(c);
1153 void
1154 start_reply(struct client *c, int code, const char *meta)
1156 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1157 const char *lang;
1158 int r, rr;
1160 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1162 c->code = code;
1163 c->meta = meta;
1165 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1166 if (r == -1)
1167 goto err;
1169 /* 2 digit status + space + 1024 max reply */
1170 if (r > 1027)
1171 goto overflow;
1173 if (c->type != REQUEST_FCGI &&
1174 c->type != REQUEST_PROXY &&
1175 !strcmp(meta, "text/gemini") &&
1176 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1177 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1178 if (rr == -1)
1179 goto err;
1180 if (r + rr > 1027)
1181 goto overflow;
1184 bufferevent_write(c->bev, "\r\n", 2);
1186 if (!vhost_disable_log(c->host, c->iri.path))
1187 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1189 if (code != 20)
1190 c->type = REQUEST_DONE;
1192 return;
1194 err:
1195 log_warnx("evbuffer_add_printf error: no memory");
1196 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1197 client_close(c);
1198 return;
1200 overflow:
1201 log_warnx("reply header overflow");
1202 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1203 start_reply(c, TEMP_FAILURE, "internal error");
1206 static void
1207 client_close_ev(int fd, short event, void *d)
1209 struct client *c = d;
1211 switch (tls_close(c->ctx)) {
1212 case TLS_WANT_POLLIN:
1213 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1214 break;
1215 case TLS_WANT_POLLOUT:
1216 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1217 break;
1220 connected_clients--;
1222 free(c->req);
1224 tls_free(c->ctx);
1225 c->ctx = NULL;
1227 free(c->header);
1229 if (c->pfd != -1)
1230 close(c->pfd);
1232 if (c->dir != NULL)
1233 free(c->dir);
1235 close(c->fd);
1236 c->fd = -1;
1239 static void
1240 client_proxy_close(int fd, short event, void *d)
1242 struct tls *ctx = d;
1244 if (ctx == NULL) {
1245 close(fd);
1246 return;
1249 switch (tls_close(ctx)) {
1250 case TLS_WANT_POLLIN:
1251 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1252 break;
1253 case TLS_WANT_POLLOUT:
1254 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1255 break;
1258 tls_free(ctx);
1259 close(fd);
1262 void
1263 client_close(struct client *c)
1266 * We may end up calling client_close in various situations
1267 * and for the most unexpected reasons. Therefore, we need to
1268 * ensure that everything gets properly released once we reach
1269 * this point.
1272 SPLAY_REMOVE(client_tree_id, &clients, c);
1274 if (c->cgibev != NULL) {
1275 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1276 bufferevent_free(c->cgibev);
1277 c->cgibev = NULL;
1278 close(c->pfd);
1279 c->pfd = -1;
1282 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1283 bufferevent_free(c->bev);
1284 c->bev = NULL;
1286 if (c->proxyevset &&
1287 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1288 c->proxyevset = 0;
1289 event_del(&c->proxyev);
1292 if (c->pfd != -1 && c->proxyctx != NULL) {
1293 /* shut down the proxy TLS connection */
1294 client_proxy_close(c->pfd, 0, c->proxyctx);
1295 c->pfd = -1;
1298 if (c->proxybev != NULL)
1299 bufferevent_free(c->proxybev);
1301 client_close_ev(c->fd, 0, c);
1304 void
1305 do_accept(int sock, short et, void *d)
1307 struct conf *conf = d;
1308 struct client *c;
1309 struct sockaddr_storage addr;
1310 struct sockaddr *saddr;
1311 socklen_t len;
1312 int fd;
1314 saddr = (struct sockaddr*)&addr;
1315 len = sizeof(addr);
1316 if ((fd = accept(sock, saddr, &len)) == -1) {
1317 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1318 errno == ECONNABORTED)
1319 return;
1320 fatal("accept");
1323 mark_nonblock(fd);
1325 c = xcalloc(1, sizeof(*c));
1326 c->conf = conf;
1327 c->id = ++server_client_id;
1328 c->fd = fd;
1329 c->pfd = -1;
1330 c->addr = addr;
1332 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1333 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1334 close(c->fd);
1335 free(c);
1336 return;
1339 SPLAY_INSERT(client_tree_id, &clients, c);
1340 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1341 connected_clients++;
1344 struct client *
1345 client_by_id(int id)
1347 struct client find;
1349 find.id = id;
1350 return SPLAY_FIND(client_tree_id, &clients, &find);
1353 static void
1354 handle_siginfo(int fd, short ev, void *d)
1356 log_info("%d connected clients", connected_clients);
1359 static void
1360 add_keypair(struct vhost *h, struct tls_config *conf)
1362 if (h->ocsp == NULL) {
1363 if (tls_config_add_keypair_mem(conf, h->cert, h->certlen,
1364 h->key, h->keylen) == -1)
1365 fatalx("failed to load the keypair: %s",
1366 tls_config_error(conf));
1367 } else {
1368 if (tls_config_add_keypair_ocsp_mem(conf, h->cert, h->certlen,
1369 h->key, h->keylen, h->ocsp, h->ocsplen) == -1)
1370 fatalx("failed to load the keypair: %s",
1371 tls_config_error(conf));
1375 static void
1376 setup_tls(struct conf *conf)
1378 struct tls_config *tlsconf;
1379 struct vhost *h;
1381 if (ctx == NULL) {
1382 if ((ctx = tls_server()) == NULL)
1383 fatal("tls_server failure");
1386 if ((tlsconf = tls_config_new()) == NULL)
1387 fatal("tls_config_new");
1389 /* optionally accept client certs, but don't try to verify them */
1390 tls_config_verify_client_optional(tlsconf);
1391 tls_config_insecure_noverifycert(tlsconf);
1393 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1394 fatalx("tls_config_set_protocols: %s",
1395 tls_config_error(tlsconf));
1397 h = TAILQ_FIRST(&conf->hosts);
1399 /* we need to set something, then we can add how many key we want */
1400 if (tls_config_set_keypair_mem(tlsconf, h->cert, h->certlen,
1401 h->key, h->keylen) == -1)
1402 fatalx("tls_config_set_keypair_mem failed: %s",
1403 tls_config_error(tlsconf));
1405 /* same for OCSP */
1406 if (h->ocsp != NULL &&
1407 tls_config_set_ocsp_staple_mem(tlsconf, h->ocsp, h->ocsplen)
1408 == -1)
1409 fatalx("tls_config_set_ocsp_staple_file failed: %s",
1410 tls_config_error(tlsconf));
1412 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1413 add_keypair(h, tlsconf);
1415 tls_reset(ctx);
1416 if (tls_configure(ctx, tlsconf) == -1)
1417 fatalx("tls_configure: %s", tls_error(ctx));
1419 tls_config_free(tlsconf);
1422 static void
1423 load_vhosts(struct conf *conf)
1425 struct vhost *h;
1426 struct location *l;
1428 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1429 TAILQ_FOREACH(l, &h->locations, locations) {
1430 if (*l->dir == '\0')
1431 continue;
1432 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1433 if (l->dirfd == -1)
1434 fatal("open %s for domain %s", l->dir,
1435 h->domain);
1440 void
1441 server(struct privsep *ps, struct privsep_proc *p)
1443 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1446 void
1447 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1449 SPLAY_INIT(&clients);
1451 #ifdef SIGINFO
1452 has_siginfo = 1;
1453 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1454 signal_add(&siginfo, NULL);
1455 #endif
1456 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1457 signal_add(&sigusr2, NULL);
1459 sandbox_server_process();
1462 int
1463 server_configure_done(struct conf *conf)
1465 if (load_default_mime(&conf->mime) == -1)
1466 fatal("can't load default mime");
1467 sort_mime(&conf->mime);
1468 setup_tls(conf);
1469 load_vhosts(conf);
1470 if (conf->sock4 != -1)
1471 event_add(&conf->evsock4, NULL);
1472 if (conf->sock6 != -1)
1473 event_add(&conf->evsock6, NULL);
1475 return 0;
1478 static int
1479 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1481 struct privsep *ps = p->p_ps;
1482 struct conf *conf = ps->ps_env;
1484 switch (imsg->hdr.type) {
1485 case IMSG_RECONF_START:
1486 case IMSG_RECONF_MIME:
1487 case IMSG_RECONF_PROTOS:
1488 case IMSG_RECONF_PORT:
1489 case IMSG_RECONF_SOCK4:
1490 case IMSG_RECONF_SOCK6:
1491 case IMSG_RECONF_FCGI:
1492 case IMSG_RECONF_HOST:
1493 case IMSG_RECONF_CERT:
1494 case IMSG_RECONF_KEY:
1495 case IMSG_RECONF_OCSP:
1496 case IMSG_RECONF_LOC:
1497 case IMSG_RECONF_ENV:
1498 case IMSG_RECONF_ALIAS:
1499 case IMSG_RECONF_PROXY:
1500 case IMSG_RECONF_PROXY_CERT:
1501 case IMSG_RECONF_PROXY_KEY:
1502 return config_recv(conf, imsg);
1503 case IMSG_RECONF_END:
1504 if (config_recv(conf, imsg) == -1)
1505 return -1;
1506 if (server_configure_done(conf) == -1)
1507 return -1;
1508 break;
1509 default:
1510 return -1;
1513 return 0;
1515 static int
1516 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1518 return -1;
1521 int
1522 client_tree_cmp(struct client *a, struct client *b)
1524 if (a->id == b->id)
1525 return 0;
1526 else if (a->id < b->id)
1527 return -1;
1528 else
1529 return +1;
1532 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)