Blob


1 /*
2 * Copyright (c) 2021, 2022, 2023 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 <ctype.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <fnmatch.h>
27 #include <limits.h>
28 #include <string.h>
30 #include "log.h"
31 #include "proc.h"
33 #define MINIMUM(a, b) ((a) < (b) ? (a) : (b))
35 #ifndef nitems
36 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
37 #endif
39 #ifdef SIGINFO
40 static struct event siginfo;
41 #endif
42 static struct event sigusr2;
44 int connected_clients;
46 /*
47 * This function is not publicy exported because it is a hack until libtls
48 * has a proper privsep setup.
49 */
50 void tls_config_use_fake_private_key(struct tls_config *);
52 static inline int matches(const char*, const char*);
54 static void handle_handshake(int, short, void*);
55 static void fmtbuf(char *, size_t, const char *, struct client *,
56 const char *);
57 static int apply_block_return(struct client*);
58 static int check_matching_certificate(X509_STORE *, struct client *);
59 static int apply_reverse_proxy(struct client *);
60 static int apply_fastcgi(struct client*);
61 static int apply_require_ca(struct client*);
62 static void open_dir(struct client*);
63 static void redirect_canonical_dir(struct client*);
65 static void client_tls_readcb(int, short, void *);
66 static void client_tls_writecb(int, short, void *);
68 static void client_read(struct bufferevent *, void *);
69 void client_write(struct bufferevent *, void *);
70 static void client_error(struct bufferevent *, short, void *);
72 static void client_close_ev(int, short, void *);
74 static void handle_siginfo(int, short, void*);
76 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
77 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
78 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
80 static ssize_t read_cb(struct tls *, void *, size_t, void *);
81 static ssize_t write_cb(struct tls *, const void *, size_t, void *);
83 static struct privsep_proc procs[] = {
84 { "parent", PROC_PARENT, server_dispatch_parent },
85 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
86 { "logger", PROC_LOGGER, server_dispatch_logger },
87 };
89 static uint32_t server_client_id;
91 struct client_tree_id clients;
93 static inline int
94 match_addr(struct address *target, struct address *source)
95 {
96 return (target->ai_flags == source->ai_flags &&
97 target->ai_family == source->ai_family &&
98 target->ai_socktype == source->ai_socktype &&
99 target->ai_protocol == source->ai_protocol &&
100 target->slen == source->slen &&
101 !memcmp(&target->ss, &source->ss, target->slen));
104 static inline int
105 matches(const char *pattern, const char *path)
107 if (*path == '/')
108 path++;
109 return !fnmatch(pattern, path, 0);
112 static inline int
113 match_host(struct vhost *v, struct client *c)
115 struct alist *a;
116 struct address *addr;
118 TAILQ_FOREACH(addr, &v->addrs, addrs)
119 if (match_addr(addr, c->addr))
120 break;
121 if (addr == NULL)
122 return 0;
124 if (*c->domain == '\0') {
125 if (strlcpy(c->domain, addr->pp, sizeof(c->domain))
126 >= sizeof(c->domain)) {
127 log_warnx("%s: domain too long: %s", __func__,
128 addr->pp);
129 *c->domain = '\0';
133 if (matches(v->domain, c->domain))
134 return 1;
136 TAILQ_FOREACH(a, &v->aliases, aliases)
137 if (matches(a->alias, c->domain))
138 return 1;
140 return 0;
143 const char *
144 vhost_lang(struct vhost *v, const char *path)
146 struct location *loc;
148 if (v == NULL || path == NULL)
149 return NULL;
151 loc = TAILQ_FIRST(&v->locations);
152 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
153 if (*loc->lang != '\0') {
154 if (matches(loc->match, path))
155 return loc->lang;
159 loc = TAILQ_FIRST(&v->locations);
160 if (*loc->lang == '\0')
161 return NULL;
162 return loc->lang;
165 const char *
166 vhost_default_mime(struct vhost *v, const char *path)
168 struct location *loc;
169 const char *default_mime = "application/octet-stream";
171 if (v == NULL || path == NULL)
172 return default_mime;
174 loc = TAILQ_FIRST(&v->locations);
175 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
176 if (*loc->default_mime != '\0') {
177 if (matches(loc->match, path))
178 return loc->default_mime;
182 loc = TAILQ_FIRST(&v->locations);
183 if (*loc->default_mime != '\0')
184 return loc->default_mime;
185 return default_mime;
188 const char *
189 vhost_index(struct vhost *v, const char *path)
191 struct location *loc;
192 const char *index = "index.gmi";
194 if (v == NULL || path == NULL)
195 return index;
197 loc = TAILQ_FIRST(&v->locations);
198 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
199 if (*loc->index != '\0') {
200 if (matches(loc->match, path))
201 return loc->index;
205 loc = TAILQ_FIRST(&v->locations);
206 if (*loc->index != '\0')
207 return loc->index;
208 return index;
211 int
212 vhost_auto_index(struct vhost *v, const char *path)
214 struct location *loc;
216 if (v == NULL || path == NULL)
217 return 0;
219 loc = TAILQ_FIRST(&v->locations);
220 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
221 if (loc->auto_index != 0) {
222 if (matches(loc->match, path))
223 return loc->auto_index == 1;
227 loc = TAILQ_FIRST(&v->locations);
228 return loc->auto_index == 1;
231 int
232 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
234 struct location *loc;
236 if (v == NULL || path == NULL)
237 return 0;
239 loc = TAILQ_FIRST(&v->locations);
240 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
241 if (loc->block_code != 0) {
242 if (matches(loc->match, path)) {
243 *code = loc->block_code;
244 *fmt = loc->block_fmt;
245 return 1;
250 loc = TAILQ_FIRST(&v->locations);
251 *code = loc->block_code;
252 *fmt = loc->block_fmt;
253 return loc->block_code != 0;
256 struct location *
257 vhost_fastcgi(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->fcgi != -1)
267 if (matches(loc->match, path))
268 return loc;
269 if (loc->nofcgi && matches(loc->match, path))
270 return NULL;
273 loc = TAILQ_FIRST(&v->locations);
274 return loc->fcgi == -1 ? NULL : loc;
277 int
278 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
280 struct location *loc;
281 size_t l = 0;
283 if (v == NULL || path == NULL)
284 return -1;
286 loc = TAILQ_FIRST(&v->locations);
287 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
288 l++;
289 if (loc->dirfd != -1)
290 if (matches(loc->match, path)) {
291 *retloc = l;
292 return loc->dirfd;
296 *retloc = 0;
297 loc = TAILQ_FIRST(&v->locations);
298 return loc->dirfd;
301 int
302 vhost_strip(struct vhost *v, const char *path)
304 struct location *loc;
306 if (v == NULL || path == NULL)
307 return 0;
309 loc = TAILQ_FIRST(&v->locations);
310 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
311 if (loc->strip != 0) {
312 if (matches(loc->match, path))
313 return loc->strip;
317 loc = TAILQ_FIRST(&v->locations);
318 return loc->strip;
321 X509_STORE *
322 vhost_require_ca(struct vhost *v, const char *path)
324 struct location *loc;
326 if (v == NULL || path == NULL)
327 return NULL;
329 loc = TAILQ_FIRST(&v->locations);
330 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
331 if (loc->reqca != NULL) {
332 if (matches(loc->match, path))
333 return loc->reqca;
337 loc = TAILQ_FIRST(&v->locations);
338 return loc->reqca;
341 int
342 vhost_disable_log(struct vhost *v, const char *path)
344 struct location *loc;
346 if (v == NULL || path == NULL)
347 return 0;
349 loc = TAILQ_FIRST(&v->locations);
350 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
351 if (loc->disable_log && matches(loc->match, path))
352 return 1;
355 loc = TAILQ_FIRST(&v->locations);
356 return loc->disable_log;
359 void
360 mark_nonblock(int fd)
362 int flags;
364 if ((flags = fcntl(fd, F_GETFL)) == -1)
365 fatal("fcntl(F_GETFL)");
366 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
367 fatal("fcntl(F_SETFL)");
370 static void
371 handle_handshake(int fd, short ev, void *d)
373 struct client *c = d;
374 struct conf *conf = c->conf;
375 struct vhost *h;
376 const char *servname;
377 const char *parse_err = "unknown error";
379 switch (tls_handshake(c->ctx)) {
380 case 0: /* success */
381 break;
382 case -1:
383 log_warnx("(%s:%s) tls_handshake failed: %s",
384 c->rhost, c->rserv, tls_error(c->ctx));
385 client_close(c);
386 return;
387 case TLS_WANT_POLLIN:
388 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
389 return;
390 case TLS_WANT_POLLOUT:
391 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
392 return;
393 default:
394 /* unreachable */
395 fatalx("unexpected return value from tls_handshake");
398 c->bev = bufferevent_new(fd, client_read, client_write,
399 client_error, c);
400 if (c->bev == NULL)
401 fatal("%s: failed to allocate client buffer", __func__);
403 event_set(&c->bev->ev_read, c->fd, EV_READ,
404 client_tls_readcb, c->bev);
405 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
406 client_tls_writecb, c->bev);
408 #if HAVE_LIBEVENT2
409 evbuffer_unfreeze(c->bev->input, 0);
410 evbuffer_unfreeze(c->bev->output, 1);
411 #endif
413 if ((servname = tls_conn_servername(c->ctx)) == NULL)
414 log_debug("handshake: missing SNI");
415 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
416 log_info("puny_decode: %s", parse_err);
417 start_reply(c, BAD_REQUEST, "Wrong/malformed host");
418 return;
421 /*
422 * match_addr will serialize the (matching) address if c->domain
423 * is empty, so that we can support requests for raw IPv6 address
424 * that can't have a SNI.
425 */
426 TAILQ_FOREACH(h, &conf->hosts, vhosts)
427 if (match_host(h, c))
428 break;
430 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
431 servname != NULL ? servname : "(null)",
432 c->domain,
433 h != NULL ? h->domain : "(null)");
435 if (h != NULL) {
436 c->host = h;
437 bufferevent_enable(c->bev, EV_READ);
438 return;
441 start_reply(c, BAD_REQUEST, "Wrong/malformed host");
444 static void
445 fmtbuf(char *buf, size_t buflen, const char *fmt, struct client *c,
446 const char *path)
448 size_t i;
449 char tmp[32];
451 *buf = '\0';
452 memset(tmp, 0, sizeof(tmp));
453 for (i = 0; *fmt; ++fmt) {
454 if (i == sizeof(tmp)-1 || *fmt == '%') {
455 strlcat(buf, tmp, buflen);
456 memset(tmp, 0, sizeof(tmp));
457 i = 0;
460 if (*fmt != '%') {
461 tmp[i++] = *fmt;
462 continue;
465 switch (*++fmt) {
466 case '%':
467 strlcat(buf, "%", buflen);
468 break;
469 case 'p':
470 if (*path != '/')
471 strlcat(buf, "/", buflen);
472 strlcat(buf, path, buflen);
473 break;
474 case 'q':
475 strlcat(buf, c->iri.query, buflen);
476 break;
477 case 'P':
478 snprintf(tmp, sizeof(tmp), "%d", c->addr->port);
479 strlcat(buf, tmp, buflen);
480 memset(tmp, 0, sizeof(tmp));
481 break;
482 case 'N':
483 strlcat(buf, c->domain, buflen);
484 break;
485 default:
486 log_warnx("%s: unknown fmt specifier %c",
487 __func__, *fmt);
491 if (i != 0)
492 strlcat(buf, tmp, buflen);
495 /* 1 if a matching `block return' (and apply it), 0 otherwise */
496 static int
497 apply_block_return(struct client *c)
499 char buf[GEMINI_URL_LEN];
500 const char *fmt, *path;
501 int code;
503 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
504 return 0;
506 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
507 fmtbuf(buf, sizeof(buf), fmt, c, path);
509 start_reply(c, code, buf);
510 return 1;
513 static struct proxy *
514 matched_proxy(struct client *c)
516 struct proxy *p;
517 const char *proto;
518 const char *host;
519 const char *port;
521 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
522 if (*(proto = p->match_proto) == '\0')
523 proto = "gemini";
524 if (*(host = p->match_host) == '\0')
525 host = "*";
526 if (*(port = p->match_port) == '\0')
527 port = "*";
529 if (matches(proto, c->iri.schema) &&
530 matches(host, c->domain) &&
531 matches(port, c->iri.port))
532 return p;
535 return NULL;
538 static int
539 check_matching_certificate(X509_STORE *store, struct client *c)
541 const uint8_t *cert;
542 size_t len;
544 if (!tls_peer_cert_provided(c->ctx)) {
545 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
546 return 1;
549 cert = tls_peer_cert_chain_pem(c->ctx, &len);
550 if (!validate_against_ca(store, cert, len)) {
551 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
552 return 1;
555 return 0;
558 static int
559 proxy_socket(struct client *c, const char *host, const char *port)
561 struct addrinfo hints, *res, *res0;
562 int r, sock, save_errno;
563 const char *cause = NULL;
565 memset(&hints, 0, sizeof(hints));
566 hints.ai_family = AF_UNSPEC;
567 hints.ai_socktype = SOCK_STREAM;
569 /* XXX: asr_run? :> */
570 r = getaddrinfo(host, port, &hints, &res0);
571 if (r != 0) {
572 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
573 host, port, gai_strerror(r));
574 return -1;
577 for (res = res0; res; res = res->ai_next) {
578 sock = socket(res->ai_family, res->ai_socktype,
579 res->ai_protocol);
580 if (sock == -1) {
581 cause = "socket";
582 continue;
585 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
586 cause = "connect";
587 save_errno = errno;
588 close(sock);
589 errno = save_errno;
590 sock = -1;
591 continue;
594 break;
597 if (sock == -1)
598 log_warn("can't connect to %s:%s: %s", host, port, cause);
600 freeaddrinfo(res0);
602 return sock;
605 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
606 static int
607 apply_reverse_proxy(struct client *c)
609 struct proxy *p;
611 if ((p = matched_proxy(c)) == NULL)
612 return 0;
614 c->proxy = p;
616 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
617 return 1;
619 log_debug("opening proxy connection for %s:%s", p->host, p->port);
621 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
622 start_reply(c, PROXY_ERROR, "proxy error");
623 return 1;
626 mark_nonblock(c->pfd);
627 if (proxy_init(c) == -1)
628 start_reply(c, PROXY_ERROR, "proxy error");
630 return 1;
633 static int
634 fcgi_open_sock(struct fcgi *f)
636 struct sockaddr_un addr;
637 int fd;
639 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
640 log_warn("socket");
641 return -1;
644 memset(&addr, 0, sizeof(addr));
645 addr.sun_family = AF_UNIX;
646 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
648 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
649 log_warn("failed to connect to %s", f->path);
650 close(fd);
651 return -1;
654 return fd;
657 static int
658 fcgi_open_conn(struct fcgi *f)
660 struct addrinfo hints, *servinfo, *p;
661 int r, sock, save_errno;
662 const char *cause = NULL;
664 memset(&hints, 0, sizeof(hints));
665 hints.ai_family = AF_UNSPEC;
666 hints.ai_socktype = SOCK_STREAM;
667 hints.ai_flags = AI_ADDRCONFIG;
669 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
670 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
671 gai_strerror(r));
672 return -1;
675 for (p = servinfo; p != NULL; p = p->ai_next) {
676 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
677 if (sock == -1) {
678 cause = "socket";
679 continue;
681 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
682 cause = "connect";
683 save_errno = errno;
684 close(sock);
685 errno = save_errno;
686 continue;
688 break;
691 if (p == NULL) {
692 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
693 cause);
694 sock = -1;
697 freeaddrinfo(servinfo);
698 return sock;
701 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
702 static int
703 apply_fastcgi(struct client *c)
705 int i = 0;
706 struct fcgi *f;
707 struct location *loc;
709 if ((loc = vhost_fastcgi(c->host, c->iri.path)) == NULL)
710 return 0;
712 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
713 if (i == loc->fcgi)
714 break;
715 ++i;
718 if (f == NULL) {
719 log_warnx("can't find fcgi #%d", loc->fcgi);
720 return 0;
723 log_debug("opening fastcgi connection for (%s,%s)", f->path, f->port);
725 if (*f->port == '\0')
726 c->pfd = fcgi_open_sock(f);
727 else
728 c->pfd = fcgi_open_conn(f);
730 if (c->pfd == -1) {
731 start_reply(c, CGI_ERROR, "CGI error");
732 return 1;
735 mark_nonblock(c->pfd);
737 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
738 fcgi_error, c);
739 if (c->cgibev == NULL) {
740 start_reply(c, TEMP_FAILURE, "internal server error");
741 return 1;
744 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
745 fcgi_req(c, loc);
747 return 1;
750 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
751 static int
752 apply_require_ca(struct client *c)
754 X509_STORE *store;
756 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
757 return 0;
758 return check_matching_certificate(store, c);
761 static void
762 server_dir_listing(struct client *c)
764 int root;
766 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
768 if (!vhost_auto_index(c->host, c->iri.path)) {
769 start_reply(c, NOT_FOUND, "not found");
770 return;
773 c->dirlen = scandir_fd(c->pfd, &c->dir,
774 root ? select_non_dotdot : select_non_dot,
775 alphasort);
776 if (c->dirlen == -1) {
777 log_warn("scandir_fd(%d) (vhost:%s) %s",
778 c->pfd, c->host->domain, c->iri.path);
779 start_reply(c, TEMP_FAILURE, "internal server error");
780 return;
783 c->type = REQUEST_DIR;
784 start_reply(c, SUCCESS, "text/gemini");
785 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
786 "# Index of /%s\n\n", c->iri.path);
789 static void
790 open_dir(struct client *c)
792 struct stat sb;
793 const char *index;
794 char path[PATH_MAX];
795 int fd = -1;
797 if (*c->iri.path != '\0' && !ends_with(c->iri.path, "/")) {
798 redirect_canonical_dir(c);
799 return;
802 index = vhost_index(c->host, c->iri.path);
803 fd = openat(c->pfd, index, O_RDONLY);
804 if (fd == -1) {
805 server_dir_listing(c);
806 return;
809 if (fstat(fd, &sb) == -1) {
810 log_warn("fstat");
811 close(fd);
812 start_reply(c, TEMP_FAILURE, "internal server error");
813 return;
816 if (!S_ISREG(sb.st_mode)) {
817 close(fd);
818 server_dir_listing(c);
819 return;
822 snprintf(path, sizeof(path), "%s%s", c->iri.path, index);
824 close(c->pfd);
825 c->pfd = fd;
826 c->type = REQUEST_FILE;
827 start_reply(c, SUCCESS, mime(c->conf, c->host, path));
830 static void
831 redirect_canonical_dir(struct client *c)
833 char buf[GEMINI_URL_LEN];
834 int r;
836 r = snprintf(buf, sizeof(buf), "/%s/", c->iri.path);
837 if (r < 0 || (size_t)r >= sizeof(buf)) {
838 start_reply(c, TEMP_FAILURE, "internal server error");
839 return;
842 start_reply(c, TEMP_REDIRECT, buf);
845 static void
846 client_tls_readcb(int fd, short event, void *d)
848 struct bufferevent *bufev = d;
849 struct client *client = bufev->cbarg;
850 ssize_t ret;
851 size_t len;
852 int what = EVBUFFER_READ;
853 int howmuch = IBUF_READ_SIZE;
854 char buf[IBUF_READ_SIZE];
856 if (event == EV_TIMEOUT) {
857 what |= EVBUFFER_TIMEOUT;
858 goto err;
861 if (bufev->wm_read.high != 0)
862 howmuch = MINIMUM(sizeof(buf), bufev->wm_read.high);
864 switch (ret = tls_read(client->ctx, buf, howmuch)) {
865 case TLS_WANT_POLLIN:
866 case TLS_WANT_POLLOUT:
867 goto retry;
868 case -1:
869 what |= EVBUFFER_ERROR;
870 goto err;
872 len = ret;
874 if (len == 0) {
875 what |= EVBUFFER_EOF;
876 goto err;
879 if (evbuffer_add(bufev->input, buf, len) == -1) {
880 what |= EVBUFFER_ERROR;
881 goto err;
884 event_add(&bufev->ev_read, NULL);
885 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
886 return;
887 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
888 /*
889 * here we could implement a read pressure policy.
890 */
893 if (bufev->readcb != NULL)
894 (*bufev->readcb)(bufev, bufev->cbarg);
896 return;
898 retry:
899 event_add(&bufev->ev_read, NULL);
900 return;
902 err:
903 (*bufev->errorcb)(bufev, what, bufev->cbarg);
906 static void
907 client_tls_writecb(int fd, short event, void *d)
909 struct bufferevent *bufev = d;
910 struct client *client = bufev->cbarg;
911 ssize_t ret;
912 size_t len;
913 short what = EVBUFFER_WRITE;
915 if (event == EV_TIMEOUT) {
916 what |= EVBUFFER_TIMEOUT;
917 goto err;
920 if (EVBUFFER_LENGTH(bufev->output) != 0) {
921 ret = tls_write(client->ctx,
922 EVBUFFER_DATA(bufev->output),
923 EVBUFFER_LENGTH(bufev->output));
924 switch (ret) {
925 case TLS_WANT_POLLIN:
926 case TLS_WANT_POLLOUT:
927 goto retry;
928 case -1:
929 what |= EVBUFFER_ERROR;
930 goto err;
932 len = ret;
933 evbuffer_drain(bufev->output, len);
936 if (EVBUFFER_LENGTH(bufev->output) != 0)
937 event_add(&bufev->ev_write, NULL);
939 if (bufev->writecb != NULL &&
940 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
941 (*bufev->writecb)(bufev, bufev->cbarg);
942 return;
944 retry:
945 event_add(&bufev->ev_write, NULL);
946 return;
947 err:
948 log_warnx("tls error: %s", tls_error(client->ctx));
949 (*bufev->errorcb)(bufev, what, bufev->cbarg);
952 static void
953 client_read(struct bufferevent *bev, void *d)
955 struct stat sb;
956 struct client *c = d;
957 struct evbuffer *src = EVBUFFER_INPUT(bev);
958 const char *path, *p, *parse_err = "invalid request";
959 char decoded[DOMAIN_NAME_LEN];
960 char *nul;
961 size_t len;
963 bufferevent_disable(bev, EVBUFFER_READ);
965 /*
966 * libevent2 can still somehow call this function, even
967 * though I never enable EV_READ in the bufferevent. If
968 * that's the case, bail out.
969 */
970 if (c->type != REQUEST_UNDECIDED)
971 return;
973 /* max url len + \r\n */
974 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
975 log_debug("too much data received");
976 start_reply(c, BAD_REQUEST, "bad request");
977 return;
980 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
981 if (c->req == NULL) {
982 /* not enough data yet. */
983 bufferevent_enable(bev, EVBUFFER_READ);
984 return;
986 if (c->reqlen > 1024+2) {
987 log_debug("URL too long");
988 start_reply(c, BAD_REQUEST, "bad request");
989 return;
992 nul = strchr(c->req, '\0');
993 len = nul - c->req;
994 if (len != c->reqlen) {
995 log_debug("NUL inside the request IRI");
996 start_reply(c, BAD_REQUEST, "bad request");
997 return;
1000 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1001 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1002 log_debug("IRI parse error: %s", parse_err);
1003 start_reply(c, BAD_REQUEST, "bad request");
1004 return;
1007 if (apply_reverse_proxy(c))
1008 return;
1010 /* ignore the port number */
1011 if (strcmp(c->iri.schema, "gemini") ||
1012 strcmp(decoded, c->domain)) {
1013 start_reply(c, PROXY_REFUSED, "won't proxy request");
1014 return;
1017 if (apply_require_ca(c) ||
1018 apply_block_return(c)||
1019 apply_fastcgi(c))
1020 return;
1022 path = c->iri.path;
1023 p = strip_path(path, vhost_strip(c->host, path));
1024 while (*p == '/')
1025 p++;
1026 if (*p == '\0')
1027 p = ".";
1029 c->pfd = openat(vhost_dirfd(c->host, path, &c->loc), p, O_RDONLY);
1030 if (c->pfd == -1) {
1031 if (errno == EACCES)
1032 log_info("can't open %s: %s", p, strerror(errno));
1033 start_reply(c, NOT_FOUND, "not found");
1034 return;
1037 if (fstat(c->pfd, &sb) == -1) {
1038 log_warnx("fstat %s", path);
1039 start_reply(c, TEMP_FAILURE, "internal server error");
1040 return;
1043 if (S_ISDIR(sb.st_mode)) {
1044 open_dir(c);
1045 return;
1048 c->type = REQUEST_FILE;
1049 start_reply(c, SUCCESS, mime(c->conf, c->host, p));
1052 void
1053 client_write(struct bufferevent *bev, void *d)
1055 struct client *c = d;
1056 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1057 char nam[PATH_MAX];
1058 char buf[BUFSIZ];
1059 ssize_t r;
1061 switch (c->type) {
1062 case REQUEST_UNDECIDED:
1064 * Ignore spurious calls when we still don't have idea
1065 * what to do with the request.
1067 break;
1069 case REQUEST_FILE:
1070 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1071 log_warn("read");
1072 client_error(bev, EVBUFFER_ERROR, c);
1073 return;
1074 } else if (r == 0) {
1075 client_close(c);
1076 return;
1077 } else if (r != sizeof(buf))
1078 c->type = REQUEST_DONE;
1079 bufferevent_write(bev, buf, r);
1080 break;
1082 case REQUEST_DIR:
1083 /* TODO: handle big big directories better */
1084 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1085 const char *sufx = "";
1087 encode_path(nam, sizeof(nam),
1088 c->dir[c->diroff]->d_name);
1089 if (c->dir[c->diroff]->d_type == DT_DIR)
1090 sufx = "/";
1091 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1092 free(c->dir[c->diroff]);
1094 free(c->dir);
1095 c->dir = NULL;
1097 c->type = REQUEST_DONE;
1099 event_add(&c->bev->ev_write, NULL);
1100 break;
1102 case REQUEST_FCGI:
1103 case REQUEST_PROXY:
1105 * Here we depend on fastcgi or proxy connection to
1106 * provide data.
1108 break;
1110 case REQUEST_DONE:
1111 if (EVBUFFER_LENGTH(out) == 0)
1112 client_close(c);
1113 break;
1117 static void
1118 client_error(struct bufferevent *bev, short error, void *d)
1120 struct client *c = d;
1122 c->type = REQUEST_DONE;
1124 if (error & EVBUFFER_TIMEOUT) {
1125 log_debug("timeout; forcefully closing the connection");
1126 if (c->code == 0)
1127 start_reply(c, BAD_REQUEST, "timeout");
1128 else
1129 client_close(c);
1130 return;
1133 if (error & EVBUFFER_EOF) {
1134 client_close(c);
1135 return;
1138 log_warnx("unknown bufferevent error 0x%x", error);
1139 client_close(c);
1142 int
1143 start_reply(struct client *c, int code, const char *meta)
1145 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1146 const char *lang;
1147 int r, rr;
1149 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1151 c->code = code;
1152 c->meta = meta;
1154 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1155 if (r == -1)
1156 goto err;
1158 /* 2 digit status + space + 1024 max reply */
1159 if (r > 1027)
1160 goto overflow;
1162 if (c->type != REQUEST_FCGI &&
1163 c->type != REQUEST_PROXY &&
1164 !strcmp(meta, "text/gemini") &&
1165 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1166 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1167 if (rr == -1)
1168 goto err;
1169 if (r + rr > 1027)
1170 goto overflow;
1173 bufferevent_write(c->bev, "\r\n", 2);
1175 if (!vhost_disable_log(c->host, c->iri.path))
1176 log_request(c, code, meta);
1178 if (code != 20)
1179 c->type = REQUEST_DONE;
1181 return 0;
1183 err:
1184 log_warnx("evbuffer_add_printf error: no memory");
1185 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1186 c->type = REQUEST_DONE;
1187 return -1;
1189 overflow:
1190 log_warnx("reply header overflow");
1191 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1192 start_reply(c, TEMP_FAILURE, "internal error");
1193 return -1;
1196 static void
1197 client_close_ev(int fd, short event, void *d)
1199 struct client *c = d;
1201 switch (tls_close(c->ctx)) {
1202 case TLS_WANT_POLLIN:
1203 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1204 return;
1205 case TLS_WANT_POLLOUT:
1206 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1207 return;
1210 connected_clients--;
1212 free(c->req);
1214 tls_free(c->ctx);
1215 c->ctx = NULL;
1217 free(c->header);
1219 if (c->pfd != -1)
1220 close(c->pfd);
1222 if (c->dir != NULL)
1223 free(c->dir);
1225 close(c->fd);
1226 c->fd = -1;
1228 free(c);
1231 static void
1232 client_proxy_close(int fd, short event, void *d)
1234 struct tls *ctx = d;
1236 if (ctx == NULL) {
1237 close(fd);
1238 return;
1241 switch (tls_close(ctx)) {
1242 case TLS_WANT_POLLIN:
1243 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1244 break;
1245 case TLS_WANT_POLLOUT:
1246 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1247 break;
1250 tls_free(ctx);
1251 close(fd);
1254 void
1255 client_close(struct client *c)
1258 * We may end up calling client_close in various situations
1259 * and for the most unexpected reasons. Therefore, we need to
1260 * ensure that everything gets properly released once we reach
1261 * this point.
1264 SPLAY_REMOVE(client_tree_id, &clients, c);
1266 if (c->cgibev != NULL) {
1267 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1268 bufferevent_free(c->cgibev);
1269 c->cgibev = NULL;
1270 close(c->pfd);
1271 c->pfd = -1;
1274 if (c->bev != NULL) {
1275 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1276 bufferevent_free(c->bev);
1279 if (c->proxyevset &&
1280 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1281 c->proxyevset = 0;
1282 event_del(&c->proxyev);
1285 if (c->pfd != -1 && c->proxyctx != NULL) {
1286 /* shut down the proxy TLS connection */
1287 client_proxy_close(c->pfd, 0, c->proxyctx);
1288 c->pfd = -1;
1291 if (c->proxybev != NULL)
1292 bufferevent_free(c->proxybev);
1294 client_close_ev(c->fd, 0, c);
1297 static ssize_t
1298 read_cb(struct tls *ctx, void *buf, size_t buflen, void *cb_arg)
1300 struct client *c = cb_arg;
1301 struct proxy_protocol_v1 pp1 = {0};
1302 char protostr[1024];
1303 ssize_t ret;
1304 size_t left, avail, copy, consumed;
1305 int status;
1307 if (!c->proxy_proto) {
1308 /* no buffer to cache into, read into libtls buffer */
1309 ret = read(c->fd, buf, buflen);
1310 if (ret == -1 && errno == EWOULDBLOCK)
1311 ret = TLS_WANT_POLLIN;
1313 return ret;
1316 if (c->buf.has_tail) {
1317 /* we have leftover data from a previous call to read_cb */
1318 left = c->buf.len - c->buf.read_pos;
1319 copy = MINIMUM(buflen, left);
1320 memcpy(buf, c->buf.data + c->buf.read_pos, copy);
1321 c->buf.read_pos += copy;
1322 if (left == copy) {
1323 c->proxy_proto = 0;
1324 c->buf.has_tail = 0;
1326 return copy;
1329 avail = sizeof(c->buf.data) - c->buf.len - 1; /* for a NUL */
1330 if (avail == 0) {
1331 log_warnx("read_cb: overlong proxy protocol v1 header");
1332 return -1;
1335 ret = read(c->fd, c->buf.data + c->buf.len, avail);
1336 if (ret == -1 && errno == EWOULDBLOCK)
1337 return TLS_WANT_POLLIN;
1338 if (ret <= 0)
1339 return ret;
1340 c->buf.len += ret;
1342 if (memmem(c->buf.data, c->buf.len, "\r\n", 2) == NULL)
1343 return TLS_WANT_POLLIN;
1345 status = proxy_proto_v1_parse(&pp1, c->buf.data, c->buf.len, &consumed);
1346 if (status == -1) {
1347 log_warnx("read_cb: received invalid proxy protocol header");
1348 return -1;
1351 switch (pp1.proto) {
1352 case PROTO_V4:
1353 inet_ntop(AF_INET, &pp1.srcaddr.v4, c->rhost,
1354 sizeof(c->rhost));
1355 break;
1356 case PROTO_V6:
1357 inet_ntop(AF_INET6, &pp1.srcaddr.v6, c->rhost,
1358 sizeof(c->rhost));
1359 break;
1360 case PROTO_UNKNOWN:
1361 strlcpy(c->rhost, "UNKNOWN", sizeof(c->rhost));
1362 break;
1365 if (pp1.proto != PROTO_UNKNOWN)
1366 snprintf(c->rserv, sizeof(c->rserv), "%u", pp1.srcport);
1368 proxy_proto_v1_string(&pp1, protostr, sizeof(protostr));
1369 log_debug("proxy-protocol v1: %s", protostr);
1371 if (consumed < c->buf.len) {
1372 /* we have some leftover */
1373 c->buf.read_pos = consumed;
1374 c->buf.has_tail = 1;
1375 } else {
1376 /* we consumed the whole buffer */
1377 c->proxy_proto = c->buf.read_pos = 0;
1378 c->buf.has_tail = 0;
1381 return TLS_WANT_POLLIN;
1384 static ssize_t
1385 write_cb(struct tls *ctx, const void *buf, size_t buflen, void *cb_arg)
1387 struct client *c = cb_arg;
1389 ssize_t ret = write(c->fd, buf, buflen);
1390 if (ret == -1 && errno == EAGAIN)
1391 return TLS_WANT_POLLOUT;
1393 return ret;
1396 void
1397 server_accept(int sock, short et, void *d)
1399 struct address *addr = d;
1400 struct client *c;
1401 struct sockaddr_storage raddr;
1402 struct sockaddr *sraddr;
1403 socklen_t len;
1404 int e, fd;
1406 sraddr = (struct sockaddr *)&raddr;
1407 len = sizeof(raddr);
1408 if ((fd = accept(sock, sraddr, &len)) == -1) {
1409 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1410 errno == ECONNABORTED)
1411 return;
1412 log_warnx("accept failed");
1413 return;
1416 mark_nonblock(fd);
1418 c = xcalloc(1, sizeof(*c));
1419 c->conf = addr->conf;
1420 c->addr = addr;
1421 c->id = ++server_client_id;
1422 c->fd = fd;
1423 c->pfd = -1;
1424 memcpy(&c->raddr, &raddr, sizeof(raddr));
1425 c->raddrlen = len;
1426 c->proxy_proto = addr->proxy;
1428 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1429 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1430 if (e != 0) {
1431 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1432 close(c->fd);
1433 free(c);
1434 return;
1437 if (tls_accept_cbs(addr->ctx, &c->ctx, read_cb, write_cb, c) == -1) {
1438 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1439 close(c->fd);
1440 free(c);
1441 return;
1444 SPLAY_INSERT(client_tree_id, &clients, c);
1445 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1446 connected_clients++;
1449 static void
1450 handle_siginfo(int fd, short ev, void *d)
1452 log_info("%d connected clients", connected_clients);
1455 static void
1456 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1457 struct conf *conf)
1459 struct address *vaddr;
1460 struct vhost *h;
1461 int r, any = 0;
1463 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1464 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1465 if (!match_addr(addr, vaddr))
1466 continue;
1468 if (!any) {
1469 any = 1;
1470 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1471 h->cert, h->certlen, h->key, h->keylen,
1472 h->ocsp, h->ocsplen);
1473 } else {
1474 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1475 h->cert, h->certlen, h->key, h->keylen,
1476 h->ocsp, h->ocsplen);
1479 if (r == -1)
1480 fatalx("failed to load keypair"
1481 " for host %s: %s", h->domain,
1482 tls_config_error(tlsconf));
1487 static void
1488 setup_tls(struct conf *conf)
1490 struct tls_config *tlsconf;
1491 struct address *addr;
1493 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1494 if ((tlsconf = tls_config_new()) == NULL)
1495 fatal("tls_config_new");
1497 if (conf->use_privsep_crypto)
1498 tls_config_use_fake_private_key(tlsconf);
1500 /* optionally accept client certs but don't verify */
1501 tls_config_verify_client_optional(tlsconf);
1502 tls_config_insecure_noverifycert(tlsconf);
1504 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1505 fatalx("tls_config_set_protocols: %s",
1506 tls_config_error(tlsconf));
1508 add_matching_kps(tlsconf, addr, conf);
1510 tls_reset(addr->ctx);
1511 if (tls_configure(addr->ctx, tlsconf) == -1)
1512 fatalx("tls_configure: %s", tls_error(addr->ctx));
1514 tls_config_free(tlsconf);
1518 static void
1519 load_vhosts(struct conf *conf)
1521 struct vhost *h;
1522 struct location *l;
1523 char path[PATH_MAX], *p;
1524 int r;
1526 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1527 TAILQ_FOREACH(l, &h->locations, locations) {
1528 if (*l->dir == '\0')
1529 continue;
1531 p = l->dir;
1533 if (conf->conftest && *conf->chroot != '\0') {
1534 r = snprintf(path, sizeof(path), "%s/%s",
1535 conf->chroot, l->dir);
1536 if (r < 0 || (size_t)r >= sizeof(path))
1537 fatalx("path too long: %s", l->dir);
1538 p = path;
1541 l->dirfd = open(p, O_RDONLY | O_DIRECTORY);
1542 if (l->dirfd == -1)
1543 fatal("open %s for domain %s", l->dir,
1544 h->domain);
1549 void
1550 server(struct privsep *ps, struct privsep_proc *p)
1552 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1555 void
1556 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1558 struct conf *c;
1560 SPLAY_INIT(&clients);
1562 #ifdef SIGINFO
1563 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1564 signal_add(&siginfo, NULL);
1565 #endif
1566 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1567 signal_add(&sigusr2, NULL);
1569 sandbox_server_process();
1572 * gemexp doesn't use the privsep crypto engine; it doesn't
1573 * use privsep at all so `ps' is NULL.
1575 if (ps != NULL) {
1576 c = ps->ps_env;
1577 if (c->use_privsep_crypto)
1578 crypto_engine_init(ps->ps_env);
1582 int
1583 server_configure_done(struct conf *conf)
1585 struct address *addr;
1587 if (load_default_mime(&conf->mime) == -1)
1588 fatal("can't load default mime");
1589 sort_mime(&conf->mime);
1590 setup_tls(conf);
1591 load_vhosts(conf);
1593 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1594 if (addr->sock != -1)
1595 event_add(&addr->evsock, NULL);
1598 return 0;
1601 static int
1602 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1604 struct privsep *ps = p->p_ps;
1605 struct conf *conf = ps->ps_env;
1607 switch (imsg_get_type(imsg)) {
1608 case IMSG_RECONF_START:
1609 case IMSG_RECONF_LOG_FMT:
1610 case IMSG_RECONF_MIME:
1611 case IMSG_RECONF_PROTOS:
1612 case IMSG_RECONF_SOCK:
1613 case IMSG_RECONF_FCGI:
1614 case IMSG_RECONF_HOST:
1615 case IMSG_RECONF_CERT:
1616 case IMSG_RECONF_KEY:
1617 case IMSG_RECONF_OCSP:
1618 case IMSG_RECONF_HOST_ADDR:
1619 case IMSG_RECONF_LOC:
1620 case IMSG_RECONF_ENV:
1621 case IMSG_RECONF_ALIAS:
1622 case IMSG_RECONF_PROXY:
1623 case IMSG_RECONF_PROXY_CERT:
1624 case IMSG_RECONF_PROXY_KEY:
1625 return config_recv(conf, imsg);
1626 case IMSG_RECONF_END:
1627 if (config_recv(conf, imsg) == -1)
1628 return -1;
1629 if (server_configure_done(conf) == -1)
1630 return -1;
1631 break;
1632 default:
1633 return -1;
1636 return 0;
1639 static int
1640 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1642 return -1;
1645 static int
1646 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1648 return -1;
1651 int
1652 client_tree_cmp(struct client *a, struct client *b)
1654 if (a->id == b->id)
1655 return 0;
1656 else if (a->id < b->id)
1657 return -1;
1658 else
1659 return +1;
1662 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)