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 int check_path(struct client*, const char*, int*);
56 static void open_file(struct client*);
57 static void handle_handshake(int, short, void*);
58 static const char *strip_path(const char*, int);
59 static void fmt_sbuf(const char*, struct client*, const char*);
60 static int apply_block_return(struct client*);
61 static int check_matching_certificate(X509_STORE *, struct client *);
62 static int apply_reverse_proxy(struct client *);
63 static int apply_fastcgi(struct client*);
64 static int apply_require_ca(struct client*);
65 static void open_dir(struct client*);
66 static void redirect_canonical_dir(struct client*);
68 static void client_tls_readcb(int, short, void *);
69 static void client_tls_writecb(int, short, void *);
71 static void client_read(struct bufferevent *, void *);
72 void client_write(struct bufferevent *, void *);
73 static void client_error(struct bufferevent *, short, void *);
75 static void client_close_ev(int, short, void *);
77 static void handle_siginfo(int, short, void*);
79 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
80 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
81 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
83 static struct privsep_proc procs[] = {
84 { "parent", PROC_PARENT, server_dispatch_parent },
85 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
86 { "logger", PROC_LOGGER, server_dispatch_logger },
87 };
89 static uint32_t server_client_id;
91 struct client_tree_id clients;
93 static inline int
94 match_addr(struct address *target, struct address *source)
95 {
96 return (target->ai_flags == source->ai_flags &&
97 target->ai_family == source->ai_family &&
98 target->ai_socktype == source->ai_socktype &&
99 target->ai_protocol == source->ai_protocol &&
100 target->slen == source->slen &&
101 !memcmp(&target->ss, &source->ss, target->slen));
104 static inline int
105 matches(const char *pattern, const char *path)
107 if (*path == '/')
108 path++;
109 return !fnmatch(pattern, path, 0);
112 static inline int
113 match_host(struct vhost *v, struct client *c)
115 struct alist *a;
116 struct address *addr;
118 TAILQ_FOREACH(addr, &v->addrs, addrs)
119 if (match_addr(addr, c->addr))
120 break;
121 if (addr == NULL)
122 return 0;
124 if (matches(v->domain, c->domain))
125 return 1;
127 TAILQ_FOREACH(a, &v->aliases, aliases)
128 if (matches(a->alias, c->domain))
129 return 1;
131 return 0;
134 const char *
135 vhost_lang(struct vhost *v, const char *path)
137 struct location *loc;
139 if (v == NULL || path == NULL)
140 return NULL;
142 loc = TAILQ_FIRST(&v->locations);
143 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
144 if (*loc->lang != '\0') {
145 if (matches(loc->match, path))
146 return loc->lang;
150 loc = TAILQ_FIRST(&v->locations);
151 if (*loc->lang == '\0')
152 return NULL;
153 return loc->lang;
156 const char *
157 vhost_default_mime(struct vhost *v, const char *path)
159 struct location *loc;
160 const char *default_mime = "application/octet-stream";
162 if (v == NULL || path == NULL)
163 return default_mime;
165 loc = TAILQ_FIRST(&v->locations);
166 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
167 if (*loc->default_mime != '\0') {
168 if (matches(loc->match, path))
169 return loc->default_mime;
173 loc = TAILQ_FIRST(&v->locations);
174 if (*loc->default_mime != '\0')
175 return loc->default_mime;
176 return default_mime;
179 const char *
180 vhost_index(struct vhost *v, const char *path)
182 struct location *loc;
183 const char *index = "index.gmi";
185 if (v == NULL || path == NULL)
186 return index;
188 loc = TAILQ_FIRST(&v->locations);
189 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
190 if (*loc->index != '\0') {
191 if (matches(loc->match, path))
192 return loc->index;
196 loc = TAILQ_FIRST(&v->locations);
197 if (*loc->index != '\0')
198 return loc->index;
199 return index;
202 int
203 vhost_auto_index(struct vhost *v, const char *path)
205 struct location *loc;
207 if (v == NULL || path == NULL)
208 return 0;
210 loc = TAILQ_FIRST(&v->locations);
211 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
212 if (loc->auto_index != 0) {
213 if (matches(loc->match, path))
214 return loc->auto_index == 1;
218 loc = TAILQ_FIRST(&v->locations);
219 return loc->auto_index == 1;
222 int
223 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
225 struct location *loc;
227 if (v == NULL || path == NULL)
228 return 0;
230 loc = TAILQ_FIRST(&v->locations);
231 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
232 if (loc->block_code != 0) {
233 if (matches(loc->match, path)) {
234 *code = loc->block_code;
235 *fmt = loc->block_fmt;
236 return 1;
241 loc = TAILQ_FIRST(&v->locations);
242 *code = loc->block_code;
243 *fmt = loc->block_fmt;
244 return loc->block_code != 0;
247 int
248 vhost_fastcgi(struct vhost *v, const char *path)
250 struct location *loc;
252 if (v == NULL || path == NULL)
253 return -1;
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->fcgi;
262 loc = TAILQ_FIRST(&v->locations);
263 return loc->fcgi;
266 int
267 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
269 struct location *loc;
270 size_t l = 0;
272 if (v == NULL || path == NULL)
273 return -1;
275 loc = TAILQ_FIRST(&v->locations);
276 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
277 l++;
278 if (loc->dirfd != -1)
279 if (matches(loc->match, path)) {
280 *retloc = l;
281 return loc->dirfd;
285 *retloc = 0;
286 loc = TAILQ_FIRST(&v->locations);
287 return loc->dirfd;
290 int
291 vhost_strip(struct vhost *v, const char *path)
293 struct location *loc;
295 if (v == NULL || path == NULL)
296 return 0;
298 loc = TAILQ_FIRST(&v->locations);
299 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
300 if (loc->strip != 0) {
301 if (matches(loc->match, path))
302 return loc->strip;
306 loc = TAILQ_FIRST(&v->locations);
307 return loc->strip;
310 X509_STORE *
311 vhost_require_ca(struct vhost *v, const char *path)
313 struct location *loc;
315 if (v == NULL || path == NULL)
316 return NULL;
318 loc = TAILQ_FIRST(&v->locations);
319 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
320 if (loc->reqca != NULL) {
321 if (matches(loc->match, path))
322 return loc->reqca;
326 loc = TAILQ_FIRST(&v->locations);
327 return loc->reqca;
330 int
331 vhost_disable_log(struct vhost *v, const char *path)
333 struct location *loc;
335 if (v == NULL || path == NULL)
336 return 0;
338 loc = TAILQ_FIRST(&v->locations);
339 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
340 if (loc->disable_log && matches(loc->match, path))
341 return 1;
344 loc = TAILQ_FIRST(&v->locations);
345 return loc->disable_log;
348 static int
349 check_path(struct client *c, const char *path, int *fd)
351 struct stat sb;
352 const char *p;
353 int dirfd, strip;
355 assert(path != NULL);
357 /*
358 * in send_dir we add an initial / (to be redirect-friendly),
359 * but here we want to skip it
360 */
361 if (*path == '/')
362 path++;
364 strip = vhost_strip(c->host, path);
365 p = strip_path(path, strip);
367 if (*p == '/')
368 p = p+1;
369 if (*p == '\0')
370 p = ".";
372 dirfd = vhost_dirfd(c->host, path, &c->loc);
373 log_debug("check_path: strip=%d path=%s original=%s",
374 strip, p, path);
375 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
376 if (errno == EACCES)
377 log_info("can't open %s: %s", p, strerror(errno));
378 return FILE_MISSING;
381 if (fstat(*fd, &sb) == -1) {
382 log_warn("fstat %s", path);
383 return FILE_MISSING;
386 if (S_ISDIR(sb.st_mode))
387 return FILE_DIRECTORY;
389 return FILE_EXISTS;
392 static void
393 open_file(struct client *c)
395 switch (check_path(c, c->iri.path, &c->pfd)) {
396 case FILE_EXISTS:
397 c->type = REQUEST_FILE;
398 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
399 return;
401 case FILE_DIRECTORY:
402 open_dir(c);
403 return;
405 case FILE_MISSING:
406 start_reply(c, NOT_FOUND, "not found");
407 return;
409 default:
410 /* unreachable */
411 abort();
415 void
416 mark_nonblock(int fd)
418 int flags;
420 if ((flags = fcntl(fd, F_GETFL)) == -1)
421 fatal("fcntl(F_GETFL)");
422 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
423 fatal("fcntl(F_SETFL)");
426 static void
427 handle_handshake(int fd, short ev, void *d)
429 struct client *c = d;
430 struct conf *conf = c->conf;
431 struct vhost *h;
432 const char *servname;
433 const char *parse_err = "unknown error";
435 switch (tls_handshake(c->ctx)) {
436 case 0: /* success */
437 break;
438 case -1:
439 log_warnx("tls_handshake failed: %s", tls_error(c->ctx));
440 client_close(c);
441 return;
442 case TLS_WANT_POLLIN:
443 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
444 return;
445 case TLS_WANT_POLLOUT:
446 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
447 return;
448 default:
449 /* unreachable */
450 abort();
453 c->bev = bufferevent_new(fd, client_read, client_write,
454 client_error, c);
455 if (c->bev == NULL)
456 fatal("%s: failed to allocate client buffer", __func__);
458 event_set(&c->bev->ev_read, c->fd, EV_READ,
459 client_tls_readcb, c->bev);
460 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
461 client_tls_writecb, c->bev);
463 #if HAVE_LIBEVENT2
464 evbuffer_unfreeze(c->bev->input, 0);
465 evbuffer_unfreeze(c->bev->output, 1);
466 #endif
468 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
469 log_debug("handshake: missing SNI");
470 goto err;
473 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
474 log_info("puny_decode: %s", parse_err);
475 goto err;
478 TAILQ_FOREACH(h, &conf->hosts, vhosts)
479 if (match_host(h, c))
480 break;
482 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
483 servname != NULL ? servname : "(null)",
484 c->domain,
485 h != NULL ? h->domain : "(null)");
487 if (h != NULL) {
488 c->host = h;
489 bufferevent_enable(c->bev, EV_READ);
490 return;
493 err:
494 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
497 static const char *
498 strip_path(const char *path, int strip)
500 char *t;
502 while (strip > 0) {
503 if ((t = strchr(path, '/')) == NULL) {
504 path = strchr(path, '\0');
505 break;
507 path = t;
508 strip--;
511 return path;
514 static void
515 fmt_sbuf(const char *fmt, struct client *c, const char *path)
517 size_t i;
518 char buf[32];
520 memset(buf, 0, sizeof(buf));
521 for (i = 0; *fmt; ++fmt) {
522 if (i == sizeof(buf)-1 || *fmt == '%') {
523 strlcat(c->sbuf, buf, sizeof(c->sbuf));
524 memset(buf, 0, sizeof(buf));
525 i = 0;
528 if (*fmt != '%') {
529 buf[i++] = *fmt;
530 continue;
533 switch (*++fmt) {
534 case '%':
535 strlcat(c->sbuf, "%", sizeof(c->sbuf));
536 break;
537 case 'p':
538 if (*path != '/')
539 strlcat(c->sbuf, "/", sizeof(c->sbuf));
540 strlcat(c->sbuf, path, sizeof(c->sbuf));
541 break;
542 case 'q':
543 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
544 break;
545 case 'P':
546 snprintf(buf, sizeof(buf), "%d", c->addr->port);
547 strlcat(c->sbuf, buf, sizeof(c->sbuf));
548 memset(buf, 0, sizeof(buf));
549 break;
550 case 'N':
551 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
552 break;
553 default:
554 fatalx("%s: unknown fmt specifier %c",
555 __func__, *fmt);
559 if (i != 0)
560 strlcat(c->sbuf, buf, sizeof(c->sbuf));
563 /* 1 if a matching `block return' (and apply it), 0 otherwise */
564 static int
565 apply_block_return(struct client *c)
567 const char *fmt, *path;
568 int code;
570 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
571 return 0;
573 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
574 fmt_sbuf(fmt, c, path);
576 start_reply(c, code, c->sbuf);
577 return 1;
580 static struct proxy *
581 matched_proxy(struct client *c)
583 struct proxy *p;
584 const char *proto;
585 const char *host;
586 const char *port;
588 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
589 if (*(proto = p->match_proto) == '\0')
590 proto = "gemini";
591 if (*(host = p->match_host) == '\0')
592 host = "*";
593 if (*(port = p->match_port) == '\0')
594 port = "*";
596 if (matches(proto, c->iri.schema) &&
597 matches(host, c->domain) &&
598 matches(port, c->iri.port))
599 return p;
602 return NULL;
605 static int
606 check_matching_certificate(X509_STORE *store, struct client *c)
608 const uint8_t *cert;
609 size_t len;
611 if (!tls_peer_cert_provided(c->ctx)) {
612 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
613 return 1;
616 cert = tls_peer_cert_chain_pem(c->ctx, &len);
617 if (!validate_against_ca(store, cert, len)) {
618 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
619 return 1;
622 return 0;
625 static int
626 proxy_socket(struct client *c, const char *host, const char *port)
628 struct addrinfo hints, *res, *res0;
629 int r, sock, save_errno;
630 const char *cause = NULL;
632 memset(&hints, 0, sizeof(hints));
633 hints.ai_family = AF_UNSPEC;
634 hints.ai_socktype = SOCK_STREAM;
636 /* XXX: asr_run? :> */
637 r = getaddrinfo(host, port, &hints, &res0);
638 if (r != 0) {
639 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
640 host, port, gai_strerror(r));
641 return -1;
644 for (res = res0; res; res = res->ai_next) {
645 sock = socket(res->ai_family, res->ai_socktype,
646 res->ai_protocol);
647 if (sock == -1) {
648 cause = "socket";
649 continue;
652 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
653 cause = "connect";
654 save_errno = errno;
655 close(sock);
656 errno = save_errno;
657 sock = -1;
658 continue;
661 break;
664 if (sock == -1)
665 log_warn("can't connect to %s:%s: %s", host, port, cause);
667 freeaddrinfo(res0);
669 return sock;
672 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
673 static int
674 apply_reverse_proxy(struct client *c)
676 struct proxy *p;
678 if ((p = matched_proxy(c)) == NULL)
679 return 0;
681 c->proxy = p;
683 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
684 return 1;
686 log_debug("opening proxy connection for %s:%s",
687 p->host, p->port);
689 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
690 start_reply(c, PROXY_ERROR, "proxy error");
691 return 1;
694 mark_nonblock(c->pfd);
695 if (proxy_init(c) == -1)
696 start_reply(c, PROXY_ERROR, "proxy error");
698 return 1;
701 static int
702 fcgi_open_sock(struct fcgi *f)
704 struct sockaddr_un addr;
705 int fd;
707 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
708 log_warn("socket");
709 return -1;
712 memset(&addr, 0, sizeof(addr));
713 addr.sun_family = AF_UNIX;
714 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
716 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
717 log_warn("failed to connect to %s", f->path);
718 close(fd);
719 return -1;
722 return fd;
725 static int
726 fcgi_open_conn(struct fcgi *f)
728 struct addrinfo hints, *servinfo, *p;
729 int r, sock, save_errno;
730 const char *cause = NULL;
732 memset(&hints, 0, sizeof(hints));
733 hints.ai_family = AF_UNSPEC;
734 hints.ai_socktype = SOCK_STREAM;
735 hints.ai_flags = AI_ADDRCONFIG;
737 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
738 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
739 gai_strerror(r));
740 return -1;
743 for (p = servinfo; p != NULL; p = p->ai_next) {
744 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
745 if (sock == -1) {
746 cause = "socket";
747 continue;
749 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
750 cause = "connect";
751 save_errno = errno;
752 close(sock);
753 errno = save_errno;
754 continue;
756 break;
759 if (p == NULL) {
760 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
761 cause);
762 sock = -1;
765 freeaddrinfo(servinfo);
766 return sock;
769 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
770 static int
771 apply_fastcgi(struct client *c)
773 int id, i = 0;
774 struct fcgi *f;
776 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
777 return 0;
779 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
780 if (i == id)
781 break;
782 ++i;
785 if (f == NULL) {
786 log_warnx("can't find fcgi #%d", id);
787 return 0;
790 log_debug("opening fastcgi connection for (%s,%s)",
791 f->path, f->port);
793 if (*f->port == '\0')
794 c->pfd = fcgi_open_sock(f);
795 else
796 c->pfd = fcgi_open_conn(f);
798 if (c->pfd == -1) {
799 start_reply(c, CGI_ERROR, "CGI error");
800 return 1;
803 mark_nonblock(c->pfd);
805 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
806 fcgi_error, c);
807 if (c->cgibev == NULL) {
808 start_reply(c, TEMP_FAILURE, "internal server error");
809 return 1;
812 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
813 fcgi_req(c);
815 return 1;
818 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
819 static int
820 apply_require_ca(struct client *c)
822 X509_STORE *store;
824 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
825 return 0;
826 return check_matching_certificate(store, c);
829 static void
830 open_dir(struct client *c)
832 size_t len;
833 int dirfd, root;
834 char *before_file;
836 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
838 len = strlen(c->iri.path);
839 if (len > 0 && !ends_with(c->iri.path, "/")) {
840 redirect_canonical_dir(c);
841 return;
844 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
845 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
846 if (!ends_with(c->sbuf, "/"))
847 strlcat(c->sbuf, "/", sizeof(c->sbuf));
848 before_file = strchr(c->sbuf, '\0');
849 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
850 sizeof(c->sbuf));
851 if (len >= sizeof(c->sbuf)) {
852 start_reply(c, TEMP_FAILURE, "internal server error");
853 return;
856 c->iri.path = c->sbuf;
858 /* close later unless we have to generate the dir listing */
859 dirfd = c->pfd;
860 c->pfd = -1;
862 switch (check_path(c, c->iri.path, &c->pfd)) {
863 case FILE_EXISTS:
864 c->type = REQUEST_FILE;
865 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
866 break;
868 case FILE_DIRECTORY:
869 start_reply(c, TEMP_REDIRECT, c->sbuf);
870 break;
872 case FILE_MISSING:
873 *before_file = '\0';
875 if (!vhost_auto_index(c->host, c->iri.path)) {
876 start_reply(c, NOT_FOUND, "not found");
877 break;
880 c->type = REQUEST_DIR;
882 c->dirlen = scandir_fd(dirfd, &c->dir,
883 root ? select_non_dotdot : select_non_dot,
884 alphasort);
885 if (c->dirlen == -1) {
886 log_warn("scandir_fd(%d) (vhost:%s) %s",
887 c->pfd, c->host->domain, c->iri.path);
888 start_reply(c, TEMP_FAILURE, "internal server error");
889 return;
891 c->diroff = 0;
892 c->off = 0;
894 start_reply(c, SUCCESS, "text/gemini");
895 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
896 "# Index of %s\n\n", c->iri.path);
897 return;
899 default:
900 /* unreachable */
901 abort();
904 close(dirfd);
907 static void
908 redirect_canonical_dir(struct client *c)
910 int r;
912 r = snprintf(c->sbuf, sizeof(c->sbuf), "/%s/", c->iri.path);
913 if (r < 0 || (size_t)r >= sizeof(c->sbuf)) {
914 start_reply(c, TEMP_FAILURE, "internal server error");
915 return;
918 start_reply(c, TEMP_REDIRECT, c->sbuf);
921 static void
922 client_tls_readcb(int fd, short event, void *d)
924 struct bufferevent *bufev = d;
925 struct client *client = bufev->cbarg;
926 ssize_t ret;
927 size_t len;
928 int what = EVBUFFER_READ;
929 int howmuch = IBUF_READ_SIZE;
930 char buf[IBUF_READ_SIZE];
932 if (event == EV_TIMEOUT) {
933 what |= EVBUFFER_TIMEOUT;
934 goto err;
937 if (bufev->wm_read.high != 0)
938 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
940 switch (ret = tls_read(client->ctx, buf, howmuch)) {
941 case TLS_WANT_POLLIN:
942 case TLS_WANT_POLLOUT:
943 goto retry;
944 case -1:
945 what |= EVBUFFER_ERROR;
946 goto err;
948 len = ret;
950 if (len == 0) {
951 what |= EVBUFFER_EOF;
952 goto err;
955 if (evbuffer_add(bufev->input, buf, len) == -1) {
956 what |= EVBUFFER_ERROR;
957 goto err;
960 event_add(&bufev->ev_read, NULL);
961 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
962 return;
963 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
964 /*
965 * here we could implement a read pressure policy.
966 */
969 if (bufev->readcb != NULL)
970 (*bufev->readcb)(bufev, bufev->cbarg);
972 return;
974 retry:
975 event_add(&bufev->ev_read, NULL);
976 return;
978 err:
979 (*bufev->errorcb)(bufev, what, bufev->cbarg);
982 static void
983 client_tls_writecb(int fd, short event, void *d)
985 struct bufferevent *bufev = d;
986 struct client *client = bufev->cbarg;
987 ssize_t ret;
988 size_t len;
989 short what = EVBUFFER_WRITE;
991 if (event == EV_TIMEOUT) {
992 what |= EVBUFFER_TIMEOUT;
993 goto err;
996 if (EVBUFFER_LENGTH(bufev->output) != 0) {
997 ret = tls_write(client->ctx,
998 EVBUFFER_DATA(bufev->output),
999 EVBUFFER_LENGTH(bufev->output));
1000 switch (ret) {
1001 case TLS_WANT_POLLIN:
1002 case TLS_WANT_POLLOUT:
1003 goto retry;
1004 case -1:
1005 what |= EVBUFFER_ERROR;
1006 goto err;
1008 len = ret;
1009 evbuffer_drain(bufev->output, len);
1012 if (EVBUFFER_LENGTH(bufev->output) != 0)
1013 event_add(&bufev->ev_write, NULL);
1015 if (bufev->writecb != NULL &&
1016 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
1017 (*bufev->writecb)(bufev, bufev->cbarg);
1018 return;
1020 retry:
1021 event_add(&bufev->ev_write, NULL);
1022 return;
1023 err:
1024 log_warnx("tls error: %s", tls_error(client->ctx));
1025 (*bufev->errorcb)(bufev, what, bufev->cbarg);
1028 static void
1029 client_read(struct bufferevent *bev, void *d)
1031 struct client *c = d;
1032 struct evbuffer *src = EVBUFFER_INPUT(bev);
1033 const char *parse_err = "invalid request";
1034 char decoded[DOMAIN_NAME_LEN];
1036 bufferevent_disable(bev, EVBUFFER_READ);
1039 * libevent2 can still somehow call this function, even
1040 * though I never enable EV_READ in the bufferevent. If
1041 * that's the case, bail out.
1043 if (c->type != REQUEST_UNDECIDED)
1044 return;
1046 /* max url len + \r\n */
1047 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1048 log_debug("too much data received");
1049 start_reply(c, BAD_REQUEST, "bad request");
1050 return;
1053 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
1054 if (c->req == NULL) {
1055 /* not enough data yet. */
1056 bufferevent_enable(bev, EVBUFFER_READ);
1057 return;
1059 if (c->reqlen > 1024+2) {
1060 log_debug("URL too long");
1061 start_reply(c, BAD_REQUEST, "bad request");
1062 return;
1065 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1066 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1067 log_debug("IRI parse error: %s", parse_err);
1068 start_reply(c, BAD_REQUEST, "bad request");
1069 return;
1072 if (apply_reverse_proxy(c))
1073 return;
1075 /* ignore the port number */
1076 if (strcmp(c->iri.schema, "gemini") ||
1077 strcmp(decoded, c->domain)) {
1078 start_reply(c, PROXY_REFUSED, "won't proxy request");
1079 return;
1082 if (apply_require_ca(c) ||
1083 apply_block_return(c)||
1084 apply_fastcgi(c))
1085 return;
1087 open_file(c);
1090 void
1091 client_write(struct bufferevent *bev, void *d)
1093 struct client *c = d;
1094 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1095 char nam[PATH_MAX];
1096 char buf[BUFSIZ];
1097 ssize_t r;
1099 switch (c->type) {
1100 case REQUEST_UNDECIDED:
1102 * Ignore spurious calls when we still don't have idea
1103 * what to do with the request.
1105 break;
1107 case REQUEST_FILE:
1108 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1109 log_warn("read");
1110 client_error(bev, EVBUFFER_ERROR, c);
1111 return;
1112 } else if (r == 0) {
1113 client_close(c);
1114 return;
1115 } else if (r != sizeof(buf))
1116 c->type = REQUEST_DONE;
1117 bufferevent_write(bev, buf, r);
1118 break;
1120 case REQUEST_DIR:
1121 /* TODO: handle big big directories better */
1122 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1123 const char *sufx = "";
1125 encode_path(nam, sizeof(nam),
1126 c->dir[c->diroff]->d_name);
1127 if (c->dir[c->diroff]->d_type == DT_DIR)
1128 sufx = "/";
1129 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1130 free(c->dir[c->diroff]);
1132 free(c->dir);
1133 c->dir = NULL;
1135 c->type = REQUEST_DONE;
1137 event_add(&c->bev->ev_write, NULL);
1138 break;
1140 case REQUEST_FCGI:
1141 case REQUEST_PROXY:
1143 * Here we depend on fastcgi or proxy connection to
1144 * provide data.
1146 break;
1148 case REQUEST_DONE:
1149 if (EVBUFFER_LENGTH(out) == 0)
1150 client_close(c);
1151 break;
1155 static void
1156 client_error(struct bufferevent *bev, short error, void *d)
1158 struct client *c = d;
1160 c->type = REQUEST_DONE;
1162 if (error & EVBUFFER_TIMEOUT) {
1163 log_debug("timeout; forcefully closing the connection");
1164 if (c->code == 0)
1165 start_reply(c, BAD_REQUEST, "timeout");
1166 else
1167 client_close(c);
1168 return;
1171 if (error & EVBUFFER_EOF) {
1172 client_close(c);
1173 return;
1176 log_warnx("unknown bufferevent error 0x%x", error);
1177 client_close(c);
1180 void
1181 start_reply(struct client *c, int code, const char *meta)
1183 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1184 const char *lang;
1185 int r, rr;
1187 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1189 c->code = code;
1190 c->meta = meta;
1192 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1193 if (r == -1)
1194 goto err;
1196 /* 2 digit status + space + 1024 max reply */
1197 if (r > 1027)
1198 goto overflow;
1200 if (c->type != REQUEST_FCGI &&
1201 c->type != REQUEST_PROXY &&
1202 !strcmp(meta, "text/gemini") &&
1203 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1204 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1205 if (rr == -1)
1206 goto err;
1207 if (r + rr > 1027)
1208 goto overflow;
1211 bufferevent_write(c->bev, "\r\n", 2);
1213 if (!vhost_disable_log(c->host, c->iri.path))
1214 log_request(c, (char *)EVBUFFER_DATA(evb),
1215 EVBUFFER_LENGTH(evb));
1217 if (code != 20)
1218 c->type = REQUEST_DONE;
1220 return;
1222 err:
1223 log_warnx("evbuffer_add_printf error: no memory");
1224 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1225 client_close(c);
1226 return;
1228 overflow:
1229 log_warnx("reply header overflow");
1230 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1231 start_reply(c, TEMP_FAILURE, "internal error");
1234 static void
1235 client_close_ev(int fd, short event, void *d)
1237 struct client *c = d;
1239 switch (tls_close(c->ctx)) {
1240 case TLS_WANT_POLLIN:
1241 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1242 return;
1243 case TLS_WANT_POLLOUT:
1244 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1245 return;
1248 connected_clients--;
1250 free(c->req);
1252 tls_free(c->ctx);
1253 c->ctx = NULL;
1255 free(c->header);
1257 if (c->pfd != -1)
1258 close(c->pfd);
1260 if (c->dir != NULL)
1261 free(c->dir);
1263 close(c->fd);
1264 c->fd = -1;
1266 free(c);
1269 static void
1270 client_proxy_close(int fd, short event, void *d)
1272 struct tls *ctx = d;
1274 if (ctx == NULL) {
1275 close(fd);
1276 return;
1279 switch (tls_close(ctx)) {
1280 case TLS_WANT_POLLIN:
1281 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1282 break;
1283 case TLS_WANT_POLLOUT:
1284 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1285 break;
1288 tls_free(ctx);
1289 close(fd);
1292 void
1293 client_close(struct client *c)
1296 * We may end up calling client_close in various situations
1297 * and for the most unexpected reasons. Therefore, we need to
1298 * ensure that everything gets properly released once we reach
1299 * this point.
1302 SPLAY_REMOVE(client_tree_id, &clients, c);
1304 if (c->cgibev != NULL) {
1305 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1306 bufferevent_free(c->cgibev);
1307 c->cgibev = NULL;
1308 close(c->pfd);
1309 c->pfd = -1;
1312 if (c->bev != NULL) {
1313 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1314 bufferevent_free(c->bev);
1317 if (c->proxyevset &&
1318 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1319 c->proxyevset = 0;
1320 event_del(&c->proxyev);
1323 if (c->pfd != -1 && c->proxyctx != NULL) {
1324 /* shut down the proxy TLS connection */
1325 client_proxy_close(c->pfd, 0, c->proxyctx);
1326 c->pfd = -1;
1329 if (c->proxybev != NULL)
1330 bufferevent_free(c->proxybev);
1332 client_close_ev(c->fd, 0, c);
1335 void
1336 do_accept(int sock, short et, void *d)
1338 struct address *addr = d;
1339 struct client *c;
1340 struct sockaddr_storage raddr;
1341 struct sockaddr *sraddr;
1342 socklen_t len;
1343 int e, fd;
1345 sraddr = (struct sockaddr *)&raddr;
1346 len = sizeof(raddr);
1347 if ((fd = accept(sock, sraddr, &len)) == -1) {
1348 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1349 errno == ECONNABORTED)
1350 return;
1351 fatal("accept");
1354 mark_nonblock(fd);
1356 c = xcalloc(1, sizeof(*c));
1357 c->conf = addr->conf;
1358 c->addr = addr;
1359 c->id = ++server_client_id;
1360 c->fd = fd;
1361 c->pfd = -1;
1362 memcpy(&c->raddr, &raddr, sizeof(raddr));
1363 c->raddrlen = len;
1365 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1366 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1367 if (e != 0) {
1368 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1369 close(c->fd);
1370 free(c);
1371 return;
1374 if (tls_accept_socket(addr->ctx, &c->ctx, fd) == -1) {
1375 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1376 close(c->fd);
1377 free(c);
1378 return;
1381 SPLAY_INSERT(client_tree_id, &clients, c);
1382 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1383 connected_clients++;
1386 struct client *
1387 client_by_id(int id)
1389 struct client find;
1391 find.id = id;
1392 return SPLAY_FIND(client_tree_id, &clients, &find);
1395 static void
1396 handle_siginfo(int fd, short ev, void *d)
1398 log_info("%d connected clients", connected_clients);
1401 static void
1402 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1403 struct conf *conf)
1405 struct address *vaddr;
1406 struct vhost *h;
1407 int r, any = 0;
1409 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1410 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1411 if (!match_addr(addr, vaddr))
1412 continue;
1414 if (!any) {
1415 any = 1;
1416 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1417 h->cert, h->certlen, h->key, h->keylen,
1418 h->ocsp, h->ocsplen);
1419 } else {
1420 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1421 h->cert, h->certlen, h->key, h->keylen,
1422 h->ocsp, h->ocsplen);
1425 if (r == -1)
1426 fatalx("failed to load keypair"
1427 " for host %s: %s", h->domain,
1428 tls_config_error(tlsconf));
1433 static void
1434 setup_tls(struct conf *conf)
1436 struct tls_config *tlsconf;
1437 struct address *addr;
1439 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1440 if ((tlsconf = tls_config_new()) == NULL)
1441 fatal("tls_config_new");
1443 if (conf->use_privsep_crypto)
1444 tls_config_use_fake_private_key(tlsconf);
1446 /* optionally accept client certs but don't verify */
1447 tls_config_verify_client_optional(tlsconf);
1448 tls_config_insecure_noverifycert(tlsconf);
1450 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1451 fatalx("tls_config_set_protocols: %s",
1452 tls_config_error(tlsconf));
1454 add_matching_kps(tlsconf, addr, conf);
1456 tls_reset(addr->ctx);
1457 if (tls_configure(addr->ctx, tlsconf) == -1)
1458 fatalx("tls_configure: %s", tls_error(addr->ctx));
1460 tls_config_free(tlsconf);
1464 static void
1465 load_vhosts(struct conf *conf)
1467 struct vhost *h;
1468 struct location *l;
1470 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1471 TAILQ_FOREACH(l, &h->locations, locations) {
1472 if (*l->dir == '\0')
1473 continue;
1474 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1475 if (l->dirfd == -1)
1476 fatal("open %s for domain %s", l->dir,
1477 h->domain);
1482 void
1483 server(struct privsep *ps, struct privsep_proc *p)
1485 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1488 void
1489 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1491 struct conf *c;
1493 SPLAY_INIT(&clients);
1495 #ifdef SIGINFO
1496 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1497 signal_add(&siginfo, NULL);
1498 #endif
1499 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1500 signal_add(&sigusr2, NULL);
1502 sandbox_server_process();
1505 * ge doesn't use the privsep crypto engine; it doesn't use
1506 * privsep at all so `ps' is NULL.
1508 if (ps != NULL) {
1509 c = ps->ps_env;
1510 if (c->use_privsep_crypto)
1511 crypto_engine_init(ps->ps_env);
1515 int
1516 server_configure_done(struct conf *conf)
1518 struct address *addr;
1520 if (load_default_mime(&conf->mime) == -1)
1521 fatal("can't load default mime");
1522 sort_mime(&conf->mime);
1523 setup_tls(conf);
1524 load_vhosts(conf);
1526 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1527 if (addr->sock != -1)
1528 event_add(&addr->evsock, NULL);
1531 return 0;
1534 static int
1535 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1537 struct privsep *ps = p->p_ps;
1538 struct conf *conf = ps->ps_env;
1540 switch (imsg->hdr.type) {
1541 case IMSG_RECONF_START:
1542 case IMSG_RECONF_MIME:
1543 case IMSG_RECONF_PROTOS:
1544 case IMSG_RECONF_SOCK:
1545 case IMSG_RECONF_FCGI:
1546 case IMSG_RECONF_HOST:
1547 case IMSG_RECONF_CERT:
1548 case IMSG_RECONF_KEY:
1549 case IMSG_RECONF_OCSP:
1550 case IMSG_RECONF_HOST_ADDR:
1551 case IMSG_RECONF_LOC:
1552 case IMSG_RECONF_ENV:
1553 case IMSG_RECONF_ALIAS:
1554 case IMSG_RECONF_PROXY:
1555 case IMSG_RECONF_PROXY_CERT:
1556 case IMSG_RECONF_PROXY_KEY:
1557 return config_recv(conf, imsg);
1558 case IMSG_RECONF_END:
1559 if (config_recv(conf, imsg) == -1)
1560 return -1;
1561 if (server_configure_done(conf) == -1)
1562 return -1;
1563 break;
1564 default:
1565 return -1;
1568 return 0;
1571 static int
1572 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1574 return -1;
1577 static int
1578 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1580 return -1;
1583 int
1584 client_tree_cmp(struct client *a, struct client *b)
1586 if (a->id == b->id)
1587 return 0;
1588 else if (a->id < b->id)
1589 return -1;
1590 else
1591 return +1;
1594 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)