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("tls_handshake failed: %s", tls_error(c->ctx));
377 client_close(c);
378 return;
379 case TLS_WANT_POLLIN:
380 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
381 return;
382 case TLS_WANT_POLLOUT:
383 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
384 return;
385 default:
386 /* unreachable */
387 abort();
390 c->bev = bufferevent_new(fd, client_read, client_write,
391 client_error, c);
392 if (c->bev == NULL)
393 fatal("%s: failed to allocate client buffer", __func__);
395 event_set(&c->bev->ev_read, c->fd, EV_READ,
396 client_tls_readcb, c->bev);
397 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
398 client_tls_writecb, c->bev);
400 #if HAVE_LIBEVENT2
401 evbuffer_unfreeze(c->bev->input, 0);
402 evbuffer_unfreeze(c->bev->output, 1);
403 #endif
405 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
406 log_debug("handshake: missing SNI");
407 goto err;
410 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
411 log_info("puny_decode: %s", parse_err);
412 goto err;
415 TAILQ_FOREACH(h, &conf->hosts, vhosts)
416 if (match_host(h, c))
417 break;
419 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
420 servname != NULL ? servname : "(null)",
421 c->domain,
422 h != NULL ? h->domain : "(null)");
424 if (h != NULL) {
425 c->host = h;
426 bufferevent_enable(c->bev, EV_READ);
427 return;
430 err:
431 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
434 static void
435 fmtbuf(char *buf, size_t buflen, const char *fmt, struct client *c,
436 const char *path)
438 size_t i;
439 char tmp[32];
441 *buf = '\0';
442 memset(tmp, 0, sizeof(tmp));
443 for (i = 0; *fmt; ++fmt) {
444 if (i == sizeof(tmp)-1 || *fmt == '%') {
445 strlcat(buf, tmp, buflen);
446 memset(tmp, 0, sizeof(tmp));
447 i = 0;
450 if (*fmt != '%') {
451 tmp[i++] = *fmt;
452 continue;
455 switch (*++fmt) {
456 case '%':
457 strlcat(buf, "%", buflen);
458 break;
459 case 'p':
460 if (*path != '/')
461 strlcat(buf, "/", buflen);
462 strlcat(buf, path, buflen);
463 break;
464 case 'q':
465 strlcat(buf, c->iri.query, buflen);
466 break;
467 case 'P':
468 snprintf(tmp, sizeof(tmp), "%d", c->addr->port);
469 strlcat(buf, tmp, buflen);
470 memset(tmp, 0, sizeof(tmp));
471 break;
472 case 'N':
473 strlcat(buf, c->domain, buflen);
474 break;
475 default:
476 log_warnx("%s: unknown fmt specifier %c",
477 __func__, *fmt);
481 if (i != 0)
482 strlcat(buf, tmp, buflen);
485 /* 1 if a matching `block return' (and apply it), 0 otherwise */
486 static int
487 apply_block_return(struct client *c)
489 char buf[GEMINI_URL_LEN];
490 const char *fmt, *path;
491 int code;
493 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
494 return 0;
496 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
497 fmtbuf(buf, sizeof(buf), fmt, c, path);
499 start_reply(c, code, buf);
500 return 1;
503 static struct proxy *
504 matched_proxy(struct client *c)
506 struct proxy *p;
507 const char *proto;
508 const char *host;
509 const char *port;
511 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
512 if (*(proto = p->match_proto) == '\0')
513 proto = "gemini";
514 if (*(host = p->match_host) == '\0')
515 host = "*";
516 if (*(port = p->match_port) == '\0')
517 port = "*";
519 if (matches(proto, c->iri.schema) &&
520 matches(host, c->domain) &&
521 matches(port, c->iri.port))
522 return p;
525 return NULL;
528 static int
529 check_matching_certificate(X509_STORE *store, struct client *c)
531 const uint8_t *cert;
532 size_t len;
534 if (!tls_peer_cert_provided(c->ctx)) {
535 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
536 return 1;
539 cert = tls_peer_cert_chain_pem(c->ctx, &len);
540 if (!validate_against_ca(store, cert, len)) {
541 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
542 return 1;
545 return 0;
548 static int
549 proxy_socket(struct client *c, const char *host, const char *port)
551 struct addrinfo hints, *res, *res0;
552 int r, sock, save_errno;
553 const char *cause = NULL;
555 memset(&hints, 0, sizeof(hints));
556 hints.ai_family = AF_UNSPEC;
557 hints.ai_socktype = SOCK_STREAM;
559 /* XXX: asr_run? :> */
560 r = getaddrinfo(host, port, &hints, &res0);
561 if (r != 0) {
562 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
563 host, port, gai_strerror(r));
564 return -1;
567 for (res = res0; res; res = res->ai_next) {
568 sock = socket(res->ai_family, res->ai_socktype,
569 res->ai_protocol);
570 if (sock == -1) {
571 cause = "socket";
572 continue;
575 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
576 cause = "connect";
577 save_errno = errno;
578 close(sock);
579 errno = save_errno;
580 sock = -1;
581 continue;
584 break;
587 if (sock == -1)
588 log_warn("can't connect to %s:%s: %s", host, port, cause);
590 freeaddrinfo(res0);
592 return sock;
595 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
596 static int
597 apply_reverse_proxy(struct client *c)
599 struct proxy *p;
601 if ((p = matched_proxy(c)) == NULL)
602 return 0;
604 c->proxy = p;
606 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
607 return 1;
609 log_debug("opening proxy connection for %s:%s",
610 p->host, p->port);
612 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
613 start_reply(c, PROXY_ERROR, "proxy error");
614 return 1;
617 mark_nonblock(c->pfd);
618 if (proxy_init(c) == -1)
619 start_reply(c, PROXY_ERROR, "proxy error");
621 return 1;
624 static int
625 fcgi_open_sock(struct fcgi *f)
627 struct sockaddr_un addr;
628 int fd;
630 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
631 log_warn("socket");
632 return -1;
635 memset(&addr, 0, sizeof(addr));
636 addr.sun_family = AF_UNIX;
637 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
639 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
640 log_warn("failed to connect to %s", f->path);
641 close(fd);
642 return -1;
645 return fd;
648 static int
649 fcgi_open_conn(struct fcgi *f)
651 struct addrinfo hints, *servinfo, *p;
652 int r, sock, save_errno;
653 const char *cause = NULL;
655 memset(&hints, 0, sizeof(hints));
656 hints.ai_family = AF_UNSPEC;
657 hints.ai_socktype = SOCK_STREAM;
658 hints.ai_flags = AI_ADDRCONFIG;
660 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
661 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
662 gai_strerror(r));
663 return -1;
666 for (p = servinfo; p != NULL; p = p->ai_next) {
667 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
668 if (sock == -1) {
669 cause = "socket";
670 continue;
672 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
673 cause = "connect";
674 save_errno = errno;
675 close(sock);
676 errno = save_errno;
677 continue;
679 break;
682 if (p == NULL) {
683 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
684 cause);
685 sock = -1;
688 freeaddrinfo(servinfo);
689 return sock;
692 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
693 static int
694 apply_fastcgi(struct client *c)
696 int i = 0;
697 struct fcgi *f;
698 struct location *loc;
700 if ((loc = vhost_fastcgi(c->host, c->iri.path)) == NULL)
701 return 0;
703 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
704 if (i == loc->fcgi)
705 break;
706 ++i;
709 if (f == NULL) {
710 log_warnx("can't find fcgi #%d", loc->fcgi);
711 return 0;
714 log_debug("opening fastcgi connection for (%s,%s)",
715 f->path, f->port);
717 if (*f->port == '\0')
718 c->pfd = fcgi_open_sock(f);
719 else
720 c->pfd = fcgi_open_conn(f);
722 if (c->pfd == -1) {
723 start_reply(c, CGI_ERROR, "CGI error");
724 return 1;
727 mark_nonblock(c->pfd);
729 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
730 fcgi_error, c);
731 if (c->cgibev == NULL) {
732 start_reply(c, TEMP_FAILURE, "internal server error");
733 return 1;
736 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
737 fcgi_req(c, loc);
739 return 1;
742 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
743 static int
744 apply_require_ca(struct client *c)
746 X509_STORE *store;
748 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
749 return 0;
750 return check_matching_certificate(store, c);
753 static void
754 server_dir_listing(struct client *c)
756 int root;
758 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
760 if (!vhost_auto_index(c->host, c->iri.path)) {
761 start_reply(c, NOT_FOUND, "not found");
762 return;
765 c->dirlen = scandir_fd(c->pfd, &c->dir,
766 root ? select_non_dotdot : select_non_dot,
767 alphasort);
768 if (c->dirlen == -1) {
769 log_warn("scandir_fd(%d) (vhost:%s) %s",
770 c->pfd, c->host->domain, c->iri.path);
771 start_reply(c, TEMP_FAILURE, "internal server error");
772 return;
775 c->type = REQUEST_DIR;
776 start_reply(c, SUCCESS, "text/gemini");
777 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
778 "# Index of /%s\n\n", c->iri.path);
781 static void
782 open_dir(struct client *c)
784 struct stat sb;
785 const char *index;
786 char path[PATH_MAX];
787 int fd = -1;
789 if (*c->iri.path != '\0' && !ends_with(c->iri.path, "/")) {
790 redirect_canonical_dir(c);
791 return;
794 index = vhost_index(c->host, c->iri.path);
795 fd = openat(c->pfd, index, O_RDONLY);
796 if (fd == -1) {
797 server_dir_listing(c);
798 return;
801 if (fstat(fd, &sb) == -1) {
802 log_warn("fstat");
803 close(fd);
804 start_reply(c, TEMP_FAILURE, "internal server error");
805 return;
808 if (!S_ISREG(sb.st_mode)) {
809 close(fd);
810 server_dir_listing(c);
811 return;
814 strlcpy(path, c->iri.path, sizeof(path));
815 strlcat(path, index, sizeof(path));
817 close(c->pfd);
818 c->pfd = fd;
819 c->type = REQUEST_FILE;
820 start_reply(c, SUCCESS, mime(c->conf, c->host, path));
823 static void
824 redirect_canonical_dir(struct client *c)
826 char buf[GEMINI_URL_LEN];
827 int r;
829 r = snprintf(buf, sizeof(buf), "/%s/", c->iri.path);
830 if (r < 0 || (size_t)r >= sizeof(buf)) {
831 start_reply(c, TEMP_FAILURE, "internal server error");
832 return;
835 start_reply(c, TEMP_REDIRECT, buf);
838 static void
839 client_tls_readcb(int fd, short event, void *d)
841 struct bufferevent *bufev = d;
842 struct client *client = bufev->cbarg;
843 ssize_t ret;
844 size_t len;
845 int what = EVBUFFER_READ;
846 int howmuch = IBUF_READ_SIZE;
847 char buf[IBUF_READ_SIZE];
849 if (event == EV_TIMEOUT) {
850 what |= EVBUFFER_TIMEOUT;
851 goto err;
854 if (bufev->wm_read.high != 0)
855 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
857 switch (ret = tls_read(client->ctx, buf, howmuch)) {
858 case TLS_WANT_POLLIN:
859 case TLS_WANT_POLLOUT:
860 goto retry;
861 case -1:
862 what |= EVBUFFER_ERROR;
863 goto err;
865 len = ret;
867 if (len == 0) {
868 what |= EVBUFFER_EOF;
869 goto err;
872 if (evbuffer_add(bufev->input, buf, len) == -1) {
873 what |= EVBUFFER_ERROR;
874 goto err;
877 event_add(&bufev->ev_read, NULL);
878 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
879 return;
880 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
881 /*
882 * here we could implement a read pressure policy.
883 */
886 if (bufev->readcb != NULL)
887 (*bufev->readcb)(bufev, bufev->cbarg);
889 return;
891 retry:
892 event_add(&bufev->ev_read, NULL);
893 return;
895 err:
896 (*bufev->errorcb)(bufev, what, bufev->cbarg);
899 static void
900 client_tls_writecb(int fd, short event, void *d)
902 struct bufferevent *bufev = d;
903 struct client *client = bufev->cbarg;
904 ssize_t ret;
905 size_t len;
906 short what = EVBUFFER_WRITE;
908 if (event == EV_TIMEOUT) {
909 what |= EVBUFFER_TIMEOUT;
910 goto err;
913 if (EVBUFFER_LENGTH(bufev->output) != 0) {
914 ret = tls_write(client->ctx,
915 EVBUFFER_DATA(bufev->output),
916 EVBUFFER_LENGTH(bufev->output));
917 switch (ret) {
918 case TLS_WANT_POLLIN:
919 case TLS_WANT_POLLOUT:
920 goto retry;
921 case -1:
922 what |= EVBUFFER_ERROR;
923 goto err;
925 len = ret;
926 evbuffer_drain(bufev->output, len);
929 if (EVBUFFER_LENGTH(bufev->output) != 0)
930 event_add(&bufev->ev_write, NULL);
932 if (bufev->writecb != NULL &&
933 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
934 (*bufev->writecb)(bufev, bufev->cbarg);
935 return;
937 retry:
938 event_add(&bufev->ev_write, NULL);
939 return;
940 err:
941 log_warnx("tls error: %s", tls_error(client->ctx));
942 (*bufev->errorcb)(bufev, what, bufev->cbarg);
945 static void
946 client_read(struct bufferevent *bev, void *d)
948 struct stat sb;
949 struct client *c = d;
950 struct evbuffer *src = EVBUFFER_INPUT(bev);
951 const char *path, *p, *parse_err = "invalid request";
952 char decoded[DOMAIN_NAME_LEN];
954 bufferevent_disable(bev, EVBUFFER_READ);
956 /*
957 * libevent2 can still somehow call this function, even
958 * though I never enable EV_READ in the bufferevent. If
959 * that's the case, bail out.
960 */
961 if (c->type != REQUEST_UNDECIDED)
962 return;
964 /* max url len + \r\n */
965 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
966 log_debug("too much data received");
967 start_reply(c, BAD_REQUEST, "bad request");
968 return;
971 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
972 if (c->req == NULL) {
973 /* not enough data yet. */
974 bufferevent_enable(bev, EVBUFFER_READ);
975 return;
977 if (c->reqlen > 1024+2) {
978 log_debug("URL too long");
979 start_reply(c, BAD_REQUEST, "bad request");
980 return;
983 if (!parse_iri(c->req, &c->iri, &parse_err) ||
984 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
985 log_debug("IRI parse error: %s", parse_err);
986 start_reply(c, BAD_REQUEST, "bad request");
987 return;
990 if (apply_reverse_proxy(c))
991 return;
993 /* ignore the port number */
994 if (strcmp(c->iri.schema, "gemini") ||
995 strcmp(decoded, c->domain)) {
996 start_reply(c, PROXY_REFUSED, "won't proxy request");
997 return;
1000 if (apply_require_ca(c) ||
1001 apply_block_return(c)||
1002 apply_fastcgi(c))
1003 return;
1005 path = c->iri.path;
1006 p = strip_path(path, vhost_strip(c->host, path));
1007 while (*p == '/')
1008 p++;
1009 if (*p == '\0')
1010 p = ".";
1012 c->pfd = openat(vhost_dirfd(c->host, path, &c->loc), p, O_RDONLY);
1013 if (c->pfd == -1) {
1014 if (errno == EACCES)
1015 log_info("can't open %s: %s", p, strerror(errno));
1016 start_reply(c, NOT_FOUND, "not found");
1017 return;
1020 if (fstat(c->pfd, &sb) == -1) {
1021 log_warnx("fstat %s", path);
1022 start_reply(c, TEMP_FAILURE, "internal server error");
1023 return;
1026 if (S_ISDIR(sb.st_mode)) {
1027 open_dir(c);
1028 return;
1031 c->type = REQUEST_FILE;
1032 start_reply(c, SUCCESS, mime(c->conf, c->host, p));
1035 void
1036 client_write(struct bufferevent *bev, void *d)
1038 struct client *c = d;
1039 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1040 char nam[PATH_MAX];
1041 char buf[BUFSIZ];
1042 ssize_t r;
1044 switch (c->type) {
1045 case REQUEST_UNDECIDED:
1047 * Ignore spurious calls when we still don't have idea
1048 * what to do with the request.
1050 break;
1052 case REQUEST_FILE:
1053 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1054 log_warn("read");
1055 client_error(bev, EVBUFFER_ERROR, c);
1056 return;
1057 } else if (r == 0) {
1058 client_close(c);
1059 return;
1060 } else if (r != sizeof(buf))
1061 c->type = REQUEST_DONE;
1062 bufferevent_write(bev, buf, r);
1063 break;
1065 case REQUEST_DIR:
1066 /* TODO: handle big big directories better */
1067 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1068 const char *sufx = "";
1070 encode_path(nam, sizeof(nam),
1071 c->dir[c->diroff]->d_name);
1072 if (c->dir[c->diroff]->d_type == DT_DIR)
1073 sufx = "/";
1074 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1075 free(c->dir[c->diroff]);
1077 free(c->dir);
1078 c->dir = NULL;
1080 c->type = REQUEST_DONE;
1082 event_add(&c->bev->ev_write, NULL);
1083 break;
1085 case REQUEST_FCGI:
1086 case REQUEST_PROXY:
1088 * Here we depend on fastcgi or proxy connection to
1089 * provide data.
1091 break;
1093 case REQUEST_DONE:
1094 if (EVBUFFER_LENGTH(out) == 0)
1095 client_close(c);
1096 break;
1100 static void
1101 client_error(struct bufferevent *bev, short error, void *d)
1103 struct client *c = d;
1105 c->type = REQUEST_DONE;
1107 if (error & EVBUFFER_TIMEOUT) {
1108 log_debug("timeout; forcefully closing the connection");
1109 if (c->code == 0)
1110 start_reply(c, BAD_REQUEST, "timeout");
1111 else
1112 client_close(c);
1113 return;
1116 if (error & EVBUFFER_EOF) {
1117 client_close(c);
1118 return;
1121 log_warnx("unknown bufferevent error 0x%x", error);
1122 client_close(c);
1125 int
1126 start_reply(struct client *c, int code, const char *meta)
1128 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1129 const char *lang;
1130 int r, rr;
1132 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1134 c->code = code;
1135 c->meta = meta;
1137 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1138 if (r == -1)
1139 goto err;
1141 /* 2 digit status + space + 1024 max reply */
1142 if (r > 1027)
1143 goto overflow;
1145 if (c->type != REQUEST_FCGI &&
1146 c->type != REQUEST_PROXY &&
1147 !strcmp(meta, "text/gemini") &&
1148 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1149 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1150 if (rr == -1)
1151 goto err;
1152 if (r + rr > 1027)
1153 goto overflow;
1156 bufferevent_write(c->bev, "\r\n", 2);
1158 if (!vhost_disable_log(c->host, c->iri.path))
1159 log_request(c, code, meta);
1161 if (code != 20)
1162 c->type = REQUEST_DONE;
1164 return 0;
1166 err:
1167 log_warnx("evbuffer_add_printf error: no memory");
1168 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1169 c->type = REQUEST_DONE;
1170 return -1;
1172 overflow:
1173 log_warnx("reply header overflow");
1174 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1175 start_reply(c, TEMP_FAILURE, "internal error");
1176 return -1;
1179 static void
1180 client_close_ev(int fd, short event, void *d)
1182 struct client *c = d;
1184 switch (tls_close(c->ctx)) {
1185 case TLS_WANT_POLLIN:
1186 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1187 return;
1188 case TLS_WANT_POLLOUT:
1189 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1190 return;
1193 connected_clients--;
1195 free(c->req);
1197 tls_free(c->ctx);
1198 c->ctx = NULL;
1200 free(c->header);
1202 if (c->pfd != -1)
1203 close(c->pfd);
1205 if (c->dir != NULL)
1206 free(c->dir);
1208 close(c->fd);
1209 c->fd = -1;
1211 free(c);
1214 static void
1215 client_proxy_close(int fd, short event, void *d)
1217 struct tls *ctx = d;
1219 if (ctx == NULL) {
1220 close(fd);
1221 return;
1224 switch (tls_close(ctx)) {
1225 case TLS_WANT_POLLIN:
1226 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1227 break;
1228 case TLS_WANT_POLLOUT:
1229 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1230 break;
1233 tls_free(ctx);
1234 close(fd);
1237 void
1238 client_close(struct client *c)
1241 * We may end up calling client_close in various situations
1242 * and for the most unexpected reasons. Therefore, we need to
1243 * ensure that everything gets properly released once we reach
1244 * this point.
1247 SPLAY_REMOVE(client_tree_id, &clients, c);
1249 if (c->cgibev != NULL) {
1250 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1251 bufferevent_free(c->cgibev);
1252 c->cgibev = NULL;
1253 close(c->pfd);
1254 c->pfd = -1;
1257 if (c->bev != NULL) {
1258 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1259 bufferevent_free(c->bev);
1262 if (c->proxyevset &&
1263 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1264 c->proxyevset = 0;
1265 event_del(&c->proxyev);
1268 if (c->pfd != -1 && c->proxyctx != NULL) {
1269 /* shut down the proxy TLS connection */
1270 client_proxy_close(c->pfd, 0, c->proxyctx);
1271 c->pfd = -1;
1274 if (c->proxybev != NULL)
1275 bufferevent_free(c->proxybev);
1277 client_close_ev(c->fd, 0, c);
1280 void
1281 server_accept(int sock, short et, void *d)
1283 struct address *addr = d;
1284 struct client *c;
1285 struct sockaddr_storage raddr;
1286 struct sockaddr *sraddr;
1287 socklen_t len;
1288 int e, fd;
1290 sraddr = (struct sockaddr *)&raddr;
1291 len = sizeof(raddr);
1292 if ((fd = accept(sock, sraddr, &len)) == -1) {
1293 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1294 errno == ECONNABORTED)
1295 return;
1296 fatal("accept");
1299 mark_nonblock(fd);
1301 c = xcalloc(1, sizeof(*c));
1302 c->conf = addr->conf;
1303 c->addr = addr;
1304 c->id = ++server_client_id;
1305 c->fd = fd;
1306 c->pfd = -1;
1307 memcpy(&c->raddr, &raddr, sizeof(raddr));
1308 c->raddrlen = len;
1310 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1311 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1312 if (e != 0) {
1313 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1314 close(c->fd);
1315 free(c);
1316 return;
1319 if (tls_accept_socket(addr->ctx, &c->ctx, fd) == -1) {
1320 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1321 close(c->fd);
1322 free(c);
1323 return;
1326 SPLAY_INSERT(client_tree_id, &clients, c);
1327 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1328 connected_clients++;
1331 struct client *
1332 client_by_id(int id)
1334 struct client find;
1336 find.id = id;
1337 return SPLAY_FIND(client_tree_id, &clients, &find);
1340 static void
1341 handle_siginfo(int fd, short ev, void *d)
1343 log_info("%d connected clients", connected_clients);
1346 static void
1347 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1348 struct conf *conf)
1350 struct address *vaddr;
1351 struct vhost *h;
1352 int r, any = 0;
1354 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1355 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1356 if (!match_addr(addr, vaddr))
1357 continue;
1359 if (!any) {
1360 any = 1;
1361 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1362 h->cert, h->certlen, h->key, h->keylen,
1363 h->ocsp, h->ocsplen);
1364 } else {
1365 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1366 h->cert, h->certlen, h->key, h->keylen,
1367 h->ocsp, h->ocsplen);
1370 if (r == -1)
1371 fatalx("failed to load keypair"
1372 " for host %s: %s", h->domain,
1373 tls_config_error(tlsconf));
1378 static void
1379 setup_tls(struct conf *conf)
1381 struct tls_config *tlsconf;
1382 struct address *addr;
1384 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1385 if ((tlsconf = tls_config_new()) == NULL)
1386 fatal("tls_config_new");
1388 if (conf->use_privsep_crypto)
1389 tls_config_use_fake_private_key(tlsconf);
1391 /* optionally accept client certs but don't verify */
1392 tls_config_verify_client_optional(tlsconf);
1393 tls_config_insecure_noverifycert(tlsconf);
1395 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1396 fatalx("tls_config_set_protocols: %s",
1397 tls_config_error(tlsconf));
1399 add_matching_kps(tlsconf, addr, conf);
1401 tls_reset(addr->ctx);
1402 if (tls_configure(addr->ctx, tlsconf) == -1)
1403 fatalx("tls_configure: %s", tls_error(addr->ctx));
1405 tls_config_free(tlsconf);
1409 static void
1410 load_vhosts(struct conf *conf)
1412 struct vhost *h;
1413 struct location *l;
1415 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1416 TAILQ_FOREACH(l, &h->locations, locations) {
1417 if (*l->dir == '\0')
1418 continue;
1419 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1420 if (l->dirfd == -1)
1421 fatal("open %s for domain %s", l->dir,
1422 h->domain);
1427 void
1428 server(struct privsep *ps, struct privsep_proc *p)
1430 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1433 void
1434 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1436 struct conf *c;
1438 SPLAY_INIT(&clients);
1440 #ifdef SIGINFO
1441 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1442 signal_add(&siginfo, NULL);
1443 #endif
1444 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1445 signal_add(&sigusr2, NULL);
1447 sandbox_server_process();
1450 * gemexp doesn't use the privsep crypto engine; it doesn't
1451 * use privsep at all so `ps' is NULL.
1453 if (ps != NULL) {
1454 c = ps->ps_env;
1455 if (c->use_privsep_crypto)
1456 crypto_engine_init(ps->ps_env);
1460 int
1461 server_configure_done(struct conf *conf)
1463 struct address *addr;
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);
1471 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1472 if (addr->sock != -1)
1473 event_add(&addr->evsock, NULL);
1476 return 0;
1479 static int
1480 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1482 struct privsep *ps = p->p_ps;
1483 struct conf *conf = ps->ps_env;
1485 switch (imsg->hdr.type) {
1486 case IMSG_RECONF_START:
1487 case IMSG_RECONF_LOG_FMT:
1488 case IMSG_RECONF_MIME:
1489 case IMSG_RECONF_PROTOS:
1490 case IMSG_RECONF_SOCK:
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_HOST_ADDR:
1497 case IMSG_RECONF_LOC:
1498 case IMSG_RECONF_ENV:
1499 case IMSG_RECONF_ALIAS:
1500 case IMSG_RECONF_PROXY:
1501 case IMSG_RECONF_PROXY_CERT:
1502 case IMSG_RECONF_PROXY_KEY:
1503 return config_recv(conf, imsg);
1504 case IMSG_RECONF_END:
1505 if (config_recv(conf, imsg) == -1)
1506 return -1;
1507 if (server_configure_done(conf) == -1)
1508 return -1;
1509 break;
1510 default:
1511 return -1;
1514 return 0;
1517 static int
1518 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1520 return -1;
1523 static int
1524 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1526 return -1;
1529 int
1530 client_tree_cmp(struct client *a, struct client *b)
1532 if (a->id == b->id)
1533 return 0;
1534 else if (a->id < b->id)
1535 return -1;
1536 else
1537 return +1;
1540 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)