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 <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 #ifdef SIGINFO
41 static struct event siginfo;
42 #endif
43 static struct event sigusr2;
45 int connected_clients;
47 /*
48 * This function is not publicy exported because it is a hack until libtls
49 * has a proper privsep setup.
50 */
51 void tls_config_use_fake_private_key(struct tls_config *);
53 static inline int matches(const char*, const char*);
55 static void handle_handshake(int, short, void*);
56 static void fmtbuf(char *, size_t, const char *, struct client *,
57 const char *);
58 static int apply_block_return(struct client*);
59 static int check_matching_certificate(X509_STORE *, struct client *);
60 static int apply_reverse_proxy(struct client *);
61 static int apply_fastcgi(struct client*);
62 static int apply_require_ca(struct client*);
63 static void open_dir(struct client*);
64 static void redirect_canonical_dir(struct client*);
66 static void client_tls_readcb(int, short, void *);
67 static void client_tls_writecb(int, short, void *);
69 static void client_read(struct bufferevent *, void *);
70 void client_write(struct bufferevent *, void *);
71 static void client_error(struct bufferevent *, short, void *);
73 static void client_close_ev(int, short, void *);
75 static void handle_siginfo(int, short, void*);
77 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
78 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
79 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
81 static struct privsep_proc procs[] = {
82 { "parent", PROC_PARENT, server_dispatch_parent },
83 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
84 { "logger", PROC_LOGGER, server_dispatch_logger },
85 };
87 static uint32_t server_client_id;
89 struct client_tree_id clients;
91 static inline int
92 match_addr(struct address *target, struct address *source)
93 {
94 return (target->ai_flags == source->ai_flags &&
95 target->ai_family == source->ai_family &&
96 target->ai_socktype == source->ai_socktype &&
97 target->ai_protocol == source->ai_protocol &&
98 target->slen == source->slen &&
99 !memcmp(&target->ss, &source->ss, target->slen));
102 static inline int
103 matches(const char *pattern, const char *path)
105 if (*path == '/')
106 path++;
107 return !fnmatch(pattern, path, 0);
110 static inline int
111 match_host(struct vhost *v, struct client *c)
113 struct alist *a;
114 struct address *addr;
116 TAILQ_FOREACH(addr, &v->addrs, addrs)
117 if (match_addr(addr, c->addr))
118 break;
119 if (addr == NULL)
120 return 0;
122 if (matches(v->domain, c->domain))
123 return 1;
125 TAILQ_FOREACH(a, &v->aliases, aliases)
126 if (matches(a->alias, c->domain))
127 return 1;
129 return 0;
132 const char *
133 vhost_lang(struct vhost *v, const char *path)
135 struct location *loc;
137 if (v == NULL || path == NULL)
138 return NULL;
140 loc = TAILQ_FIRST(&v->locations);
141 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
142 if (*loc->lang != '\0') {
143 if (matches(loc->match, path))
144 return loc->lang;
148 loc = TAILQ_FIRST(&v->locations);
149 if (*loc->lang == '\0')
150 return NULL;
151 return loc->lang;
154 const char *
155 vhost_default_mime(struct vhost *v, const char *path)
157 struct location *loc;
158 const char *default_mime = "application/octet-stream";
160 if (v == NULL || path == NULL)
161 return default_mime;
163 loc = TAILQ_FIRST(&v->locations);
164 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
165 if (*loc->default_mime != '\0') {
166 if (matches(loc->match, path))
167 return loc->default_mime;
171 loc = TAILQ_FIRST(&v->locations);
172 if (*loc->default_mime != '\0')
173 return loc->default_mime;
174 return default_mime;
177 const char *
178 vhost_index(struct vhost *v, const char *path)
180 struct location *loc;
181 const char *index = "index.gmi";
183 if (v == NULL || path == NULL)
184 return index;
186 loc = TAILQ_FIRST(&v->locations);
187 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
188 if (*loc->index != '\0') {
189 if (matches(loc->match, path))
190 return loc->index;
194 loc = TAILQ_FIRST(&v->locations);
195 if (*loc->index != '\0')
196 return loc->index;
197 return index;
200 int
201 vhost_auto_index(struct vhost *v, const char *path)
203 struct location *loc;
205 if (v == NULL || path == NULL)
206 return 0;
208 loc = TAILQ_FIRST(&v->locations);
209 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
210 if (loc->auto_index != 0) {
211 if (matches(loc->match, path))
212 return loc->auto_index == 1;
216 loc = TAILQ_FIRST(&v->locations);
217 return loc->auto_index == 1;
220 int
221 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
223 struct location *loc;
225 if (v == NULL || path == NULL)
226 return 0;
228 loc = TAILQ_FIRST(&v->locations);
229 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
230 if (loc->block_code != 0) {
231 if (matches(loc->match, path)) {
232 *code = loc->block_code;
233 *fmt = loc->block_fmt;
234 return 1;
239 loc = TAILQ_FIRST(&v->locations);
240 *code = loc->block_code;
241 *fmt = loc->block_fmt;
242 return loc->block_code != 0;
245 struct location *
246 vhost_fastcgi(struct vhost *v, const char *path)
248 struct location *loc;
249 int force_disable = 0;
251 if (v == NULL || path == NULL)
252 return NULL;
254 loc = TAILQ_FIRST(&v->locations);
255 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
256 if (loc->fcgi != -1)
257 if (matches(loc->match, path))
258 return loc;
259 if (loc->nofcgi && matches(loc->match, path))
260 force_disable = 1;
263 if (force_disable)
264 return NULL;
266 loc = TAILQ_FIRST(&v->locations);
267 return loc->fcgi == -1 ? NULL : loc;
270 int
271 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
273 struct location *loc;
274 size_t l = 0;
276 if (v == NULL || path == NULL)
277 return -1;
279 loc = TAILQ_FIRST(&v->locations);
280 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
281 l++;
282 if (loc->dirfd != -1)
283 if (matches(loc->match, path)) {
284 *retloc = l;
285 return loc->dirfd;
289 *retloc = 0;
290 loc = TAILQ_FIRST(&v->locations);
291 return loc->dirfd;
294 int
295 vhost_strip(struct vhost *v, const char *path)
297 struct location *loc;
299 if (v == NULL || path == NULL)
300 return 0;
302 loc = TAILQ_FIRST(&v->locations);
303 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
304 if (loc->strip != 0) {
305 if (matches(loc->match, path))
306 return loc->strip;
310 loc = TAILQ_FIRST(&v->locations);
311 return loc->strip;
314 X509_STORE *
315 vhost_require_ca(struct vhost *v, const char *path)
317 struct location *loc;
319 if (v == NULL || path == NULL)
320 return NULL;
322 loc = TAILQ_FIRST(&v->locations);
323 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
324 if (loc->reqca != NULL) {
325 if (matches(loc->match, path))
326 return loc->reqca;
330 loc = TAILQ_FIRST(&v->locations);
331 return loc->reqca;
334 int
335 vhost_disable_log(struct vhost *v, const char *path)
337 struct location *loc;
339 if (v == NULL || path == NULL)
340 return 0;
342 loc = TAILQ_FIRST(&v->locations);
343 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
344 if (loc->disable_log && matches(loc->match, path))
345 return 1;
348 loc = TAILQ_FIRST(&v->locations);
349 return loc->disable_log;
352 void
353 mark_nonblock(int fd)
355 int flags;
357 if ((flags = fcntl(fd, F_GETFL)) == -1)
358 fatal("fcntl(F_GETFL)");
359 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
360 fatal("fcntl(F_SETFL)");
363 static void
364 handle_handshake(int fd, short ev, void *d)
366 struct client *c = d;
367 struct conf *conf = c->conf;
368 struct vhost *h;
369 const char *servname;
370 const char *parse_err = "unknown error";
372 switch (tls_handshake(c->ctx)) {
373 case 0: /* success */
374 break;
375 case -1:
376 log_warnx("(%s:%s) tls_handshake failed: %s",
377 c->rhost, c->rserv, tls_error(c->ctx));
378 client_close(c);
379 return;
380 case TLS_WANT_POLLIN:
381 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
382 return;
383 case TLS_WANT_POLLOUT:
384 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
385 return;
386 default:
387 /* unreachable */
388 abort();
391 c->bev = bufferevent_new(fd, client_read, client_write,
392 client_error, c);
393 if (c->bev == NULL)
394 fatal("%s: failed to allocate client buffer", __func__);
396 event_set(&c->bev->ev_read, c->fd, EV_READ,
397 client_tls_readcb, c->bev);
398 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
399 client_tls_writecb, c->bev);
401 #if HAVE_LIBEVENT2
402 evbuffer_unfreeze(c->bev->input, 0);
403 evbuffer_unfreeze(c->bev->output, 1);
404 #endif
406 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
407 log_debug("handshake: missing SNI");
408 goto err;
411 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
412 log_info("puny_decode: %s", parse_err);
413 goto err;
416 TAILQ_FOREACH(h, &conf->hosts, vhosts)
417 if (match_host(h, c))
418 break;
420 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
421 servname != NULL ? servname : "(null)",
422 c->domain,
423 h != NULL ? h->domain : "(null)");
425 if (h != NULL) {
426 c->host = h;
427 bufferevent_enable(c->bev, EV_READ);
428 return;
431 err:
432 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
435 static void
436 fmtbuf(char *buf, size_t buflen, const char *fmt, struct client *c,
437 const char *path)
439 size_t i;
440 char tmp[32];
442 *buf = '\0';
443 memset(tmp, 0, sizeof(tmp));
444 for (i = 0; *fmt; ++fmt) {
445 if (i == sizeof(tmp)-1 || *fmt == '%') {
446 strlcat(buf, tmp, buflen);
447 memset(tmp, 0, sizeof(tmp));
448 i = 0;
451 if (*fmt != '%') {
452 tmp[i++] = *fmt;
453 continue;
456 switch (*++fmt) {
457 case '%':
458 strlcat(buf, "%", buflen);
459 break;
460 case 'p':
461 if (*path != '/')
462 strlcat(buf, "/", buflen);
463 strlcat(buf, path, buflen);
464 break;
465 case 'q':
466 strlcat(buf, c->iri.query, buflen);
467 break;
468 case 'P':
469 snprintf(tmp, sizeof(tmp), "%d", c->addr->port);
470 strlcat(buf, tmp, buflen);
471 memset(tmp, 0, sizeof(tmp));
472 break;
473 case 'N':
474 strlcat(buf, c->domain, buflen);
475 break;
476 default:
477 log_warnx("%s: unknown fmt specifier %c",
478 __func__, *fmt);
482 if (i != 0)
483 strlcat(buf, tmp, buflen);
486 /* 1 if a matching `block return' (and apply it), 0 otherwise */
487 static int
488 apply_block_return(struct client *c)
490 char buf[GEMINI_URL_LEN];
491 const char *fmt, *path;
492 int code;
494 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
495 return 0;
497 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
498 fmtbuf(buf, sizeof(buf), fmt, c, path);
500 start_reply(c, code, buf);
501 return 1;
504 static struct proxy *
505 matched_proxy(struct client *c)
507 struct proxy *p;
508 const char *proto;
509 const char *host;
510 const char *port;
512 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
513 if (*(proto = p->match_proto) == '\0')
514 proto = "gemini";
515 if (*(host = p->match_host) == '\0')
516 host = "*";
517 if (*(port = p->match_port) == '\0')
518 port = "*";
520 if (matches(proto, c->iri.schema) &&
521 matches(host, c->domain) &&
522 matches(port, c->iri.port))
523 return p;
526 return NULL;
529 static int
530 check_matching_certificate(X509_STORE *store, struct client *c)
532 const uint8_t *cert;
533 size_t len;
535 if (!tls_peer_cert_provided(c->ctx)) {
536 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
537 return 1;
540 cert = tls_peer_cert_chain_pem(c->ctx, &len);
541 if (!validate_against_ca(store, cert, len)) {
542 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
543 return 1;
546 return 0;
549 static int
550 proxy_socket(struct client *c, const char *host, const char *port)
552 struct addrinfo hints, *res, *res0;
553 int r, sock, save_errno;
554 const char *cause = NULL;
556 memset(&hints, 0, sizeof(hints));
557 hints.ai_family = AF_UNSPEC;
558 hints.ai_socktype = SOCK_STREAM;
560 /* XXX: asr_run? :> */
561 r = getaddrinfo(host, port, &hints, &res0);
562 if (r != 0) {
563 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
564 host, port, gai_strerror(r));
565 return -1;
568 for (res = res0; res; res = res->ai_next) {
569 sock = socket(res->ai_family, res->ai_socktype,
570 res->ai_protocol);
571 if (sock == -1) {
572 cause = "socket";
573 continue;
576 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
577 cause = "connect";
578 save_errno = errno;
579 close(sock);
580 errno = save_errno;
581 sock = -1;
582 continue;
585 break;
588 if (sock == -1)
589 log_warn("can't connect to %s:%s: %s", host, port, cause);
591 freeaddrinfo(res0);
593 return sock;
596 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
597 static int
598 apply_reverse_proxy(struct client *c)
600 struct proxy *p;
602 if ((p = matched_proxy(c)) == NULL)
603 return 0;
605 c->proxy = p;
607 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
608 return 1;
610 log_debug("opening proxy connection for %s:%s",
611 p->host, p->port);
613 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
614 start_reply(c, PROXY_ERROR, "proxy error");
615 return 1;
618 mark_nonblock(c->pfd);
619 if (proxy_init(c) == -1)
620 start_reply(c, PROXY_ERROR, "proxy error");
622 return 1;
625 static int
626 fcgi_open_sock(struct fcgi *f)
628 struct sockaddr_un addr;
629 int fd;
631 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
632 log_warn("socket");
633 return -1;
636 memset(&addr, 0, sizeof(addr));
637 addr.sun_family = AF_UNIX;
638 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
640 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
641 log_warn("failed to connect to %s", f->path);
642 close(fd);
643 return -1;
646 return fd;
649 static int
650 fcgi_open_conn(struct fcgi *f)
652 struct addrinfo hints, *servinfo, *p;
653 int r, sock, save_errno;
654 const char *cause = NULL;
656 memset(&hints, 0, sizeof(hints));
657 hints.ai_family = AF_UNSPEC;
658 hints.ai_socktype = SOCK_STREAM;
659 hints.ai_flags = AI_ADDRCONFIG;
661 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
662 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
663 gai_strerror(r));
664 return -1;
667 for (p = servinfo; p != NULL; p = p->ai_next) {
668 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
669 if (sock == -1) {
670 cause = "socket";
671 continue;
673 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
674 cause = "connect";
675 save_errno = errno;
676 close(sock);
677 errno = save_errno;
678 continue;
680 break;
683 if (p == NULL) {
684 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
685 cause);
686 sock = -1;
689 freeaddrinfo(servinfo);
690 return sock;
693 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
694 static int
695 apply_fastcgi(struct client *c)
697 int i = 0;
698 struct fcgi *f;
699 struct location *loc;
701 if ((loc = vhost_fastcgi(c->host, c->iri.path)) == NULL)
702 return 0;
704 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
705 if (i == loc->fcgi)
706 break;
707 ++i;
710 if (f == NULL) {
711 log_warnx("can't find fcgi #%d", loc->fcgi);
712 return 0;
715 log_debug("opening fastcgi connection for (%s,%s)",
716 f->path, f->port);
718 if (*f->port == '\0')
719 c->pfd = fcgi_open_sock(f);
720 else
721 c->pfd = fcgi_open_conn(f);
723 if (c->pfd == -1) {
724 start_reply(c, CGI_ERROR, "CGI error");
725 return 1;
728 mark_nonblock(c->pfd);
730 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
731 fcgi_error, c);
732 if (c->cgibev == NULL) {
733 start_reply(c, TEMP_FAILURE, "internal server error");
734 return 1;
737 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
738 fcgi_req(c, loc);
740 return 1;
743 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
744 static int
745 apply_require_ca(struct client *c)
747 X509_STORE *store;
749 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
750 return 0;
751 return check_matching_certificate(store, c);
754 static void
755 server_dir_listing(struct client *c)
757 int root;
759 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
761 if (!vhost_auto_index(c->host, c->iri.path)) {
762 start_reply(c, NOT_FOUND, "not found");
763 return;
766 c->dirlen = scandir_fd(c->pfd, &c->dir,
767 root ? select_non_dotdot : select_non_dot,
768 alphasort);
769 if (c->dirlen == -1) {
770 log_warn("scandir_fd(%d) (vhost:%s) %s",
771 c->pfd, c->host->domain, c->iri.path);
772 start_reply(c, TEMP_FAILURE, "internal server error");
773 return;
776 c->type = REQUEST_DIR;
777 start_reply(c, SUCCESS, "text/gemini");
778 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
779 "# Index of /%s\n\n", c->iri.path);
782 static void
783 open_dir(struct client *c)
785 struct stat sb;
786 const char *index;
787 char path[PATH_MAX];
788 int fd = -1;
790 if (*c->iri.path != '\0' && !ends_with(c->iri.path, "/")) {
791 redirect_canonical_dir(c);
792 return;
795 index = vhost_index(c->host, c->iri.path);
796 fd = openat(c->pfd, index, O_RDONLY);
797 if (fd == -1) {
798 server_dir_listing(c);
799 return;
802 if (fstat(fd, &sb) == -1) {
803 log_warn("fstat");
804 close(fd);
805 start_reply(c, TEMP_FAILURE, "internal server error");
806 return;
809 if (!S_ISREG(sb.st_mode)) {
810 close(fd);
811 server_dir_listing(c);
812 return;
815 strlcpy(path, c->iri.path, sizeof(path));
816 strlcat(path, index, sizeof(path));
818 close(c->pfd);
819 c->pfd = fd;
820 c->type = REQUEST_FILE;
821 start_reply(c, SUCCESS, mime(c->conf, c->host, path));
824 static void
825 redirect_canonical_dir(struct client *c)
827 char buf[GEMINI_URL_LEN];
828 int r;
830 r = snprintf(buf, sizeof(buf), "/%s/", c->iri.path);
831 if (r < 0 || (size_t)r >= sizeof(buf)) {
832 start_reply(c, TEMP_FAILURE, "internal server error");
833 return;
836 start_reply(c, TEMP_REDIRECT, buf);
839 static void
840 client_tls_readcb(int fd, short event, void *d)
842 struct bufferevent *bufev = d;
843 struct client *client = bufev->cbarg;
844 ssize_t ret;
845 size_t len;
846 int what = EVBUFFER_READ;
847 int howmuch = IBUF_READ_SIZE;
848 char buf[IBUF_READ_SIZE];
850 if (event == EV_TIMEOUT) {
851 what |= EVBUFFER_TIMEOUT;
852 goto err;
855 if (bufev->wm_read.high != 0)
856 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
858 switch (ret = tls_read(client->ctx, buf, howmuch)) {
859 case TLS_WANT_POLLIN:
860 case TLS_WANT_POLLOUT:
861 goto retry;
862 case -1:
863 what |= EVBUFFER_ERROR;
864 goto err;
866 len = ret;
868 if (len == 0) {
869 what |= EVBUFFER_EOF;
870 goto err;
873 if (evbuffer_add(bufev->input, buf, len) == -1) {
874 what |= EVBUFFER_ERROR;
875 goto err;
878 event_add(&bufev->ev_read, NULL);
879 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
880 return;
881 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
882 /*
883 * here we could implement a read pressure policy.
884 */
887 if (bufev->readcb != NULL)
888 (*bufev->readcb)(bufev, bufev->cbarg);
890 return;
892 retry:
893 event_add(&bufev->ev_read, NULL);
894 return;
896 err:
897 (*bufev->errorcb)(bufev, what, bufev->cbarg);
900 static void
901 client_tls_writecb(int fd, short event, void *d)
903 struct bufferevent *bufev = d;
904 struct client *client = bufev->cbarg;
905 ssize_t ret;
906 size_t len;
907 short what = EVBUFFER_WRITE;
909 if (event == EV_TIMEOUT) {
910 what |= EVBUFFER_TIMEOUT;
911 goto err;
914 if (EVBUFFER_LENGTH(bufev->output) != 0) {
915 ret = tls_write(client->ctx,
916 EVBUFFER_DATA(bufev->output),
917 EVBUFFER_LENGTH(bufev->output));
918 switch (ret) {
919 case TLS_WANT_POLLIN:
920 case TLS_WANT_POLLOUT:
921 goto retry;
922 case -1:
923 what |= EVBUFFER_ERROR;
924 goto err;
926 len = ret;
927 evbuffer_drain(bufev->output, len);
930 if (EVBUFFER_LENGTH(bufev->output) != 0)
931 event_add(&bufev->ev_write, NULL);
933 if (bufev->writecb != NULL &&
934 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
935 (*bufev->writecb)(bufev, bufev->cbarg);
936 return;
938 retry:
939 event_add(&bufev->ev_write, NULL);
940 return;
941 err:
942 log_warnx("tls error: %s", tls_error(client->ctx));
943 (*bufev->errorcb)(bufev, what, bufev->cbarg);
946 static void
947 client_read(struct bufferevent *bev, void *d)
949 struct stat sb;
950 struct client *c = d;
951 struct evbuffer *src = EVBUFFER_INPUT(bev);
952 const char *path, *p, *parse_err = "invalid request";
953 char decoded[DOMAIN_NAME_LEN];
955 bufferevent_disable(bev, EVBUFFER_READ);
957 /*
958 * libevent2 can still somehow call this function, even
959 * though I never enable EV_READ in the bufferevent. If
960 * that's the case, bail out.
961 */
962 if (c->type != REQUEST_UNDECIDED)
963 return;
965 /* max url len + \r\n */
966 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
967 log_debug("too much data received");
968 start_reply(c, BAD_REQUEST, "bad request");
969 return;
972 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
973 if (c->req == NULL) {
974 /* not enough data yet. */
975 bufferevent_enable(bev, EVBUFFER_READ);
976 return;
978 if (c->reqlen > 1024+2) {
979 log_debug("URL too long");
980 start_reply(c, BAD_REQUEST, "bad request");
981 return;
984 if (!parse_iri(c->req, &c->iri, &parse_err) ||
985 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
986 log_debug("IRI parse error: %s", parse_err);
987 start_reply(c, BAD_REQUEST, "bad request");
988 return;
991 if (apply_reverse_proxy(c))
992 return;
994 /* ignore the port number */
995 if (strcmp(c->iri.schema, "gemini") ||
996 strcmp(decoded, c->domain)) {
997 start_reply(c, PROXY_REFUSED, "won't proxy request");
998 return;
1001 if (apply_require_ca(c) ||
1002 apply_block_return(c)||
1003 apply_fastcgi(c))
1004 return;
1006 path = c->iri.path;
1007 p = strip_path(path, vhost_strip(c->host, path));
1008 while (*p == '/')
1009 p++;
1010 if (*p == '\0')
1011 p = ".";
1013 c->pfd = openat(vhost_dirfd(c->host, path, &c->loc), p, O_RDONLY);
1014 if (c->pfd == -1) {
1015 if (errno == EACCES)
1016 log_info("can't open %s: %s", p, strerror(errno));
1017 start_reply(c, NOT_FOUND, "not found");
1018 return;
1021 if (fstat(c->pfd, &sb) == -1) {
1022 log_warnx("fstat %s", path);
1023 start_reply(c, TEMP_FAILURE, "internal server error");
1024 return;
1027 if (S_ISDIR(sb.st_mode)) {
1028 open_dir(c);
1029 return;
1032 c->type = REQUEST_FILE;
1033 start_reply(c, SUCCESS, mime(c->conf, c->host, p));
1036 void
1037 client_write(struct bufferevent *bev, void *d)
1039 struct client *c = d;
1040 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1041 char nam[PATH_MAX];
1042 char buf[BUFSIZ];
1043 ssize_t r;
1045 switch (c->type) {
1046 case REQUEST_UNDECIDED:
1048 * Ignore spurious calls when we still don't have idea
1049 * what to do with the request.
1051 break;
1053 case REQUEST_FILE:
1054 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1055 log_warn("read");
1056 client_error(bev, EVBUFFER_ERROR, c);
1057 return;
1058 } else if (r == 0) {
1059 client_close(c);
1060 return;
1061 } else if (r != sizeof(buf))
1062 c->type = REQUEST_DONE;
1063 bufferevent_write(bev, buf, r);
1064 break;
1066 case REQUEST_DIR:
1067 /* TODO: handle big big directories better */
1068 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1069 const char *sufx = "";
1071 encode_path(nam, sizeof(nam),
1072 c->dir[c->diroff]->d_name);
1073 if (c->dir[c->diroff]->d_type == DT_DIR)
1074 sufx = "/";
1075 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1076 free(c->dir[c->diroff]);
1078 free(c->dir);
1079 c->dir = NULL;
1081 c->type = REQUEST_DONE;
1083 event_add(&c->bev->ev_write, NULL);
1084 break;
1086 case REQUEST_FCGI:
1087 case REQUEST_PROXY:
1089 * Here we depend on fastcgi or proxy connection to
1090 * provide data.
1092 break;
1094 case REQUEST_DONE:
1095 if (EVBUFFER_LENGTH(out) == 0)
1096 client_close(c);
1097 break;
1101 static void
1102 client_error(struct bufferevent *bev, short error, void *d)
1104 struct client *c = d;
1106 c->type = REQUEST_DONE;
1108 if (error & EVBUFFER_TIMEOUT) {
1109 log_debug("timeout; forcefully closing the connection");
1110 if (c->code == 0)
1111 start_reply(c, BAD_REQUEST, "timeout");
1112 else
1113 client_close(c);
1114 return;
1117 if (error & EVBUFFER_EOF) {
1118 client_close(c);
1119 return;
1122 log_warnx("unknown bufferevent error 0x%x", error);
1123 client_close(c);
1126 int
1127 start_reply(struct client *c, int code, const char *meta)
1129 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1130 const char *lang;
1131 int r, rr;
1133 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1135 c->code = code;
1136 c->meta = meta;
1138 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1139 if (r == -1)
1140 goto err;
1142 /* 2 digit status + space + 1024 max reply */
1143 if (r > 1027)
1144 goto overflow;
1146 if (c->type != REQUEST_FCGI &&
1147 c->type != REQUEST_PROXY &&
1148 !strcmp(meta, "text/gemini") &&
1149 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1150 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1151 if (rr == -1)
1152 goto err;
1153 if (r + rr > 1027)
1154 goto overflow;
1157 bufferevent_write(c->bev, "\r\n", 2);
1159 if (!vhost_disable_log(c->host, c->iri.path))
1160 log_request(c, code, meta);
1162 if (code != 20)
1163 c->type = REQUEST_DONE;
1165 return 0;
1167 err:
1168 log_warnx("evbuffer_add_printf error: no memory");
1169 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1170 c->type = REQUEST_DONE;
1171 return -1;
1173 overflow:
1174 log_warnx("reply header overflow");
1175 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1176 start_reply(c, TEMP_FAILURE, "internal error");
1177 return -1;
1180 static void
1181 client_close_ev(int fd, short event, void *d)
1183 struct client *c = d;
1185 switch (tls_close(c->ctx)) {
1186 case TLS_WANT_POLLIN:
1187 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1188 return;
1189 case TLS_WANT_POLLOUT:
1190 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1191 return;
1194 connected_clients--;
1196 free(c->req);
1198 tls_free(c->ctx);
1199 c->ctx = NULL;
1201 free(c->header);
1203 if (c->pfd != -1)
1204 close(c->pfd);
1206 if (c->dir != NULL)
1207 free(c->dir);
1209 close(c->fd);
1210 c->fd = -1;
1212 free(c);
1215 static void
1216 client_proxy_close(int fd, short event, void *d)
1218 struct tls *ctx = d;
1220 if (ctx == NULL) {
1221 close(fd);
1222 return;
1225 switch (tls_close(ctx)) {
1226 case TLS_WANT_POLLIN:
1227 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1228 break;
1229 case TLS_WANT_POLLOUT:
1230 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1231 break;
1234 tls_free(ctx);
1235 close(fd);
1238 void
1239 client_close(struct client *c)
1242 * We may end up calling client_close in various situations
1243 * and for the most unexpected reasons. Therefore, we need to
1244 * ensure that everything gets properly released once we reach
1245 * this point.
1248 SPLAY_REMOVE(client_tree_id, &clients, c);
1250 if (c->cgibev != NULL) {
1251 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1252 bufferevent_free(c->cgibev);
1253 c->cgibev = NULL;
1254 close(c->pfd);
1255 c->pfd = -1;
1258 if (c->bev != NULL) {
1259 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1260 bufferevent_free(c->bev);
1263 if (c->proxyevset &&
1264 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1265 c->proxyevset = 0;
1266 event_del(&c->proxyev);
1269 if (c->pfd != -1 && c->proxyctx != NULL) {
1270 /* shut down the proxy TLS connection */
1271 client_proxy_close(c->pfd, 0, c->proxyctx);
1272 c->pfd = -1;
1275 if (c->proxybev != NULL)
1276 bufferevent_free(c->proxybev);
1278 client_close_ev(c->fd, 0, c);
1281 void
1282 server_accept(int sock, short et, void *d)
1284 struct address *addr = d;
1285 struct client *c;
1286 struct sockaddr_storage raddr;
1287 struct sockaddr *sraddr;
1288 socklen_t len;
1289 int e, fd;
1291 sraddr = (struct sockaddr *)&raddr;
1292 len = sizeof(raddr);
1293 if ((fd = accept(sock, sraddr, &len)) == -1) {
1294 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1295 errno == ECONNABORTED)
1296 return;
1297 fatal("accept");
1300 mark_nonblock(fd);
1302 c = xcalloc(1, sizeof(*c));
1303 c->conf = addr->conf;
1304 c->addr = addr;
1305 c->id = ++server_client_id;
1306 c->fd = fd;
1307 c->pfd = -1;
1308 memcpy(&c->raddr, &raddr, sizeof(raddr));
1309 c->raddrlen = len;
1311 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1312 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1313 if (e != 0) {
1314 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1315 close(c->fd);
1316 free(c);
1317 return;
1320 if (tls_accept_socket(addr->ctx, &c->ctx, fd) == -1) {
1321 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1322 close(c->fd);
1323 free(c);
1324 return;
1327 SPLAY_INSERT(client_tree_id, &clients, c);
1328 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1329 connected_clients++;
1332 static void
1333 handle_siginfo(int fd, short ev, void *d)
1335 log_info("%d connected clients", connected_clients);
1338 static void
1339 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1340 struct conf *conf)
1342 struct address *vaddr;
1343 struct vhost *h;
1344 int r, any = 0;
1346 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1347 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1348 if (!match_addr(addr, vaddr))
1349 continue;
1351 if (!any) {
1352 any = 1;
1353 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1354 h->cert, h->certlen, h->key, h->keylen,
1355 h->ocsp, h->ocsplen);
1356 } else {
1357 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1358 h->cert, h->certlen, h->key, h->keylen,
1359 h->ocsp, h->ocsplen);
1362 if (r == -1)
1363 fatalx("failed to load keypair"
1364 " for host %s: %s", h->domain,
1365 tls_config_error(tlsconf));
1370 static void
1371 setup_tls(struct conf *conf)
1373 struct tls_config *tlsconf;
1374 struct address *addr;
1376 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1377 if ((tlsconf = tls_config_new()) == NULL)
1378 fatal("tls_config_new");
1380 if (conf->use_privsep_crypto)
1381 tls_config_use_fake_private_key(tlsconf);
1383 /* optionally accept client certs but don't verify */
1384 tls_config_verify_client_optional(tlsconf);
1385 tls_config_insecure_noverifycert(tlsconf);
1387 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1388 fatalx("tls_config_set_protocols: %s",
1389 tls_config_error(tlsconf));
1391 add_matching_kps(tlsconf, addr, conf);
1393 tls_reset(addr->ctx);
1394 if (tls_configure(addr->ctx, tlsconf) == -1)
1395 fatalx("tls_configure: %s", tls_error(addr->ctx));
1397 tls_config_free(tlsconf);
1401 static void
1402 load_vhosts(struct conf *conf)
1404 struct vhost *h;
1405 struct location *l;
1406 char path[PATH_MAX], *p;
1407 int r;
1409 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1410 TAILQ_FOREACH(l, &h->locations, locations) {
1411 if (*l->dir == '\0')
1412 continue;
1414 p = l->dir;
1416 if (conf->conftest && *conf->chroot != '\0') {
1417 r = snprintf(path, sizeof(path), "%s/%s",
1418 conf->chroot, l->dir);
1419 if (r < 0 || (size_t)r >= sizeof(path))
1420 fatalx("path too long: %s", l->dir);
1421 p = path;
1424 l->dirfd = open(p, O_RDONLY | O_DIRECTORY);
1425 if (l->dirfd == -1)
1426 fatal("open %s for domain %s", l->dir,
1427 h->domain);
1432 void
1433 server(struct privsep *ps, struct privsep_proc *p)
1435 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1438 void
1439 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1441 struct conf *c;
1443 SPLAY_INIT(&clients);
1445 #ifdef SIGINFO
1446 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1447 signal_add(&siginfo, NULL);
1448 #endif
1449 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1450 signal_add(&sigusr2, NULL);
1452 sandbox_server_process();
1455 * gemexp doesn't use the privsep crypto engine; it doesn't
1456 * use privsep at all so `ps' is NULL.
1458 if (ps != NULL) {
1459 c = ps->ps_env;
1460 if (c->use_privsep_crypto)
1461 crypto_engine_init(ps->ps_env);
1465 int
1466 server_configure_done(struct conf *conf)
1468 struct address *addr;
1470 if (load_default_mime(&conf->mime) == -1)
1471 fatal("can't load default mime");
1472 sort_mime(&conf->mime);
1473 setup_tls(conf);
1474 load_vhosts(conf);
1476 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1477 if (addr->sock != -1)
1478 event_add(&addr->evsock, NULL);
1481 return 0;
1484 static int
1485 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1487 struct privsep *ps = p->p_ps;
1488 struct conf *conf = ps->ps_env;
1490 switch (imsg_get_type(imsg)) {
1491 case IMSG_RECONF_START:
1492 case IMSG_RECONF_LOG_FMT:
1493 case IMSG_RECONF_MIME:
1494 case IMSG_RECONF_PROTOS:
1495 case IMSG_RECONF_SOCK:
1496 case IMSG_RECONF_FCGI:
1497 case IMSG_RECONF_HOST:
1498 case IMSG_RECONF_CERT:
1499 case IMSG_RECONF_KEY:
1500 case IMSG_RECONF_OCSP:
1501 case IMSG_RECONF_HOST_ADDR:
1502 case IMSG_RECONF_LOC:
1503 case IMSG_RECONF_ENV:
1504 case IMSG_RECONF_ALIAS:
1505 case IMSG_RECONF_PROXY:
1506 case IMSG_RECONF_PROXY_CERT:
1507 case IMSG_RECONF_PROXY_KEY:
1508 return config_recv(conf, imsg);
1509 case IMSG_RECONF_END:
1510 if (config_recv(conf, imsg) == -1)
1511 return -1;
1512 if (server_configure_done(conf) == -1)
1513 return -1;
1514 break;
1515 default:
1516 return -1;
1519 return 0;
1522 static int
1523 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1525 return -1;
1528 static int
1529 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1531 return -1;
1534 int
1535 client_tree_cmp(struct client *a, struct client *b)
1537 if (a->id == b->id)
1538 return 0;
1539 else if (a->id < b->id)
1540 return -1;
1541 else
1542 return +1;
1545 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)