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 const char *strip_path(const char*, int);
57 static void fmtbuf(char *, size_t, const char *, struct client *,
58 const char *);
59 static int apply_block_return(struct client*);
60 static int check_matching_certificate(X509_STORE *, struct client *);
61 static int apply_reverse_proxy(struct client *);
62 static int apply_fastcgi(struct client*);
63 static int apply_require_ca(struct client*);
64 static void open_dir(struct client*);
65 static void redirect_canonical_dir(struct client*);
67 static void client_tls_readcb(int, short, void *);
68 static void client_tls_writecb(int, short, void *);
70 static void client_read(struct bufferevent *, void *);
71 void client_write(struct bufferevent *, void *);
72 static void client_error(struct bufferevent *, short, void *);
74 static void client_close_ev(int, short, void *);
76 static void handle_siginfo(int, short, void*);
78 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
79 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
80 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
82 static struct privsep_proc procs[] = {
83 { "parent", PROC_PARENT, server_dispatch_parent },
84 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
85 { "logger", PROC_LOGGER, server_dispatch_logger },
86 };
88 static uint32_t server_client_id;
90 struct client_tree_id clients;
92 static inline int
93 match_addr(struct address *target, struct address *source)
94 {
95 return (target->ai_flags == source->ai_flags &&
96 target->ai_family == source->ai_family &&
97 target->ai_socktype == source->ai_socktype &&
98 target->ai_protocol == source->ai_protocol &&
99 target->slen == source->slen &&
100 !memcmp(&target->ss, &source->ss, target->slen));
103 static inline int
104 matches(const char *pattern, const char *path)
106 if (*path == '/')
107 path++;
108 return !fnmatch(pattern, path, 0);
111 static inline int
112 match_host(struct vhost *v, struct client *c)
114 struct alist *a;
115 struct address *addr;
117 TAILQ_FOREACH(addr, &v->addrs, addrs)
118 if (match_addr(addr, c->addr))
119 break;
120 if (addr == NULL)
121 return 0;
123 if (matches(v->domain, c->domain))
124 return 1;
126 TAILQ_FOREACH(a, &v->aliases, aliases)
127 if (matches(a->alias, c->domain))
128 return 1;
130 return 0;
133 const char *
134 vhost_lang(struct vhost *v, const char *path)
136 struct location *loc;
138 if (v == NULL || path == NULL)
139 return NULL;
141 loc = TAILQ_FIRST(&v->locations);
142 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
143 if (*loc->lang != '\0') {
144 if (matches(loc->match, path))
145 return loc->lang;
149 loc = TAILQ_FIRST(&v->locations);
150 if (*loc->lang == '\0')
151 return NULL;
152 return loc->lang;
155 const char *
156 vhost_default_mime(struct vhost *v, const char *path)
158 struct location *loc;
159 const char *default_mime = "application/octet-stream";
161 if (v == NULL || path == NULL)
162 return default_mime;
164 loc = TAILQ_FIRST(&v->locations);
165 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
166 if (*loc->default_mime != '\0') {
167 if (matches(loc->match, path))
168 return loc->default_mime;
172 loc = TAILQ_FIRST(&v->locations);
173 if (*loc->default_mime != '\0')
174 return loc->default_mime;
175 return default_mime;
178 const char *
179 vhost_index(struct vhost *v, const char *path)
181 struct location *loc;
182 const char *index = "index.gmi";
184 if (v == NULL || path == NULL)
185 return index;
187 loc = TAILQ_FIRST(&v->locations);
188 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
189 if (*loc->index != '\0') {
190 if (matches(loc->match, path))
191 return loc->index;
195 loc = TAILQ_FIRST(&v->locations);
196 if (*loc->index != '\0')
197 return loc->index;
198 return index;
201 int
202 vhost_auto_index(struct vhost *v, const char *path)
204 struct location *loc;
206 if (v == NULL || path == NULL)
207 return 0;
209 loc = TAILQ_FIRST(&v->locations);
210 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
211 if (loc->auto_index != 0) {
212 if (matches(loc->match, path))
213 return loc->auto_index == 1;
217 loc = TAILQ_FIRST(&v->locations);
218 return loc->auto_index == 1;
221 int
222 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
224 struct location *loc;
226 if (v == NULL || path == NULL)
227 return 0;
229 loc = TAILQ_FIRST(&v->locations);
230 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
231 if (loc->block_code != 0) {
232 if (matches(loc->match, path)) {
233 *code = loc->block_code;
234 *fmt = loc->block_fmt;
235 return 1;
240 loc = TAILQ_FIRST(&v->locations);
241 *code = loc->block_code;
242 *fmt = loc->block_fmt;
243 return loc->block_code != 0;
246 struct location *
247 vhost_fastcgi(struct vhost *v, const char *path)
249 struct location *loc;
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;
261 loc = TAILQ_FIRST(&v->locations);
262 return loc->fcgi == -1 ? NULL : loc;
265 int
266 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
268 struct location *loc;
269 size_t l = 0;
271 if (v == NULL || path == NULL)
272 return -1;
274 loc = TAILQ_FIRST(&v->locations);
275 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
276 l++;
277 if (loc->dirfd != -1)
278 if (matches(loc->match, path)) {
279 *retloc = l;
280 return loc->dirfd;
284 *retloc = 0;
285 loc = TAILQ_FIRST(&v->locations);
286 return loc->dirfd;
289 int
290 vhost_strip(struct vhost *v, const char *path)
292 struct location *loc;
294 if (v == NULL || path == NULL)
295 return 0;
297 loc = TAILQ_FIRST(&v->locations);
298 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
299 if (loc->strip != 0) {
300 if (matches(loc->match, path))
301 return loc->strip;
305 loc = TAILQ_FIRST(&v->locations);
306 return loc->strip;
309 X509_STORE *
310 vhost_require_ca(struct vhost *v, const char *path)
312 struct location *loc;
314 if (v == NULL || path == NULL)
315 return NULL;
317 loc = TAILQ_FIRST(&v->locations);
318 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
319 if (loc->reqca != NULL) {
320 if (matches(loc->match, path))
321 return loc->reqca;
325 loc = TAILQ_FIRST(&v->locations);
326 return loc->reqca;
329 int
330 vhost_disable_log(struct vhost *v, const char *path)
332 struct location *loc;
334 if (v == NULL || path == NULL)
335 return 0;
337 loc = TAILQ_FIRST(&v->locations);
338 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
339 if (loc->disable_log && matches(loc->match, path))
340 return 1;
343 loc = TAILQ_FIRST(&v->locations);
344 return loc->disable_log;
347 void
348 mark_nonblock(int fd)
350 int flags;
352 if ((flags = fcntl(fd, F_GETFL)) == -1)
353 fatal("fcntl(F_GETFL)");
354 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
355 fatal("fcntl(F_SETFL)");
358 static void
359 handle_handshake(int fd, short ev, void *d)
361 struct client *c = d;
362 struct conf *conf = c->conf;
363 struct vhost *h;
364 const char *servname;
365 const char *parse_err = "unknown error";
367 switch (tls_handshake(c->ctx)) {
368 case 0: /* success */
369 break;
370 case -1:
371 log_warnx("tls_handshake failed: %s", tls_error(c->ctx));
372 client_close(c);
373 return;
374 case TLS_WANT_POLLIN:
375 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
376 return;
377 case TLS_WANT_POLLOUT:
378 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
379 return;
380 default:
381 /* unreachable */
382 abort();
385 c->bev = bufferevent_new(fd, client_read, client_write,
386 client_error, c);
387 if (c->bev == NULL)
388 fatal("%s: failed to allocate client buffer", __func__);
390 event_set(&c->bev->ev_read, c->fd, EV_READ,
391 client_tls_readcb, c->bev);
392 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
393 client_tls_writecb, c->bev);
395 #if HAVE_LIBEVENT2
396 evbuffer_unfreeze(c->bev->input, 0);
397 evbuffer_unfreeze(c->bev->output, 1);
398 #endif
400 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
401 log_debug("handshake: missing SNI");
402 goto err;
405 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
406 log_info("puny_decode: %s", parse_err);
407 goto err;
410 TAILQ_FOREACH(h, &conf->hosts, vhosts)
411 if (match_host(h, c))
412 break;
414 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
415 servname != NULL ? servname : "(null)",
416 c->domain,
417 h != NULL ? h->domain : "(null)");
419 if (h != NULL) {
420 c->host = h;
421 bufferevent_enable(c->bev, EV_READ);
422 return;
425 err:
426 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
429 static const char *
430 strip_path(const char *path, int strip)
432 char *t;
434 while (strip > 0) {
435 if ((t = strchr(path, '/')) == NULL) {
436 path = strchr(path, '\0');
437 break;
439 path = t;
440 strip--;
443 return path;
446 static void
447 fmtbuf(char *buf, size_t buflen, const char *fmt, struct client *c,
448 const char *path)
450 size_t i;
451 char tmp[32];
453 *buf = '\0';
454 memset(tmp, 0, sizeof(tmp));
455 for (i = 0; *fmt; ++fmt) {
456 if (i == sizeof(tmp)-1 || *fmt == '%') {
457 strlcat(buf, tmp, buflen);
458 memset(tmp, 0, sizeof(tmp));
459 i = 0;
462 if (*fmt != '%') {
463 tmp[i++] = *fmt;
464 continue;
467 switch (*++fmt) {
468 case '%':
469 strlcat(buf, "%", buflen);
470 break;
471 case 'p':
472 if (*path != '/')
473 strlcat(buf, "/", buflen);
474 strlcat(buf, path, buflen);
475 break;
476 case 'q':
477 strlcat(buf, c->iri.query, buflen);
478 break;
479 case 'P':
480 snprintf(tmp, sizeof(tmp), "%d", c->addr->port);
481 strlcat(buf, tmp, buflen);
482 memset(tmp, 0, sizeof(tmp));
483 break;
484 case 'N':
485 strlcat(buf, c->domain, buflen);
486 break;
487 default:
488 log_warnx("%s: unknown fmt specifier %c",
489 __func__, *fmt);
493 if (i != 0)
494 strlcat(buf, tmp, buflen);
497 /* 1 if a matching `block return' (and apply it), 0 otherwise */
498 static int
499 apply_block_return(struct client *c)
501 char buf[GEMINI_URL_LEN];
502 const char *fmt, *path;
503 int code;
505 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
506 return 0;
508 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
509 fmtbuf(buf, sizeof(buf), fmt, c, path);
511 start_reply(c, code, buf);
512 return 1;
515 static struct proxy *
516 matched_proxy(struct client *c)
518 struct proxy *p;
519 const char *proto;
520 const char *host;
521 const char *port;
523 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
524 if (*(proto = p->match_proto) == '\0')
525 proto = "gemini";
526 if (*(host = p->match_host) == '\0')
527 host = "*";
528 if (*(port = p->match_port) == '\0')
529 port = "*";
531 if (matches(proto, c->iri.schema) &&
532 matches(host, c->domain) &&
533 matches(port, c->iri.port))
534 return p;
537 return NULL;
540 static int
541 check_matching_certificate(X509_STORE *store, struct client *c)
543 const uint8_t *cert;
544 size_t len;
546 if (!tls_peer_cert_provided(c->ctx)) {
547 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
548 return 1;
551 cert = tls_peer_cert_chain_pem(c->ctx, &len);
552 if (!validate_against_ca(store, cert, len)) {
553 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
554 return 1;
557 return 0;
560 static int
561 proxy_socket(struct client *c, const char *host, const char *port)
563 struct addrinfo hints, *res, *res0;
564 int r, sock, save_errno;
565 const char *cause = NULL;
567 memset(&hints, 0, sizeof(hints));
568 hints.ai_family = AF_UNSPEC;
569 hints.ai_socktype = SOCK_STREAM;
571 /* XXX: asr_run? :> */
572 r = getaddrinfo(host, port, &hints, &res0);
573 if (r != 0) {
574 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
575 host, port, gai_strerror(r));
576 return -1;
579 for (res = res0; res; res = res->ai_next) {
580 sock = socket(res->ai_family, res->ai_socktype,
581 res->ai_protocol);
582 if (sock == -1) {
583 cause = "socket";
584 continue;
587 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
588 cause = "connect";
589 save_errno = errno;
590 close(sock);
591 errno = save_errno;
592 sock = -1;
593 continue;
596 break;
599 if (sock == -1)
600 log_warn("can't connect to %s:%s: %s", host, port, cause);
602 freeaddrinfo(res0);
604 return sock;
607 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
608 static int
609 apply_reverse_proxy(struct client *c)
611 struct proxy *p;
613 if ((p = matched_proxy(c)) == NULL)
614 return 0;
616 c->proxy = p;
618 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
619 return 1;
621 log_debug("opening proxy connection for %s:%s",
622 p->host, p->port);
624 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
625 start_reply(c, PROXY_ERROR, "proxy error");
626 return 1;
629 mark_nonblock(c->pfd);
630 if (proxy_init(c) == -1)
631 start_reply(c, PROXY_ERROR, "proxy error");
633 return 1;
636 static int
637 fcgi_open_sock(struct fcgi *f)
639 struct sockaddr_un addr;
640 int fd;
642 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
643 log_warn("socket");
644 return -1;
647 memset(&addr, 0, sizeof(addr));
648 addr.sun_family = AF_UNIX;
649 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
651 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
652 log_warn("failed to connect to %s", f->path);
653 close(fd);
654 return -1;
657 return fd;
660 static int
661 fcgi_open_conn(struct fcgi *f)
663 struct addrinfo hints, *servinfo, *p;
664 int r, sock, save_errno;
665 const char *cause = NULL;
667 memset(&hints, 0, sizeof(hints));
668 hints.ai_family = AF_UNSPEC;
669 hints.ai_socktype = SOCK_STREAM;
670 hints.ai_flags = AI_ADDRCONFIG;
672 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
673 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
674 gai_strerror(r));
675 return -1;
678 for (p = servinfo; p != NULL; p = p->ai_next) {
679 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
680 if (sock == -1) {
681 cause = "socket";
682 continue;
684 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
685 cause = "connect";
686 save_errno = errno;
687 close(sock);
688 errno = save_errno;
689 continue;
691 break;
694 if (p == NULL) {
695 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
696 cause);
697 sock = -1;
700 freeaddrinfo(servinfo);
701 return sock;
704 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
705 static int
706 apply_fastcgi(struct client *c)
708 int i = 0;
709 struct fcgi *f;
710 struct location *loc;
712 if ((loc = vhost_fastcgi(c->host, c->iri.path)) == NULL)
713 return 0;
715 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
716 if (i == loc->fcgi)
717 break;
718 ++i;
721 if (f == NULL) {
722 log_warnx("can't find fcgi #%d", loc->fcgi);
723 return 0;
726 log_debug("opening fastcgi connection for (%s,%s)",
727 f->path, f->port);
729 if (*f->port == '\0')
730 c->pfd = fcgi_open_sock(f);
731 else
732 c->pfd = fcgi_open_conn(f);
734 if (c->pfd == -1) {
735 start_reply(c, CGI_ERROR, "CGI error");
736 return 1;
739 mark_nonblock(c->pfd);
741 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
742 fcgi_error, c);
743 if (c->cgibev == NULL) {
744 start_reply(c, TEMP_FAILURE, "internal server error");
745 return 1;
748 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
749 fcgi_req(c, loc);
751 return 1;
754 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
755 static int
756 apply_require_ca(struct client *c)
758 X509_STORE *store;
760 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
761 return 0;
762 return check_matching_certificate(store, c);
765 static void
766 server_dir_listing(struct client *c)
768 int root;
770 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
772 if (!vhost_auto_index(c->host, c->iri.path)) {
773 start_reply(c, NOT_FOUND, "not found");
774 return;
777 c->dirlen = scandir_fd(c->pfd, &c->dir,
778 root ? select_non_dotdot : select_non_dot,
779 alphasort);
780 if (c->dirlen == -1) {
781 log_warn("scandir_fd(%d) (vhost:%s) %s",
782 c->pfd, c->host->domain, c->iri.path);
783 start_reply(c, TEMP_FAILURE, "internal server error");
784 return;
787 c->type = REQUEST_DIR;
788 start_reply(c, SUCCESS, "text/gemini");
789 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
790 "# Index of /%s\n\n", c->iri.path);
793 static void
794 open_dir(struct client *c)
796 struct stat sb;
797 const char *index;
798 char path[PATH_MAX];
799 int fd = -1;
801 if (*c->iri.path != '\0' && !ends_with(c->iri.path, "/")) {
802 redirect_canonical_dir(c);
803 return;
806 index = vhost_index(c->host, c->iri.path);
807 fd = openat(c->pfd, index, O_RDONLY);
808 if (fd == -1) {
809 server_dir_listing(c);
810 return;
813 if (fstat(fd, &sb) == -1) {
814 log_warn("fstat");
815 close(fd);
816 start_reply(c, TEMP_FAILURE, "internal server error");
817 return;
820 if (!S_ISREG(sb.st_mode)) {
821 close(fd);
822 server_dir_listing(c);
823 return;
826 strlcpy(path, c->iri.path, sizeof(path));
827 strlcat(path, index, sizeof(path));
829 close(c->pfd);
830 c->pfd = fd;
831 c->type = REQUEST_FILE;
832 start_reply(c, SUCCESS, mime(c->conf, c->host, path));
835 static void
836 redirect_canonical_dir(struct client *c)
838 char buf[GEMINI_URL_LEN];
839 int r;
841 r = snprintf(buf, sizeof(buf), "/%s/", c->iri.path);
842 if (r < 0 || (size_t)r >= sizeof(buf)) {
843 start_reply(c, TEMP_FAILURE, "internal server error");
844 return;
847 start_reply(c, TEMP_REDIRECT, buf);
850 static void
851 client_tls_readcb(int fd, short event, void *d)
853 struct bufferevent *bufev = d;
854 struct client *client = bufev->cbarg;
855 ssize_t ret;
856 size_t len;
857 int what = EVBUFFER_READ;
858 int howmuch = IBUF_READ_SIZE;
859 char buf[IBUF_READ_SIZE];
861 if (event == EV_TIMEOUT) {
862 what |= EVBUFFER_TIMEOUT;
863 goto err;
866 if (bufev->wm_read.high != 0)
867 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
869 switch (ret = tls_read(client->ctx, buf, howmuch)) {
870 case TLS_WANT_POLLIN:
871 case TLS_WANT_POLLOUT:
872 goto retry;
873 case -1:
874 what |= EVBUFFER_ERROR;
875 goto err;
877 len = ret;
879 if (len == 0) {
880 what |= EVBUFFER_EOF;
881 goto err;
884 if (evbuffer_add(bufev->input, buf, len) == -1) {
885 what |= EVBUFFER_ERROR;
886 goto err;
889 event_add(&bufev->ev_read, NULL);
890 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
891 return;
892 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
893 /*
894 * here we could implement a read pressure policy.
895 */
898 if (bufev->readcb != NULL)
899 (*bufev->readcb)(bufev, bufev->cbarg);
901 return;
903 retry:
904 event_add(&bufev->ev_read, NULL);
905 return;
907 err:
908 (*bufev->errorcb)(bufev, what, bufev->cbarg);
911 static void
912 client_tls_writecb(int fd, short event, void *d)
914 struct bufferevent *bufev = d;
915 struct client *client = bufev->cbarg;
916 ssize_t ret;
917 size_t len;
918 short what = EVBUFFER_WRITE;
920 if (event == EV_TIMEOUT) {
921 what |= EVBUFFER_TIMEOUT;
922 goto err;
925 if (EVBUFFER_LENGTH(bufev->output) != 0) {
926 ret = tls_write(client->ctx,
927 EVBUFFER_DATA(bufev->output),
928 EVBUFFER_LENGTH(bufev->output));
929 switch (ret) {
930 case TLS_WANT_POLLIN:
931 case TLS_WANT_POLLOUT:
932 goto retry;
933 case -1:
934 what |= EVBUFFER_ERROR;
935 goto err;
937 len = ret;
938 evbuffer_drain(bufev->output, len);
941 if (EVBUFFER_LENGTH(bufev->output) != 0)
942 event_add(&bufev->ev_write, NULL);
944 if (bufev->writecb != NULL &&
945 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
946 (*bufev->writecb)(bufev, bufev->cbarg);
947 return;
949 retry:
950 event_add(&bufev->ev_write, NULL);
951 return;
952 err:
953 log_warnx("tls error: %s", tls_error(client->ctx));
954 (*bufev->errorcb)(bufev, what, bufev->cbarg);
957 static void
958 client_read(struct bufferevent *bev, void *d)
960 struct stat sb;
961 struct client *c = d;
962 struct evbuffer *src = EVBUFFER_INPUT(bev);
963 const char *path, *p, *parse_err = "invalid request";
964 char decoded[DOMAIN_NAME_LEN];
966 bufferevent_disable(bev, EVBUFFER_READ);
968 /*
969 * libevent2 can still somehow call this function, even
970 * though I never enable EV_READ in the bufferevent. If
971 * that's the case, bail out.
972 */
973 if (c->type != REQUEST_UNDECIDED)
974 return;
976 /* max url len + \r\n */
977 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
978 log_debug("too much data received");
979 start_reply(c, BAD_REQUEST, "bad request");
980 return;
983 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
984 if (c->req == NULL) {
985 /* not enough data yet. */
986 bufferevent_enable(bev, EVBUFFER_READ);
987 return;
989 if (c->reqlen > 1024+2) {
990 log_debug("URL too long");
991 start_reply(c, BAD_REQUEST, "bad request");
992 return;
995 if (!parse_iri(c->req, &c->iri, &parse_err) ||
996 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
997 log_debug("IRI parse error: %s", parse_err);
998 start_reply(c, BAD_REQUEST, "bad request");
999 return;
1002 if (apply_reverse_proxy(c))
1003 return;
1005 /* ignore the port number */
1006 if (strcmp(c->iri.schema, "gemini") ||
1007 strcmp(decoded, c->domain)) {
1008 start_reply(c, PROXY_REFUSED, "won't proxy request");
1009 return;
1012 if (apply_require_ca(c) ||
1013 apply_block_return(c)||
1014 apply_fastcgi(c))
1015 return;
1017 path = c->iri.path;
1018 p = strip_path(path, vhost_strip(c->host, path));
1019 while (*p == '/')
1020 p++;
1021 if (*p == '\0')
1022 p = ".";
1024 c->pfd = openat(vhost_dirfd(c->host, path, &c->loc), p, O_RDONLY);
1025 if (c->pfd == -1) {
1026 if (errno == EACCES)
1027 log_info("can't open %s: %s", p, strerror(errno));
1028 start_reply(c, NOT_FOUND, "not found");
1029 return;
1032 if (fstat(c->pfd, &sb) == -1) {
1033 log_warnx("fstat %s", path);
1034 start_reply(c, TEMP_FAILURE, "internal server error");
1035 return;
1038 if (S_ISDIR(sb.st_mode)) {
1039 open_dir(c);
1040 return;
1043 c->type = REQUEST_FILE;
1044 start_reply(c, SUCCESS, mime(c->conf, c->host, p));
1047 void
1048 client_write(struct bufferevent *bev, void *d)
1050 struct client *c = d;
1051 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1052 char nam[PATH_MAX];
1053 char buf[BUFSIZ];
1054 ssize_t r;
1056 switch (c->type) {
1057 case REQUEST_UNDECIDED:
1059 * Ignore spurious calls when we still don't have idea
1060 * what to do with the request.
1062 break;
1064 case REQUEST_FILE:
1065 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1066 log_warn("read");
1067 client_error(bev, EVBUFFER_ERROR, c);
1068 return;
1069 } else if (r == 0) {
1070 client_close(c);
1071 return;
1072 } else if (r != sizeof(buf))
1073 c->type = REQUEST_DONE;
1074 bufferevent_write(bev, buf, r);
1075 break;
1077 case REQUEST_DIR:
1078 /* TODO: handle big big directories better */
1079 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1080 const char *sufx = "";
1082 encode_path(nam, sizeof(nam),
1083 c->dir[c->diroff]->d_name);
1084 if (c->dir[c->diroff]->d_type == DT_DIR)
1085 sufx = "/";
1086 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1087 free(c->dir[c->diroff]);
1089 free(c->dir);
1090 c->dir = NULL;
1092 c->type = REQUEST_DONE;
1094 event_add(&c->bev->ev_write, NULL);
1095 break;
1097 case REQUEST_FCGI:
1098 case REQUEST_PROXY:
1100 * Here we depend on fastcgi or proxy connection to
1101 * provide data.
1103 break;
1105 case REQUEST_DONE:
1106 if (EVBUFFER_LENGTH(out) == 0)
1107 client_close(c);
1108 break;
1112 static void
1113 client_error(struct bufferevent *bev, short error, void *d)
1115 struct client *c = d;
1117 c->type = REQUEST_DONE;
1119 if (error & EVBUFFER_TIMEOUT) {
1120 log_debug("timeout; forcefully closing the connection");
1121 if (c->code == 0)
1122 start_reply(c, BAD_REQUEST, "timeout");
1123 else
1124 client_close(c);
1125 return;
1128 if (error & EVBUFFER_EOF) {
1129 client_close(c);
1130 return;
1133 log_warnx("unknown bufferevent error 0x%x", error);
1134 client_close(c);
1137 void
1138 start_reply(struct client *c, int code, const char *meta)
1140 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1141 const char *lang;
1142 int r, rr;
1144 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1146 c->code = code;
1147 c->meta = meta;
1149 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1150 if (r == -1)
1151 goto err;
1153 /* 2 digit status + space + 1024 max reply */
1154 if (r > 1027)
1155 goto overflow;
1157 if (c->type != REQUEST_FCGI &&
1158 c->type != REQUEST_PROXY &&
1159 !strcmp(meta, "text/gemini") &&
1160 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1161 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1162 if (rr == -1)
1163 goto err;
1164 if (r + rr > 1027)
1165 goto overflow;
1168 bufferevent_write(c->bev, "\r\n", 2);
1170 if (!vhost_disable_log(c->host, c->iri.path))
1171 log_request(c, code, meta);
1173 if (code != 20)
1174 c->type = REQUEST_DONE;
1176 return;
1178 err:
1179 log_warnx("evbuffer_add_printf error: no memory");
1180 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1181 client_close(c);
1182 return;
1184 overflow:
1185 log_warnx("reply header overflow");
1186 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1187 start_reply(c, TEMP_FAILURE, "internal error");
1190 static void
1191 client_close_ev(int fd, short event, void *d)
1193 struct client *c = d;
1195 switch (tls_close(c->ctx)) {
1196 case TLS_WANT_POLLIN:
1197 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1198 return;
1199 case TLS_WANT_POLLOUT:
1200 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1201 return;
1204 connected_clients--;
1206 free(c->req);
1208 tls_free(c->ctx);
1209 c->ctx = NULL;
1211 free(c->header);
1213 if (c->pfd != -1)
1214 close(c->pfd);
1216 if (c->dir != NULL)
1217 free(c->dir);
1219 close(c->fd);
1220 c->fd = -1;
1222 free(c);
1225 static void
1226 client_proxy_close(int fd, short event, void *d)
1228 struct tls *ctx = d;
1230 if (ctx == NULL) {
1231 close(fd);
1232 return;
1235 switch (tls_close(ctx)) {
1236 case TLS_WANT_POLLIN:
1237 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1238 break;
1239 case TLS_WANT_POLLOUT:
1240 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1241 break;
1244 tls_free(ctx);
1245 close(fd);
1248 void
1249 client_close(struct client *c)
1252 * We may end up calling client_close in various situations
1253 * and for the most unexpected reasons. Therefore, we need to
1254 * ensure that everything gets properly released once we reach
1255 * this point.
1258 SPLAY_REMOVE(client_tree_id, &clients, c);
1260 if (c->cgibev != NULL) {
1261 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1262 bufferevent_free(c->cgibev);
1263 c->cgibev = NULL;
1264 close(c->pfd);
1265 c->pfd = -1;
1268 if (c->bev != NULL) {
1269 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1270 bufferevent_free(c->bev);
1273 if (c->proxyevset &&
1274 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1275 c->proxyevset = 0;
1276 event_del(&c->proxyev);
1279 if (c->pfd != -1 && c->proxyctx != NULL) {
1280 /* shut down the proxy TLS connection */
1281 client_proxy_close(c->pfd, 0, c->proxyctx);
1282 c->pfd = -1;
1285 if (c->proxybev != NULL)
1286 bufferevent_free(c->proxybev);
1288 client_close_ev(c->fd, 0, c);
1291 void
1292 server_accept(int sock, short et, void *d)
1294 struct address *addr = d;
1295 struct client *c;
1296 struct sockaddr_storage raddr;
1297 struct sockaddr *sraddr;
1298 socklen_t len;
1299 int e, fd;
1301 sraddr = (struct sockaddr *)&raddr;
1302 len = sizeof(raddr);
1303 if ((fd = accept(sock, sraddr, &len)) == -1) {
1304 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1305 errno == ECONNABORTED)
1306 return;
1307 fatal("accept");
1310 mark_nonblock(fd);
1312 c = xcalloc(1, sizeof(*c));
1313 c->conf = addr->conf;
1314 c->addr = addr;
1315 c->id = ++server_client_id;
1316 c->fd = fd;
1317 c->pfd = -1;
1318 memcpy(&c->raddr, &raddr, sizeof(raddr));
1319 c->raddrlen = len;
1321 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1322 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1323 if (e != 0) {
1324 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1325 close(c->fd);
1326 free(c);
1327 return;
1330 if (tls_accept_socket(addr->ctx, &c->ctx, fd) == -1) {
1331 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1332 close(c->fd);
1333 free(c);
1334 return;
1337 SPLAY_INSERT(client_tree_id, &clients, c);
1338 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1339 connected_clients++;
1342 struct client *
1343 client_by_id(int id)
1345 struct client find;
1347 find.id = id;
1348 return SPLAY_FIND(client_tree_id, &clients, &find);
1351 static void
1352 handle_siginfo(int fd, short ev, void *d)
1354 log_info("%d connected clients", connected_clients);
1357 static void
1358 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1359 struct conf *conf)
1361 struct address *vaddr;
1362 struct vhost *h;
1363 int r, any = 0;
1365 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1366 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1367 if (!match_addr(addr, vaddr))
1368 continue;
1370 if (!any) {
1371 any = 1;
1372 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1373 h->cert, h->certlen, h->key, h->keylen,
1374 h->ocsp, h->ocsplen);
1375 } else {
1376 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1377 h->cert, h->certlen, h->key, h->keylen,
1378 h->ocsp, h->ocsplen);
1381 if (r == -1)
1382 fatalx("failed to load keypair"
1383 " for host %s: %s", h->domain,
1384 tls_config_error(tlsconf));
1389 static void
1390 setup_tls(struct conf *conf)
1392 struct tls_config *tlsconf;
1393 struct address *addr;
1395 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1396 if ((tlsconf = tls_config_new()) == NULL)
1397 fatal("tls_config_new");
1399 if (conf->use_privsep_crypto)
1400 tls_config_use_fake_private_key(tlsconf);
1402 /* optionally accept client certs but don't verify */
1403 tls_config_verify_client_optional(tlsconf);
1404 tls_config_insecure_noverifycert(tlsconf);
1406 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1407 fatalx("tls_config_set_protocols: %s",
1408 tls_config_error(tlsconf));
1410 add_matching_kps(tlsconf, addr, conf);
1412 tls_reset(addr->ctx);
1413 if (tls_configure(addr->ctx, tlsconf) == -1)
1414 fatalx("tls_configure: %s", tls_error(addr->ctx));
1416 tls_config_free(tlsconf);
1420 static void
1421 load_vhosts(struct conf *conf)
1423 struct vhost *h;
1424 struct location *l;
1426 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1427 TAILQ_FOREACH(l, &h->locations, locations) {
1428 if (*l->dir == '\0')
1429 continue;
1430 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1431 if (l->dirfd == -1)
1432 fatal("open %s for domain %s", l->dir,
1433 h->domain);
1438 void
1439 server(struct privsep *ps, struct privsep_proc *p)
1441 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1444 void
1445 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1447 struct conf *c;
1449 SPLAY_INIT(&clients);
1451 #ifdef SIGINFO
1452 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1453 signal_add(&siginfo, NULL);
1454 #endif
1455 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1456 signal_add(&sigusr2, NULL);
1458 sandbox_server_process();
1461 * ge doesn't use the privsep crypto engine; it doesn't use
1462 * privsep at all so `ps' is NULL.
1464 if (ps != NULL) {
1465 c = ps->ps_env;
1466 if (c->use_privsep_crypto)
1467 crypto_engine_init(ps->ps_env);
1471 int
1472 server_configure_done(struct conf *conf)
1474 struct address *addr;
1476 if (load_default_mime(&conf->mime) == -1)
1477 fatal("can't load default mime");
1478 sort_mime(&conf->mime);
1479 setup_tls(conf);
1480 load_vhosts(conf);
1482 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1483 if (addr->sock != -1)
1484 event_add(&addr->evsock, NULL);
1487 return 0;
1490 static int
1491 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1493 struct privsep *ps = p->p_ps;
1494 struct conf *conf = ps->ps_env;
1496 switch (imsg->hdr.type) {
1497 case IMSG_RECONF_START:
1498 case IMSG_RECONF_MIME:
1499 case IMSG_RECONF_PROTOS:
1500 case IMSG_RECONF_SOCK:
1501 case IMSG_RECONF_FCGI:
1502 case IMSG_RECONF_HOST:
1503 case IMSG_RECONF_CERT:
1504 case IMSG_RECONF_KEY:
1505 case IMSG_RECONF_OCSP:
1506 case IMSG_RECONF_HOST_ADDR:
1507 case IMSG_RECONF_LOC:
1508 case IMSG_RECONF_ENV:
1509 case IMSG_RECONF_ALIAS:
1510 case IMSG_RECONF_PROXY:
1511 case IMSG_RECONF_PROXY_CERT:
1512 case IMSG_RECONF_PROXY_KEY:
1513 return config_recv(conf, imsg);
1514 case IMSG_RECONF_END:
1515 if (config_recv(conf, imsg) == -1)
1516 return -1;
1517 if (server_configure_done(conf) == -1)
1518 return -1;
1519 break;
1520 default:
1521 return -1;
1524 return 0;
1527 static int
1528 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1530 return -1;
1533 static int
1534 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1536 return -1;
1539 int
1540 client_tree_cmp(struct client *a, struct client *b)
1542 if (a->id == b->id)
1543 return 0;
1544 else if (a->id < b->id)
1545 return -1;
1546 else
1547 return +1;
1550 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)