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;
250 int force_disable = 0;
252 if (v == NULL || path == NULL)
253 return NULL;
255 loc = TAILQ_FIRST(&v->locations);
256 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
257 if (loc->fcgi != -1)
258 if (matches(loc->match, path))
259 return loc;
260 if (loc->nofcgi && matches(loc->match, path))
261 force_disable = 1;
264 if (force_disable)
265 return NULL;
267 loc = TAILQ_FIRST(&v->locations);
268 return loc->fcgi == -1 ? NULL : loc;
271 int
272 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
274 struct location *loc;
275 size_t l = 0;
277 if (v == NULL || path == NULL)
278 return -1;
280 loc = TAILQ_FIRST(&v->locations);
281 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
282 l++;
283 if (loc->dirfd != -1)
284 if (matches(loc->match, path)) {
285 *retloc = l;
286 return loc->dirfd;
290 *retloc = 0;
291 loc = TAILQ_FIRST(&v->locations);
292 return loc->dirfd;
295 int
296 vhost_strip(struct vhost *v, const char *path)
298 struct location *loc;
300 if (v == NULL || path == NULL)
301 return 0;
303 loc = TAILQ_FIRST(&v->locations);
304 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
305 if (loc->strip != 0) {
306 if (matches(loc->match, path))
307 return loc->strip;
311 loc = TAILQ_FIRST(&v->locations);
312 return loc->strip;
315 X509_STORE *
316 vhost_require_ca(struct vhost *v, const char *path)
318 struct location *loc;
320 if (v == NULL || path == NULL)
321 return NULL;
323 loc = TAILQ_FIRST(&v->locations);
324 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
325 if (loc->reqca != NULL) {
326 if (matches(loc->match, path))
327 return loc->reqca;
331 loc = TAILQ_FIRST(&v->locations);
332 return loc->reqca;
335 int
336 vhost_disable_log(struct vhost *v, const char *path)
338 struct location *loc;
340 if (v == NULL || path == NULL)
341 return 0;
343 loc = TAILQ_FIRST(&v->locations);
344 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
345 if (loc->disable_log && matches(loc->match, path))
346 return 1;
349 loc = TAILQ_FIRST(&v->locations);
350 return loc->disable_log;
353 void
354 mark_nonblock(int fd)
356 int flags;
358 if ((flags = fcntl(fd, F_GETFL)) == -1)
359 fatal("fcntl(F_GETFL)");
360 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
361 fatal("fcntl(F_SETFL)");
364 static void
365 handle_handshake(int fd, short ev, void *d)
367 struct client *c = d;
368 struct conf *conf = c->conf;
369 struct vhost *h;
370 const char *servname;
371 const char *parse_err = "unknown error";
373 switch (tls_handshake(c->ctx)) {
374 case 0: /* success */
375 break;
376 case -1:
377 log_warnx("tls_handshake failed: %s", 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 const char *
436 strip_path(const char *path, int strip)
438 char *t;
440 while (strip > 0) {
441 if ((t = strchr(path, '/')) == NULL) {
442 path = strchr(path, '\0');
443 break;
445 path = t;
446 strip--;
449 return path;
452 static void
453 fmtbuf(char *buf, size_t buflen, const char *fmt, struct client *c,
454 const char *path)
456 size_t i;
457 char tmp[32];
459 *buf = '\0';
460 memset(tmp, 0, sizeof(tmp));
461 for (i = 0; *fmt; ++fmt) {
462 if (i == sizeof(tmp)-1 || *fmt == '%') {
463 strlcat(buf, tmp, buflen);
464 memset(tmp, 0, sizeof(tmp));
465 i = 0;
468 if (*fmt != '%') {
469 tmp[i++] = *fmt;
470 continue;
473 switch (*++fmt) {
474 case '%':
475 strlcat(buf, "%", buflen);
476 break;
477 case 'p':
478 if (*path != '/')
479 strlcat(buf, "/", buflen);
480 strlcat(buf, path, buflen);
481 break;
482 case 'q':
483 strlcat(buf, c->iri.query, buflen);
484 break;
485 case 'P':
486 snprintf(tmp, sizeof(tmp), "%d", c->addr->port);
487 strlcat(buf, tmp, buflen);
488 memset(tmp, 0, sizeof(tmp));
489 break;
490 case 'N':
491 strlcat(buf, c->domain, buflen);
492 break;
493 default:
494 log_warnx("%s: unknown fmt specifier %c",
495 __func__, *fmt);
499 if (i != 0)
500 strlcat(buf, tmp, buflen);
503 /* 1 if a matching `block return' (and apply it), 0 otherwise */
504 static int
505 apply_block_return(struct client *c)
507 char buf[GEMINI_URL_LEN];
508 const char *fmt, *path;
509 int code;
511 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
512 return 0;
514 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
515 fmtbuf(buf, sizeof(buf), fmt, c, path);
517 start_reply(c, code, buf);
518 return 1;
521 static struct proxy *
522 matched_proxy(struct client *c)
524 struct proxy *p;
525 const char *proto;
526 const char *host;
527 const char *port;
529 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
530 if (*(proto = p->match_proto) == '\0')
531 proto = "gemini";
532 if (*(host = p->match_host) == '\0')
533 host = "*";
534 if (*(port = p->match_port) == '\0')
535 port = "*";
537 if (matches(proto, c->iri.schema) &&
538 matches(host, c->domain) &&
539 matches(port, c->iri.port))
540 return p;
543 return NULL;
546 static int
547 check_matching_certificate(X509_STORE *store, struct client *c)
549 const uint8_t *cert;
550 size_t len;
552 if (!tls_peer_cert_provided(c->ctx)) {
553 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
554 return 1;
557 cert = tls_peer_cert_chain_pem(c->ctx, &len);
558 if (!validate_against_ca(store, cert, len)) {
559 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
560 return 1;
563 return 0;
566 static int
567 proxy_socket(struct client *c, const char *host, const char *port)
569 struct addrinfo hints, *res, *res0;
570 int r, sock, save_errno;
571 const char *cause = NULL;
573 memset(&hints, 0, sizeof(hints));
574 hints.ai_family = AF_UNSPEC;
575 hints.ai_socktype = SOCK_STREAM;
577 /* XXX: asr_run? :> */
578 r = getaddrinfo(host, port, &hints, &res0);
579 if (r != 0) {
580 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
581 host, port, gai_strerror(r));
582 return -1;
585 for (res = res0; res; res = res->ai_next) {
586 sock = socket(res->ai_family, res->ai_socktype,
587 res->ai_protocol);
588 if (sock == -1) {
589 cause = "socket";
590 continue;
593 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
594 cause = "connect";
595 save_errno = errno;
596 close(sock);
597 errno = save_errno;
598 sock = -1;
599 continue;
602 break;
605 if (sock == -1)
606 log_warn("can't connect to %s:%s: %s", host, port, cause);
608 freeaddrinfo(res0);
610 return sock;
613 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
614 static int
615 apply_reverse_proxy(struct client *c)
617 struct proxy *p;
619 if ((p = matched_proxy(c)) == NULL)
620 return 0;
622 c->proxy = p;
624 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
625 return 1;
627 log_debug("opening proxy connection for %s:%s",
628 p->host, p->port);
630 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
631 start_reply(c, PROXY_ERROR, "proxy error");
632 return 1;
635 mark_nonblock(c->pfd);
636 if (proxy_init(c) == -1)
637 start_reply(c, PROXY_ERROR, "proxy error");
639 return 1;
642 static int
643 fcgi_open_sock(struct fcgi *f)
645 struct sockaddr_un addr;
646 int fd;
648 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
649 log_warn("socket");
650 return -1;
653 memset(&addr, 0, sizeof(addr));
654 addr.sun_family = AF_UNIX;
655 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
657 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
658 log_warn("failed to connect to %s", f->path);
659 close(fd);
660 return -1;
663 return fd;
666 static int
667 fcgi_open_conn(struct fcgi *f)
669 struct addrinfo hints, *servinfo, *p;
670 int r, sock, save_errno;
671 const char *cause = NULL;
673 memset(&hints, 0, sizeof(hints));
674 hints.ai_family = AF_UNSPEC;
675 hints.ai_socktype = SOCK_STREAM;
676 hints.ai_flags = AI_ADDRCONFIG;
678 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
679 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
680 gai_strerror(r));
681 return -1;
684 for (p = servinfo; p != NULL; p = p->ai_next) {
685 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
686 if (sock == -1) {
687 cause = "socket";
688 continue;
690 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
691 cause = "connect";
692 save_errno = errno;
693 close(sock);
694 errno = save_errno;
695 continue;
697 break;
700 if (p == NULL) {
701 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
702 cause);
703 sock = -1;
706 freeaddrinfo(servinfo);
707 return sock;
710 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
711 static int
712 apply_fastcgi(struct client *c)
714 int i = 0;
715 struct fcgi *f;
716 struct location *loc;
718 if ((loc = vhost_fastcgi(c->host, c->iri.path)) == NULL)
719 return 0;
721 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
722 if (i == loc->fcgi)
723 break;
724 ++i;
727 if (f == NULL) {
728 log_warnx("can't find fcgi #%d", loc->fcgi);
729 return 0;
732 log_debug("opening fastcgi connection for (%s,%s)",
733 f->path, f->port);
735 if (*f->port == '\0')
736 c->pfd = fcgi_open_sock(f);
737 else
738 c->pfd = fcgi_open_conn(f);
740 if (c->pfd == -1) {
741 start_reply(c, CGI_ERROR, "CGI error");
742 return 1;
745 mark_nonblock(c->pfd);
747 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
748 fcgi_error, c);
749 if (c->cgibev == NULL) {
750 start_reply(c, TEMP_FAILURE, "internal server error");
751 return 1;
754 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
755 fcgi_req(c, loc);
757 return 1;
760 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
761 static int
762 apply_require_ca(struct client *c)
764 X509_STORE *store;
766 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
767 return 0;
768 return check_matching_certificate(store, c);
771 static void
772 server_dir_listing(struct client *c)
774 int root;
776 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
778 if (!vhost_auto_index(c->host, c->iri.path)) {
779 start_reply(c, NOT_FOUND, "not found");
780 return;
783 c->dirlen = scandir_fd(c->pfd, &c->dir,
784 root ? select_non_dotdot : select_non_dot,
785 alphasort);
786 if (c->dirlen == -1) {
787 log_warn("scandir_fd(%d) (vhost:%s) %s",
788 c->pfd, c->host->domain, c->iri.path);
789 start_reply(c, TEMP_FAILURE, "internal server error");
790 return;
793 c->type = REQUEST_DIR;
794 start_reply(c, SUCCESS, "text/gemini");
795 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
796 "# Index of /%s\n\n", c->iri.path);
799 static void
800 open_dir(struct client *c)
802 struct stat sb;
803 const char *index;
804 char path[PATH_MAX];
805 int fd = -1;
807 if (*c->iri.path != '\0' && !ends_with(c->iri.path, "/")) {
808 redirect_canonical_dir(c);
809 return;
812 index = vhost_index(c->host, c->iri.path);
813 fd = openat(c->pfd, index, O_RDONLY);
814 if (fd == -1) {
815 server_dir_listing(c);
816 return;
819 if (fstat(fd, &sb) == -1) {
820 log_warn("fstat");
821 close(fd);
822 start_reply(c, TEMP_FAILURE, "internal server error");
823 return;
826 if (!S_ISREG(sb.st_mode)) {
827 close(fd);
828 server_dir_listing(c);
829 return;
832 strlcpy(path, c->iri.path, sizeof(path));
833 strlcat(path, index, sizeof(path));
835 close(c->pfd);
836 c->pfd = fd;
837 c->type = REQUEST_FILE;
838 start_reply(c, SUCCESS, mime(c->conf, c->host, path));
841 static void
842 redirect_canonical_dir(struct client *c)
844 char buf[GEMINI_URL_LEN];
845 int r;
847 r = snprintf(buf, sizeof(buf), "/%s/", c->iri.path);
848 if (r < 0 || (size_t)r >= sizeof(buf)) {
849 start_reply(c, TEMP_FAILURE, "internal server error");
850 return;
853 start_reply(c, TEMP_REDIRECT, buf);
856 static void
857 client_tls_readcb(int fd, short event, void *d)
859 struct bufferevent *bufev = d;
860 struct client *client = bufev->cbarg;
861 ssize_t ret;
862 size_t len;
863 int what = EVBUFFER_READ;
864 int howmuch = IBUF_READ_SIZE;
865 char buf[IBUF_READ_SIZE];
867 if (event == EV_TIMEOUT) {
868 what |= EVBUFFER_TIMEOUT;
869 goto err;
872 if (bufev->wm_read.high != 0)
873 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
875 switch (ret = tls_read(client->ctx, buf, howmuch)) {
876 case TLS_WANT_POLLIN:
877 case TLS_WANT_POLLOUT:
878 goto retry;
879 case -1:
880 what |= EVBUFFER_ERROR;
881 goto err;
883 len = ret;
885 if (len == 0) {
886 what |= EVBUFFER_EOF;
887 goto err;
890 if (evbuffer_add(bufev->input, buf, len) == -1) {
891 what |= EVBUFFER_ERROR;
892 goto err;
895 event_add(&bufev->ev_read, NULL);
896 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
897 return;
898 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
899 /*
900 * here we could implement a read pressure policy.
901 */
904 if (bufev->readcb != NULL)
905 (*bufev->readcb)(bufev, bufev->cbarg);
907 return;
909 retry:
910 event_add(&bufev->ev_read, NULL);
911 return;
913 err:
914 (*bufev->errorcb)(bufev, what, bufev->cbarg);
917 static void
918 client_tls_writecb(int fd, short event, void *d)
920 struct bufferevent *bufev = d;
921 struct client *client = bufev->cbarg;
922 ssize_t ret;
923 size_t len;
924 short what = EVBUFFER_WRITE;
926 if (event == EV_TIMEOUT) {
927 what |= EVBUFFER_TIMEOUT;
928 goto err;
931 if (EVBUFFER_LENGTH(bufev->output) != 0) {
932 ret = tls_write(client->ctx,
933 EVBUFFER_DATA(bufev->output),
934 EVBUFFER_LENGTH(bufev->output));
935 switch (ret) {
936 case TLS_WANT_POLLIN:
937 case TLS_WANT_POLLOUT:
938 goto retry;
939 case -1:
940 what |= EVBUFFER_ERROR;
941 goto err;
943 len = ret;
944 evbuffer_drain(bufev->output, len);
947 if (EVBUFFER_LENGTH(bufev->output) != 0)
948 event_add(&bufev->ev_write, NULL);
950 if (bufev->writecb != NULL &&
951 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
952 (*bufev->writecb)(bufev, bufev->cbarg);
953 return;
955 retry:
956 event_add(&bufev->ev_write, NULL);
957 return;
958 err:
959 log_warnx("tls error: %s", tls_error(client->ctx));
960 (*bufev->errorcb)(bufev, what, bufev->cbarg);
963 static void
964 client_read(struct bufferevent *bev, void *d)
966 struct stat sb;
967 struct client *c = d;
968 struct evbuffer *src = EVBUFFER_INPUT(bev);
969 const char *path, *p, *parse_err = "invalid request";
970 char decoded[DOMAIN_NAME_LEN];
972 bufferevent_disable(bev, EVBUFFER_READ);
974 /*
975 * libevent2 can still somehow call this function, even
976 * though I never enable EV_READ in the bufferevent. If
977 * that's the case, bail out.
978 */
979 if (c->type != REQUEST_UNDECIDED)
980 return;
982 /* max url len + \r\n */
983 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
984 log_debug("too much data received");
985 start_reply(c, BAD_REQUEST, "bad request");
986 return;
989 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
990 if (c->req == NULL) {
991 /* not enough data yet. */
992 bufferevent_enable(bev, EVBUFFER_READ);
993 return;
995 if (c->reqlen > 1024+2) {
996 log_debug("URL too long");
997 start_reply(c, BAD_REQUEST, "bad request");
998 return;
1001 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1002 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1003 log_debug("IRI parse error: %s", parse_err);
1004 start_reply(c, BAD_REQUEST, "bad request");
1005 return;
1008 if (apply_reverse_proxy(c))
1009 return;
1011 /* ignore the port number */
1012 if (strcmp(c->iri.schema, "gemini") ||
1013 strcmp(decoded, c->domain)) {
1014 start_reply(c, PROXY_REFUSED, "won't proxy request");
1015 return;
1018 if (apply_require_ca(c) ||
1019 apply_block_return(c)||
1020 apply_fastcgi(c))
1021 return;
1023 path = c->iri.path;
1024 p = strip_path(path, vhost_strip(c->host, path));
1025 while (*p == '/')
1026 p++;
1027 if (*p == '\0')
1028 p = ".";
1030 c->pfd = openat(vhost_dirfd(c->host, path, &c->loc), p, O_RDONLY);
1031 if (c->pfd == -1) {
1032 if (errno == EACCES)
1033 log_info("can't open %s: %s", p, strerror(errno));
1034 start_reply(c, NOT_FOUND, "not found");
1035 return;
1038 if (fstat(c->pfd, &sb) == -1) {
1039 log_warnx("fstat %s", path);
1040 start_reply(c, TEMP_FAILURE, "internal server error");
1041 return;
1044 if (S_ISDIR(sb.st_mode)) {
1045 open_dir(c);
1046 return;
1049 c->type = REQUEST_FILE;
1050 start_reply(c, SUCCESS, mime(c->conf, c->host, p));
1053 void
1054 client_write(struct bufferevent *bev, void *d)
1056 struct client *c = d;
1057 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1058 char nam[PATH_MAX];
1059 char buf[BUFSIZ];
1060 ssize_t r;
1062 switch (c->type) {
1063 case REQUEST_UNDECIDED:
1065 * Ignore spurious calls when we still don't have idea
1066 * what to do with the request.
1068 break;
1070 case REQUEST_FILE:
1071 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1072 log_warn("read");
1073 client_error(bev, EVBUFFER_ERROR, c);
1074 return;
1075 } else if (r == 0) {
1076 client_close(c);
1077 return;
1078 } else if (r != sizeof(buf))
1079 c->type = REQUEST_DONE;
1080 bufferevent_write(bev, buf, r);
1081 break;
1083 case REQUEST_DIR:
1084 /* TODO: handle big big directories better */
1085 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1086 const char *sufx = "";
1088 encode_path(nam, sizeof(nam),
1089 c->dir[c->diroff]->d_name);
1090 if (c->dir[c->diroff]->d_type == DT_DIR)
1091 sufx = "/";
1092 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1093 free(c->dir[c->diroff]);
1095 free(c->dir);
1096 c->dir = NULL;
1098 c->type = REQUEST_DONE;
1100 event_add(&c->bev->ev_write, NULL);
1101 break;
1103 case REQUEST_FCGI:
1104 case REQUEST_PROXY:
1106 * Here we depend on fastcgi or proxy connection to
1107 * provide data.
1109 break;
1111 case REQUEST_DONE:
1112 if (EVBUFFER_LENGTH(out) == 0)
1113 client_close(c);
1114 break;
1118 static void
1119 client_error(struct bufferevent *bev, short error, void *d)
1121 struct client *c = d;
1123 c->type = REQUEST_DONE;
1125 if (error & EVBUFFER_TIMEOUT) {
1126 log_debug("timeout; forcefully closing the connection");
1127 if (c->code == 0)
1128 start_reply(c, BAD_REQUEST, "timeout");
1129 else
1130 client_close(c);
1131 return;
1134 if (error & EVBUFFER_EOF) {
1135 client_close(c);
1136 return;
1139 log_warnx("unknown bufferevent error 0x%x", error);
1140 client_close(c);
1143 void
1144 start_reply(struct client *c, int code, const char *meta)
1146 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1147 const char *lang;
1148 int r, rr;
1150 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1152 c->code = code;
1153 c->meta = meta;
1155 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1156 if (r == -1)
1157 goto err;
1159 /* 2 digit status + space + 1024 max reply */
1160 if (r > 1027)
1161 goto overflow;
1163 if (c->type != REQUEST_FCGI &&
1164 c->type != REQUEST_PROXY &&
1165 !strcmp(meta, "text/gemini") &&
1166 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1167 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1168 if (rr == -1)
1169 goto err;
1170 if (r + rr > 1027)
1171 goto overflow;
1174 bufferevent_write(c->bev, "\r\n", 2);
1176 if (!vhost_disable_log(c->host, c->iri.path))
1177 log_request(c, code, meta);
1179 if (code != 20)
1180 c->type = REQUEST_DONE;
1182 return;
1184 err:
1185 log_warnx("evbuffer_add_printf error: no memory");
1186 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1187 client_close(c);
1188 return;
1190 overflow:
1191 log_warnx("reply header overflow");
1192 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1193 start_reply(c, TEMP_FAILURE, "internal error");
1196 static void
1197 client_close_ev(int fd, short event, void *d)
1199 struct client *c = d;
1201 switch (tls_close(c->ctx)) {
1202 case TLS_WANT_POLLIN:
1203 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1204 return;
1205 case TLS_WANT_POLLOUT:
1206 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1207 return;
1210 connected_clients--;
1212 free(c->req);
1214 tls_free(c->ctx);
1215 c->ctx = NULL;
1217 free(c->header);
1219 if (c->pfd != -1)
1220 close(c->pfd);
1222 if (c->dir != NULL)
1223 free(c->dir);
1225 close(c->fd);
1226 c->fd = -1;
1228 free(c);
1231 static void
1232 client_proxy_close(int fd, short event, void *d)
1234 struct tls *ctx = d;
1236 if (ctx == NULL) {
1237 close(fd);
1238 return;
1241 switch (tls_close(ctx)) {
1242 case TLS_WANT_POLLIN:
1243 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1244 break;
1245 case TLS_WANT_POLLOUT:
1246 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1247 break;
1250 tls_free(ctx);
1251 close(fd);
1254 void
1255 client_close(struct client *c)
1258 * We may end up calling client_close in various situations
1259 * and for the most unexpected reasons. Therefore, we need to
1260 * ensure that everything gets properly released once we reach
1261 * this point.
1264 SPLAY_REMOVE(client_tree_id, &clients, c);
1266 if (c->cgibev != NULL) {
1267 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1268 bufferevent_free(c->cgibev);
1269 c->cgibev = NULL;
1270 close(c->pfd);
1271 c->pfd = -1;
1274 if (c->bev != NULL) {
1275 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1276 bufferevent_free(c->bev);
1279 if (c->proxyevset &&
1280 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1281 c->proxyevset = 0;
1282 event_del(&c->proxyev);
1285 if (c->pfd != -1 && c->proxyctx != NULL) {
1286 /* shut down the proxy TLS connection */
1287 client_proxy_close(c->pfd, 0, c->proxyctx);
1288 c->pfd = -1;
1291 if (c->proxybev != NULL)
1292 bufferevent_free(c->proxybev);
1294 client_close_ev(c->fd, 0, c);
1297 void
1298 server_accept(int sock, short et, void *d)
1300 struct address *addr = d;
1301 struct client *c;
1302 struct sockaddr_storage raddr;
1303 struct sockaddr *sraddr;
1304 socklen_t len;
1305 int e, fd;
1307 sraddr = (struct sockaddr *)&raddr;
1308 len = sizeof(raddr);
1309 if ((fd = accept(sock, sraddr, &len)) == -1) {
1310 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1311 errno == ECONNABORTED)
1312 return;
1313 fatal("accept");
1316 mark_nonblock(fd);
1318 c = xcalloc(1, sizeof(*c));
1319 c->conf = addr->conf;
1320 c->addr = addr;
1321 c->id = ++server_client_id;
1322 c->fd = fd;
1323 c->pfd = -1;
1324 memcpy(&c->raddr, &raddr, sizeof(raddr));
1325 c->raddrlen = len;
1327 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1328 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1329 if (e != 0) {
1330 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1331 close(c->fd);
1332 free(c);
1333 return;
1336 if (tls_accept_socket(addr->ctx, &c->ctx, fd) == -1) {
1337 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1338 close(c->fd);
1339 free(c);
1340 return;
1343 SPLAY_INSERT(client_tree_id, &clients, c);
1344 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1345 connected_clients++;
1348 struct client *
1349 client_by_id(int id)
1351 struct client find;
1353 find.id = id;
1354 return SPLAY_FIND(client_tree_id, &clients, &find);
1357 static void
1358 handle_siginfo(int fd, short ev, void *d)
1360 log_info("%d connected clients", connected_clients);
1363 static void
1364 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1365 struct conf *conf)
1367 struct address *vaddr;
1368 struct vhost *h;
1369 int r, any = 0;
1371 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1372 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1373 if (!match_addr(addr, vaddr))
1374 continue;
1376 if (!any) {
1377 any = 1;
1378 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1379 h->cert, h->certlen, h->key, h->keylen,
1380 h->ocsp, h->ocsplen);
1381 } else {
1382 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1383 h->cert, h->certlen, h->key, h->keylen,
1384 h->ocsp, h->ocsplen);
1387 if (r == -1)
1388 fatalx("failed to load keypair"
1389 " for host %s: %s", h->domain,
1390 tls_config_error(tlsconf));
1395 static void
1396 setup_tls(struct conf *conf)
1398 struct tls_config *tlsconf;
1399 struct address *addr;
1401 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1402 if ((tlsconf = tls_config_new()) == NULL)
1403 fatal("tls_config_new");
1405 if (conf->use_privsep_crypto)
1406 tls_config_use_fake_private_key(tlsconf);
1408 /* optionally accept client certs but don't verify */
1409 tls_config_verify_client_optional(tlsconf);
1410 tls_config_insecure_noverifycert(tlsconf);
1412 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1413 fatalx("tls_config_set_protocols: %s",
1414 tls_config_error(tlsconf));
1416 add_matching_kps(tlsconf, addr, conf);
1418 tls_reset(addr->ctx);
1419 if (tls_configure(addr->ctx, tlsconf) == -1)
1420 fatalx("tls_configure: %s", tls_error(addr->ctx));
1422 tls_config_free(tlsconf);
1426 static void
1427 load_vhosts(struct conf *conf)
1429 struct vhost *h;
1430 struct location *l;
1432 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1433 TAILQ_FOREACH(l, &h->locations, locations) {
1434 if (*l->dir == '\0')
1435 continue;
1436 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1437 if (l->dirfd == -1)
1438 fatal("open %s for domain %s", l->dir,
1439 h->domain);
1444 void
1445 server(struct privsep *ps, struct privsep_proc *p)
1447 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1450 void
1451 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1453 struct conf *c;
1455 SPLAY_INIT(&clients);
1457 #ifdef SIGINFO
1458 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1459 signal_add(&siginfo, NULL);
1460 #endif
1461 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1462 signal_add(&sigusr2, NULL);
1464 sandbox_server_process();
1467 * ge doesn't use the privsep crypto engine; it doesn't use
1468 * privsep at all so `ps' is NULL.
1470 if (ps != NULL) {
1471 c = ps->ps_env;
1472 if (c->use_privsep_crypto)
1473 crypto_engine_init(ps->ps_env);
1477 int
1478 server_configure_done(struct conf *conf)
1480 struct address *addr;
1482 if (load_default_mime(&conf->mime) == -1)
1483 fatal("can't load default mime");
1484 sort_mime(&conf->mime);
1485 setup_tls(conf);
1486 load_vhosts(conf);
1488 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1489 if (addr->sock != -1)
1490 event_add(&addr->evsock, NULL);
1493 return 0;
1496 static int
1497 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1499 struct privsep *ps = p->p_ps;
1500 struct conf *conf = ps->ps_env;
1502 switch (imsg->hdr.type) {
1503 case IMSG_RECONF_START:
1504 case IMSG_RECONF_MIME:
1505 case IMSG_RECONF_PROTOS:
1506 case IMSG_RECONF_SOCK:
1507 case IMSG_RECONF_FCGI:
1508 case IMSG_RECONF_HOST:
1509 case IMSG_RECONF_CERT:
1510 case IMSG_RECONF_KEY:
1511 case IMSG_RECONF_OCSP:
1512 case IMSG_RECONF_HOST_ADDR:
1513 case IMSG_RECONF_LOC:
1514 case IMSG_RECONF_ENV:
1515 case IMSG_RECONF_ALIAS:
1516 case IMSG_RECONF_PROXY:
1517 case IMSG_RECONF_PROXY_CERT:
1518 case IMSG_RECONF_PROXY_KEY:
1519 return config_recv(conf, imsg);
1520 case IMSG_RECONF_END:
1521 if (config_recv(conf, imsg) == -1)
1522 return -1;
1523 if (server_configure_done(conf) == -1)
1524 return -1;
1525 break;
1526 default:
1527 return -1;
1530 return 0;
1533 static int
1534 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1536 return -1;
1539 static int
1540 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1542 return -1;
1545 int
1546 client_tree_cmp(struct client *a, struct client *b)
1548 if (a->id == b->id)
1549 return 0;
1550 else if (a->id < b->id)
1551 return -1;
1552 else
1553 return +1;
1556 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)