Blob


1 /*
2 * Copyright (c) 2021, 2022 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 int shutting_down;
42 static struct tls *ctx;
44 static struct event siginfo, sigusr2;
45 static int has_siginfo;
47 int connected_clients;
49 /*
50 * This function is not publicy exported because it is a hack until libtls
51 * has a proper privsep setup.
52 */
53 void tls_config_use_fake_private_key(struct tls_config *);
55 static inline int matches(const char*, const char*);
57 static int check_path(struct client*, const char*, int*);
58 static void open_file(struct client*);
59 static void handle_handshake(int, short, void*);
60 static const char *strip_path(const char*, int);
61 static void fmt_sbuf(const char*, struct client*, const char*);
62 static int apply_block_return(struct client*);
63 static int check_matching_certificate(X509_STORE *, struct client *);
64 static int apply_reverse_proxy(struct client *);
65 static int apply_fastcgi(struct client*);
66 static int apply_require_ca(struct client*);
67 static void open_dir(struct client*);
68 static void redirect_canonical_dir(struct client*);
70 static void client_tls_readcb(int, short, void *);
71 static void client_tls_writecb(int, short, void *);
73 static void client_read(struct bufferevent *, void *);
74 void client_write(struct bufferevent *, void *);
75 static void client_error(struct bufferevent *, short, void *);
77 static void client_close_ev(int, short, void *);
79 static void handle_siginfo(int, short, void*);
81 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
82 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
83 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
85 static struct privsep_proc procs[] = {
86 { "parent", PROC_PARENT, server_dispatch_parent },
87 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
88 { "logger", PROC_LOGGER, server_dispatch_logger },
89 };
91 static uint32_t server_client_id;
93 struct client_tree_id clients;
95 static inline int
96 matches(const char *pattern, const char *path)
97 {
98 if (*path == '/')
99 path++;
100 return !fnmatch(pattern, path, 0);
103 const char *
104 vhost_lang(struct vhost *v, const char *path)
106 struct location *loc;
108 if (v == NULL || path == NULL)
109 return NULL;
111 loc = TAILQ_FIRST(&v->locations);
112 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
113 if (*loc->lang != '\0') {
114 if (matches(loc->match, path))
115 return loc->lang;
119 loc = TAILQ_FIRST(&v->locations);
120 if (*loc->lang == '\0')
121 return NULL;
122 return loc->lang;
125 const char *
126 vhost_default_mime(struct vhost *v, const char *path)
128 struct location *loc;
129 const char *default_mime = "application/octet-stream";
131 if (v == NULL || path == NULL)
132 return default_mime;
134 loc = TAILQ_FIRST(&v->locations);
135 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
136 if (*loc->default_mime != '\0') {
137 if (matches(loc->match, path))
138 return loc->default_mime;
142 loc = TAILQ_FIRST(&v->locations);
143 if (*loc->default_mime != '\0')
144 return loc->default_mime;
145 return default_mime;
148 const char *
149 vhost_index(struct vhost *v, const char *path)
151 struct location *loc;
152 const char *index = "index.gmi";
154 if (v == NULL || path == NULL)
155 return index;
157 loc = TAILQ_FIRST(&v->locations);
158 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
159 if (*loc->index != '\0') {
160 if (matches(loc->match, path))
161 return loc->index;
165 loc = TAILQ_FIRST(&v->locations);
166 if (*loc->index != '\0')
167 return loc->index;
168 return index;
171 int
172 vhost_auto_index(struct vhost *v, const char *path)
174 struct location *loc;
176 if (v == NULL || path == NULL)
177 return 0;
179 loc = TAILQ_FIRST(&v->locations);
180 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
181 if (loc->auto_index != 0) {
182 if (matches(loc->match, path))
183 return loc->auto_index == 1;
187 loc = TAILQ_FIRST(&v->locations);
188 return loc->auto_index == 1;
191 int
192 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
194 struct location *loc;
196 if (v == NULL || path == NULL)
197 return 0;
199 loc = TAILQ_FIRST(&v->locations);
200 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
201 if (loc->block_code != 0) {
202 if (matches(loc->match, path)) {
203 *code = loc->block_code;
204 *fmt = loc->block_fmt;
205 return 1;
210 loc = TAILQ_FIRST(&v->locations);
211 *code = loc->block_code;
212 *fmt = loc->block_fmt;
213 return loc->block_code != 0;
216 int
217 vhost_fastcgi(struct vhost *v, const char *path)
219 struct location *loc;
221 if (v == NULL || path == NULL)
222 return -1;
224 loc = TAILQ_FIRST(&v->locations);
225 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
226 if (loc->fcgi != -1)
227 if (matches(loc->match, path))
228 return loc->fcgi;
231 loc = TAILQ_FIRST(&v->locations);
232 return loc->fcgi;
235 int
236 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
238 struct location *loc;
239 size_t l = 0;
241 if (v == NULL || path == NULL)
242 return -1;
244 loc = TAILQ_FIRST(&v->locations);
245 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
246 l++;
247 if (loc->dirfd != -1)
248 if (matches(loc->match, path)) {
249 *retloc = l;
250 return loc->dirfd;
254 *retloc = 0;
255 loc = TAILQ_FIRST(&v->locations);
256 return loc->dirfd;
259 int
260 vhost_strip(struct vhost *v, const char *path)
262 struct location *loc;
264 if (v == NULL || path == NULL)
265 return 0;
267 loc = TAILQ_FIRST(&v->locations);
268 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
269 if (loc->strip != 0) {
270 if (matches(loc->match, path))
271 return loc->strip;
275 loc = TAILQ_FIRST(&v->locations);
276 return loc->strip;
279 X509_STORE *
280 vhost_require_ca(struct vhost *v, const char *path)
282 struct location *loc;
284 if (v == NULL || path == NULL)
285 return NULL;
287 loc = TAILQ_FIRST(&v->locations);
288 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
289 if (loc->reqca != NULL) {
290 if (matches(loc->match, path))
291 return loc->reqca;
295 loc = TAILQ_FIRST(&v->locations);
296 return loc->reqca;
299 int
300 vhost_disable_log(struct vhost *v, const char *path)
302 struct location *loc;
304 if (v == NULL || path == NULL)
305 return 0;
307 loc = TAILQ_FIRST(&v->locations);
308 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
309 if (loc->disable_log && matches(loc->match, path))
310 return 1;
313 loc = TAILQ_FIRST(&v->locations);
314 return loc->disable_log;
317 static int
318 check_path(struct client *c, const char *path, int *fd)
320 struct stat sb;
321 const char *p;
322 int dirfd, strip;
324 assert(path != NULL);
326 /*
327 * in send_dir we add an initial / (to be redirect-friendly),
328 * but here we want to skip it
329 */
330 if (*path == '/')
331 path++;
333 strip = vhost_strip(c->host, path);
334 p = strip_path(path, strip);
336 if (*p == '/')
337 p = p+1;
338 if (*p == '\0')
339 p = ".";
341 dirfd = vhost_dirfd(c->host, path, &c->loc);
342 log_debug("check_path: strip=%d path=%s original=%s",
343 strip, p, path);
344 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
345 if (errno == EACCES)
346 log_info("can't open %s: %s", p, strerror(errno));
347 return FILE_MISSING;
350 if (fstat(*fd, &sb) == -1) {
351 log_warn("fstat %s", path);
352 return FILE_MISSING;
355 if (S_ISDIR(sb.st_mode))
356 return FILE_DIRECTORY;
358 return FILE_EXISTS;
361 static void
362 open_file(struct client *c)
364 switch (check_path(c, c->iri.path, &c->pfd)) {
365 case FILE_EXISTS:
366 c->type = REQUEST_FILE;
367 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
368 return;
370 case FILE_DIRECTORY:
371 open_dir(c);
372 return;
374 case FILE_MISSING:
375 start_reply(c, NOT_FOUND, "not found");
376 return;
378 default:
379 /* unreachable */
380 abort();
384 void
385 mark_nonblock(int fd)
387 int flags;
389 if ((flags = fcntl(fd, F_GETFL)) == -1)
390 fatal("fcntl(F_GETFL)");
391 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
392 fatal("fcntl(F_SETFL)");
395 static void
396 handle_handshake(int fd, short ev, void *d)
398 struct client *c = d;
399 struct conf *conf = c->conf;
400 struct vhost *h;
401 struct alist *a;
402 const char *servname;
403 const char *parse_err = "unknown error";
405 switch (tls_handshake(c->ctx)) {
406 case 0: /* success */
407 case -1: /* already handshaked */
408 break;
409 case TLS_WANT_POLLIN:
410 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
411 return;
412 case TLS_WANT_POLLOUT:
413 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
414 return;
415 default:
416 /* unreachable */
417 abort();
420 c->bev = bufferevent_new(fd, client_read, client_write,
421 client_error, c);
422 if (c->bev == NULL)
423 fatal("%s: failed to allocate client buffer", __func__);
425 event_set(&c->bev->ev_read, c->fd, EV_READ,
426 client_tls_readcb, c->bev);
427 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
428 client_tls_writecb, c->bev);
430 #if HAVE_LIBEVENT2
431 evbuffer_unfreeze(c->bev->input, 0);
432 evbuffer_unfreeze(c->bev->output, 1);
433 #endif
435 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
436 log_debug("handshake: missing SNI");
437 goto err;
440 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
441 log_info("puny_decode: %s", parse_err);
442 goto err;
445 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
446 if (matches(h->domain, c->domain))
447 goto found;
448 TAILQ_FOREACH(a, &h->aliases, aliases) {
449 if (matches(a->alias, c->domain))
450 goto found;
454 found:
455 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
456 servname != NULL ? servname : "(null)",
457 c->domain,
458 h != NULL ? h->domain : "(null)");
460 if (h != NULL) {
461 c->host = h;
462 bufferevent_enable(c->bev, EV_READ);
463 return;
466 err:
467 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
470 static const char *
471 strip_path(const char *path, int strip)
473 char *t;
475 while (strip > 0) {
476 if ((t = strchr(path, '/')) == NULL) {
477 path = strchr(path, '\0');
478 break;
480 path = t;
481 strip--;
484 return path;
487 static void
488 fmt_sbuf(const char *fmt, struct client *c, const char *path)
490 struct conf *conf = c->conf;
491 size_t i;
492 char buf[32];
494 memset(buf, 0, sizeof(buf));
495 for (i = 0; *fmt; ++fmt) {
496 if (i == sizeof(buf)-1 || *fmt == '%') {
497 strlcat(c->sbuf, buf, sizeof(c->sbuf));
498 memset(buf, 0, sizeof(buf));
499 i = 0;
502 if (*fmt != '%') {
503 buf[i++] = *fmt;
504 continue;
507 switch (*++fmt) {
508 case '%':
509 strlcat(c->sbuf, "%", sizeof(c->sbuf));
510 break;
511 case 'p':
512 if (*path != '/')
513 strlcat(c->sbuf, "/", sizeof(c->sbuf));
514 strlcat(c->sbuf, path, sizeof(c->sbuf));
515 break;
516 case 'q':
517 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
518 break;
519 case 'P':
520 snprintf(buf, sizeof(buf), "%d", conf->port);
521 strlcat(c->sbuf, buf, sizeof(c->sbuf));
522 memset(buf, 0, sizeof(buf));
523 break;
524 case 'N':
525 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
526 break;
527 default:
528 fatalx("%s: unknown fmt specifier %c",
529 __func__, *fmt);
533 if (i != 0)
534 strlcat(c->sbuf, buf, sizeof(c->sbuf));
537 /* 1 if a matching `block return' (and apply it), 0 otherwise */
538 static int
539 apply_block_return(struct client *c)
541 const char *fmt, *path;
542 int code;
544 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
545 return 0;
547 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
548 fmt_sbuf(fmt, c, path);
550 start_reply(c, code, c->sbuf);
551 return 1;
554 static struct proxy *
555 matched_proxy(struct client *c)
557 struct proxy *p;
558 const char *proto;
559 const char *host;
560 const char *port;
562 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
563 if (*(proto = p->match_proto) == '\0')
564 proto = "gemini";
565 if (*(host = p->match_host) == '\0')
566 host = "*";
567 if (*(port = p->match_port) == '\0')
568 port = "*";
570 if (matches(proto, c->iri.schema) &&
571 matches(host, c->domain) &&
572 matches(port, c->iri.port))
573 return p;
576 return NULL;
579 static int
580 check_matching_certificate(X509_STORE *store, struct client *c)
582 const uint8_t *cert;
583 size_t len;
585 if (!tls_peer_cert_provided(c->ctx)) {
586 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
587 return 1;
590 cert = tls_peer_cert_chain_pem(c->ctx, &len);
591 if (!validate_against_ca(store, cert, len)) {
592 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
593 return 1;
596 return 0;
599 static int
600 proxy_socket(struct client *c, const char *host, const char *port)
602 struct addrinfo hints, *res, *res0;
603 int r, sock, save_errno;
604 const char *cause = NULL;
606 memset(&hints, 0, sizeof(hints));
607 hints.ai_family = AF_UNSPEC;
608 hints.ai_socktype = SOCK_STREAM;
610 /* XXX: asr_run? :> */
611 r = getaddrinfo(host, port, &hints, &res0);
612 if (r != 0) {
613 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
614 host, port, gai_strerror(r));
615 return -1;
618 for (res = res0; res; res = res->ai_next) {
619 sock = socket(res->ai_family, res->ai_socktype,
620 res->ai_protocol);
621 if (sock == -1) {
622 cause = "socket";
623 continue;
626 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
627 cause = "connect";
628 save_errno = errno;
629 close(sock);
630 errno = save_errno;
631 sock = -1;
632 continue;
635 break;
638 if (sock == -1)
639 log_warn("can't connect to %s:%s: %s", host, port, cause);
641 freeaddrinfo(res0);
643 return sock;
646 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
647 static int
648 apply_reverse_proxy(struct client *c)
650 struct proxy *p;
652 if ((p = matched_proxy(c)) == NULL)
653 return 0;
655 c->proxy = p;
657 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
658 return 1;
660 log_debug("opening proxy connection for %s:%s",
661 p->host, p->port);
663 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
664 start_reply(c, PROXY_ERROR, "proxy error");
665 return 1;
668 mark_nonblock(c->pfd);
669 if (proxy_init(c) == -1)
670 start_reply(c, PROXY_ERROR, "proxy error");
672 return 1;
675 static int
676 fcgi_open_sock(struct fcgi *f)
678 struct sockaddr_un addr;
679 int fd;
681 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
682 log_warn("socket");
683 return -1;
686 memset(&addr, 0, sizeof(addr));
687 addr.sun_family = AF_UNIX;
688 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
690 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
691 log_warn("failed to connect to %s", f->path);
692 close(fd);
693 return -1;
696 return fd;
699 static int
700 fcgi_open_conn(struct fcgi *f)
702 struct addrinfo hints, *servinfo, *p;
703 int r, sock, save_errno;
704 const char *cause = NULL;
706 memset(&hints, 0, sizeof(hints));
707 hints.ai_family = AF_UNSPEC;
708 hints.ai_socktype = SOCK_STREAM;
709 hints.ai_flags = AI_ADDRCONFIG;
711 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
712 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
713 gai_strerror(r));
714 return -1;
717 for (p = servinfo; p != NULL; p = p->ai_next) {
718 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
719 if (sock == -1) {
720 cause = "socket";
721 continue;
723 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
724 cause = "connect";
725 save_errno = errno;
726 close(sock);
727 errno = save_errno;
728 continue;
730 break;
733 if (p == NULL) {
734 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
735 cause);
736 sock = -1;
739 freeaddrinfo(servinfo);
740 return sock;
743 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
744 static int
745 apply_fastcgi(struct client *c)
747 int id, i = 0;
748 struct fcgi *f;
750 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
751 return 0;
753 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
754 if (i == id)
755 break;
756 ++i;
759 if (f == NULL) {
760 log_warnx("can't find fcgi #%d", id);
761 return 0;
764 log_debug("opening fastcgi connection for (%s,%s)",
765 f->path, f->port);
767 if (*f->port == '\0')
768 c->pfd = fcgi_open_sock(f);
769 else
770 c->pfd = fcgi_open_conn(f);
772 if (c->pfd == -1) {
773 start_reply(c, CGI_ERROR, "CGI error");
774 return 1;
777 mark_nonblock(c->pfd);
779 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
780 fcgi_error, c);
781 if (c->cgibev == NULL) {
782 start_reply(c, TEMP_FAILURE, "internal server error");
783 return 1;
786 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
787 fcgi_req(c);
789 return 1;
792 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
793 static int
794 apply_require_ca(struct client *c)
796 X509_STORE *store;
798 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
799 return 0;
800 return check_matching_certificate(store, c);
803 static void
804 open_dir(struct client *c)
806 size_t len;
807 int dirfd, root;
808 char *before_file;
810 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
812 len = strlen(c->iri.path);
813 if (len > 0 && !ends_with(c->iri.path, "/")) {
814 redirect_canonical_dir(c);
815 return;
818 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
819 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
820 if (!ends_with(c->sbuf, "/"))
821 strlcat(c->sbuf, "/", sizeof(c->sbuf));
822 before_file = strchr(c->sbuf, '\0');
823 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
824 sizeof(c->sbuf));
825 if (len >= sizeof(c->sbuf)) {
826 start_reply(c, TEMP_FAILURE, "internal server error");
827 return;
830 c->iri.path = c->sbuf;
832 /* close later unless we have to generate the dir listing */
833 dirfd = c->pfd;
834 c->pfd = -1;
836 switch (check_path(c, c->iri.path, &c->pfd)) {
837 case FILE_EXISTS:
838 c->type = REQUEST_FILE;
839 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
840 break;
842 case FILE_DIRECTORY:
843 start_reply(c, TEMP_REDIRECT, c->sbuf);
844 break;
846 case FILE_MISSING:
847 *before_file = '\0';
849 if (!vhost_auto_index(c->host, c->iri.path)) {
850 start_reply(c, NOT_FOUND, "not found");
851 break;
854 c->type = REQUEST_DIR;
856 c->dirlen = scandir_fd(dirfd, &c->dir,
857 root ? select_non_dotdot : select_non_dot,
858 alphasort);
859 if (c->dirlen == -1) {
860 log_warn("scandir_fd(%d) (vhost:%s) %s",
861 c->pfd, c->host->domain, c->iri.path);
862 start_reply(c, TEMP_FAILURE, "internal server error");
863 return;
865 c->diroff = 0;
866 c->off = 0;
868 start_reply(c, SUCCESS, "text/gemini");
869 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
870 "# Index of %s\n\n", c->iri.path);
871 return;
873 default:
874 /* unreachable */
875 abort();
878 close(dirfd);
881 static void
882 redirect_canonical_dir(struct client *c)
884 size_t len;
886 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
887 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
888 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
890 if (len >= sizeof(c->sbuf)) {
891 start_reply(c, TEMP_FAILURE, "internal server error");
892 return;
895 start_reply(c, TEMP_REDIRECT, c->sbuf);
898 static void
899 client_tls_readcb(int fd, short event, void *d)
901 struct bufferevent *bufev = d;
902 struct client *client = bufev->cbarg;
903 ssize_t ret;
904 size_t len;
905 int what = EVBUFFER_READ;
906 int howmuch = IBUF_READ_SIZE;
907 char buf[IBUF_READ_SIZE];
909 if (event == EV_TIMEOUT) {
910 what |= EVBUFFER_TIMEOUT;
911 goto err;
914 if (bufev->wm_read.high != 0)
915 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
917 switch (ret = tls_read(client->ctx, buf, howmuch)) {
918 case TLS_WANT_POLLIN:
919 case TLS_WANT_POLLOUT:
920 goto retry;
921 case -1:
922 what |= EVBUFFER_ERROR;
923 goto err;
925 len = ret;
927 if (len == 0) {
928 what |= EVBUFFER_EOF;
929 goto err;
932 if (evbuffer_add(bufev->input, buf, len) == -1) {
933 what |= EVBUFFER_ERROR;
934 goto err;
937 event_add(&bufev->ev_read, NULL);
938 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
939 return;
940 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
941 /*
942 * here we could implement a read pressure policy.
943 */
946 if (bufev->readcb != NULL)
947 (*bufev->readcb)(bufev, bufev->cbarg);
949 return;
951 retry:
952 event_add(&bufev->ev_read, NULL);
953 return;
955 err:
956 (*bufev->errorcb)(bufev, what, bufev->cbarg);
959 static void
960 client_tls_writecb(int fd, short event, void *d)
962 struct bufferevent *bufev = d;
963 struct client *client = bufev->cbarg;
964 ssize_t ret;
965 size_t len;
966 short what = EVBUFFER_WRITE;
968 if (event == EV_TIMEOUT) {
969 what |= EVBUFFER_TIMEOUT;
970 goto err;
973 if (EVBUFFER_LENGTH(bufev->output) != 0) {
974 ret = tls_write(client->ctx,
975 EVBUFFER_DATA(bufev->output),
976 EVBUFFER_LENGTH(bufev->output));
977 switch (ret) {
978 case TLS_WANT_POLLIN:
979 case TLS_WANT_POLLOUT:
980 goto retry;
981 case -1:
982 what |= EVBUFFER_ERROR;
983 goto err;
985 len = ret;
986 evbuffer_drain(bufev->output, len);
989 if (EVBUFFER_LENGTH(bufev->output) != 0)
990 event_add(&bufev->ev_write, NULL);
992 if (bufev->writecb != NULL &&
993 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
994 (*bufev->writecb)(bufev, bufev->cbarg);
995 return;
997 retry:
998 event_add(&bufev->ev_write, NULL);
999 return;
1000 err:
1001 log_warnx("tls error: %s", tls_error(client->ctx));
1002 (*bufev->errorcb)(bufev, what, bufev->cbarg);
1005 static void
1006 client_read(struct bufferevent *bev, void *d)
1008 struct client *c = d;
1009 struct evbuffer *src = EVBUFFER_INPUT(bev);
1010 const char *parse_err = "invalid request";
1011 char decoded[DOMAIN_NAME_LEN];
1012 size_t len;
1014 bufferevent_disable(bev, EVBUFFER_READ);
1017 * libevent2 can still somehow call this function, even
1018 * though I never enable EV_READ in the bufferevent. If
1019 * that's the case, bail out.
1021 if (c->type != REQUEST_UNDECIDED)
1022 return;
1024 /* max url len + \r\n */
1025 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1026 log_debug("too much data received");
1027 start_reply(c, BAD_REQUEST, "bad request");
1028 return;
1031 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1032 if (c->req == NULL) {
1033 /* not enough data yet. */
1034 bufferevent_enable(bev, EVBUFFER_READ);
1035 return;
1037 c->reqlen = strlen(c->req);
1038 if (c->reqlen > 1024+2) {
1039 log_debug("URL too long");
1040 start_reply(c, BAD_REQUEST, "bad request");
1041 return;
1044 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1045 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1046 log_debug("IRI parse error: %s", parse_err);
1047 start_reply(c, BAD_REQUEST, "bad request");
1048 return;
1051 if (apply_reverse_proxy(c))
1052 return;
1054 /* ignore the port number */
1055 if (strcmp(c->iri.schema, "gemini") ||
1056 strcmp(decoded, c->domain)) {
1057 start_reply(c, PROXY_REFUSED, "won't proxy request");
1058 return;
1061 if (apply_require_ca(c) ||
1062 apply_block_return(c)||
1063 apply_fastcgi(c))
1064 return;
1066 open_file(c);
1069 void
1070 client_write(struct bufferevent *bev, void *d)
1072 struct client *c = d;
1073 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1074 char nam[PATH_MAX];
1075 char buf[BUFSIZ];
1076 ssize_t r;
1078 switch (c->type) {
1079 case REQUEST_UNDECIDED:
1081 * Ignore spurious calls when we still don't have idea
1082 * what to do with the request.
1084 break;
1086 case REQUEST_FILE:
1087 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1088 log_warn("read");
1089 client_error(bev, EVBUFFER_ERROR, c);
1090 return;
1091 } else if (r == 0) {
1092 client_close(c);
1093 return;
1094 } else if (r != sizeof(buf))
1095 c->type = REQUEST_DONE;
1096 bufferevent_write(bev, buf, r);
1097 break;
1099 case REQUEST_DIR:
1100 /* TODO: handle big big directories better */
1101 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1102 const char *sufx = "";
1104 encode_path(nam, sizeof(nam),
1105 c->dir[c->diroff]->d_name);
1106 if (c->dir[c->diroff]->d_type == DT_DIR)
1107 sufx = "/";
1108 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1109 free(c->dir[c->diroff]);
1111 free(c->dir);
1112 c->dir = NULL;
1114 c->type = REQUEST_DONE;
1116 event_add(&c->bev->ev_write, NULL);
1117 break;
1119 case REQUEST_FCGI:
1120 case REQUEST_PROXY:
1122 * Here we depend on fastcgi or proxy connection to
1123 * provide data.
1125 break;
1127 case REQUEST_DONE:
1128 if (EVBUFFER_LENGTH(out) == 0)
1129 client_close(c);
1130 break;
1134 static void
1135 client_error(struct bufferevent *bev, short error, void *d)
1137 struct client *c = d;
1139 c->type = REQUEST_DONE;
1141 if (error & EVBUFFER_TIMEOUT) {
1142 log_debug("timeout; forcefully closing the connection");
1143 if (c->code == 0)
1144 start_reply(c, BAD_REQUEST, "timeout");
1145 else
1146 client_close(c);
1147 return;
1150 if (error & EVBUFFER_EOF) {
1151 client_close(c);
1152 return;
1155 log_warnx("unknown bufferevent error 0x%x", error);
1156 client_close(c);
1159 void
1160 start_reply(struct client *c, int code, const char *meta)
1162 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1163 const char *lang;
1164 int r, rr;
1166 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1168 c->code = code;
1169 c->meta = meta;
1171 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1172 if (r == -1)
1173 goto err;
1175 /* 2 digit status + space + 1024 max reply */
1176 if (r > 1027)
1177 goto overflow;
1179 if (c->type != REQUEST_FCGI &&
1180 c->type != REQUEST_PROXY &&
1181 !strcmp(meta, "text/gemini") &&
1182 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1183 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1184 if (rr == -1)
1185 goto err;
1186 if (r + rr > 1027)
1187 goto overflow;
1190 bufferevent_write(c->bev, "\r\n", 2);
1192 if (!vhost_disable_log(c->host, c->iri.path))
1193 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1195 if (code != 20)
1196 c->type = REQUEST_DONE;
1198 return;
1200 err:
1201 log_warnx("evbuffer_add_printf error: no memory");
1202 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1203 client_close(c);
1204 return;
1206 overflow:
1207 log_warnx("reply header overflow");
1208 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1209 start_reply(c, TEMP_FAILURE, "internal error");
1212 static void
1213 client_close_ev(int fd, short event, void *d)
1215 struct client *c = d;
1217 switch (tls_close(c->ctx)) {
1218 case TLS_WANT_POLLIN:
1219 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1220 break;
1221 case TLS_WANT_POLLOUT:
1222 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1223 break;
1226 connected_clients--;
1228 free(c->req);
1230 tls_free(c->ctx);
1231 c->ctx = NULL;
1233 free(c->header);
1235 if (c->pfd != -1)
1236 close(c->pfd);
1238 if (c->dir != NULL)
1239 free(c->dir);
1241 close(c->fd);
1242 c->fd = -1;
1245 static void
1246 client_proxy_close(int fd, short event, void *d)
1248 struct tls *ctx = d;
1250 if (ctx == NULL) {
1251 close(fd);
1252 return;
1255 switch (tls_close(ctx)) {
1256 case TLS_WANT_POLLIN:
1257 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1258 break;
1259 case TLS_WANT_POLLOUT:
1260 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1261 break;
1264 tls_free(ctx);
1265 close(fd);
1268 void
1269 client_close(struct client *c)
1272 * We may end up calling client_close in various situations
1273 * and for the most unexpected reasons. Therefore, we need to
1274 * ensure that everything gets properly released once we reach
1275 * this point.
1278 SPLAY_REMOVE(client_tree_id, &clients, c);
1280 if (c->cgibev != NULL) {
1281 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1282 bufferevent_free(c->cgibev);
1283 c->cgibev = NULL;
1284 close(c->pfd);
1285 c->pfd = -1;
1288 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1289 bufferevent_free(c->bev);
1290 c->bev = NULL;
1292 if (c->proxyevset &&
1293 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1294 c->proxyevset = 0;
1295 event_del(&c->proxyev);
1298 if (c->pfd != -1 && c->proxyctx != NULL) {
1299 /* shut down the proxy TLS connection */
1300 client_proxy_close(c->pfd, 0, c->proxyctx);
1301 c->pfd = -1;
1304 if (c->proxybev != NULL)
1305 bufferevent_free(c->proxybev);
1307 client_close_ev(c->fd, 0, c);
1310 void
1311 do_accept(int sock, short et, void *d)
1313 struct conf *conf = d;
1314 struct client *c;
1315 struct sockaddr_storage addr;
1316 struct sockaddr *saddr;
1317 socklen_t len;
1318 int fd;
1320 saddr = (struct sockaddr*)&addr;
1321 len = sizeof(addr);
1322 if ((fd = accept(sock, saddr, &len)) == -1) {
1323 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1324 errno == ECONNABORTED)
1325 return;
1326 fatal("accept");
1329 mark_nonblock(fd);
1331 c = xcalloc(1, sizeof(*c));
1332 c->conf = conf;
1333 c->id = ++server_client_id;
1334 c->fd = fd;
1335 c->pfd = -1;
1336 c->addr = addr;
1338 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1339 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1340 close(c->fd);
1341 free(c);
1342 return;
1345 SPLAY_INSERT(client_tree_id, &clients, c);
1346 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1347 connected_clients++;
1350 struct client *
1351 client_by_id(int id)
1353 struct client find;
1355 find.id = id;
1356 return SPLAY_FIND(client_tree_id, &clients, &find);
1359 static void
1360 handle_siginfo(int fd, short ev, void *d)
1362 log_info("%d connected clients", connected_clients);
1365 static void
1366 add_keypair(struct vhost *h, struct tls_config *conf)
1368 if (h->ocsp == NULL) {
1369 if (tls_config_add_keypair_mem(conf, h->cert, h->certlen,
1370 h->key, h->keylen) == -1)
1371 fatalx("failed to load the keypair: %s",
1372 tls_config_error(conf));
1373 } else {
1374 if (tls_config_add_keypair_ocsp_mem(conf, h->cert, h->certlen,
1375 h->key, h->keylen, h->ocsp, h->ocsplen) == -1)
1376 fatalx("failed to load the keypair: %s",
1377 tls_config_error(conf));
1381 static void
1382 setup_tls(struct conf *conf)
1384 struct tls_config *tlsconf;
1385 struct vhost *h;
1387 if (ctx == NULL) {
1388 if ((ctx = tls_server()) == NULL)
1389 fatal("tls_server failure");
1392 if ((tlsconf = tls_config_new()) == NULL)
1393 fatal("tls_config_new");
1396 * ge doesn't use the privsep crypto engine; it doesn't use
1397 * privsep at all so `ps' is NULL.
1399 if (conf->ps != NULL)
1400 tls_config_use_fake_private_key(tlsconf);
1402 /* optionally accept client certs, but don't try to verify them */
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 h = TAILQ_FIRST(&conf->hosts);
1412 /* we need to set something, then we can add how many key we want */
1413 if (tls_config_set_keypair_mem(tlsconf, h->cert, h->certlen,
1414 h->key, h->keylen) == -1)
1415 fatalx("tls_config_set_keypair_mem failed: %s",
1416 tls_config_error(tlsconf));
1418 /* same for OCSP */
1419 if (h->ocsp != NULL &&
1420 tls_config_set_ocsp_staple_mem(tlsconf, h->ocsp, h->ocsplen)
1421 == -1)
1422 fatalx("tls_config_set_ocsp_staple_file failed: %s",
1423 tls_config_error(tlsconf));
1425 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1426 add_keypair(h, tlsconf);
1428 tls_reset(ctx);
1429 if (tls_configure(ctx, tlsconf) == -1)
1430 fatalx("tls_configure: %s", tls_error(ctx));
1432 tls_config_free(tlsconf);
1435 static void
1436 load_vhosts(struct conf *conf)
1438 struct vhost *h;
1439 struct location *l;
1441 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1442 TAILQ_FOREACH(l, &h->locations, locations) {
1443 if (*l->dir == '\0')
1444 continue;
1445 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1446 if (l->dirfd == -1)
1447 fatal("open %s for domain %s", l->dir,
1448 h->domain);
1453 void
1454 server(struct privsep *ps, struct privsep_proc *p)
1456 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1459 void
1460 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1462 SPLAY_INIT(&clients);
1464 #ifdef SIGINFO
1465 has_siginfo = 1;
1466 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1467 signal_add(&siginfo, NULL);
1468 #endif
1469 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1470 signal_add(&sigusr2, NULL);
1472 sandbox_server_process();
1475 * ge doesn't use the privsep crypto engine; it doesn't use
1476 * privsep at all so `ps' is NULL.
1478 if (ps != NULL)
1479 crypto_engine_init(ps->ps_env);
1482 int
1483 server_configure_done(struct conf *conf)
1485 if (load_default_mime(&conf->mime) == -1)
1486 fatal("can't load default mime");
1487 sort_mime(&conf->mime);
1488 setup_tls(conf);
1489 load_vhosts(conf);
1490 if (conf->sock4 != -1)
1491 event_add(&conf->evsock4, NULL);
1492 if (conf->sock6 != -1)
1493 event_add(&conf->evsock6, NULL);
1495 return 0;
1498 static int
1499 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1501 struct privsep *ps = p->p_ps;
1502 struct conf *conf = ps->ps_env;
1504 switch (imsg->hdr.type) {
1505 case IMSG_RECONF_START:
1506 case IMSG_RECONF_MIME:
1507 case IMSG_RECONF_PROTOS:
1508 case IMSG_RECONF_PORT:
1509 case IMSG_RECONF_SOCK4:
1510 case IMSG_RECONF_SOCK6:
1511 case IMSG_RECONF_FCGI:
1512 case IMSG_RECONF_HOST:
1513 case IMSG_RECONF_CERT:
1514 case IMSG_RECONF_KEY:
1515 case IMSG_RECONF_OCSP:
1516 case IMSG_RECONF_LOC:
1517 case IMSG_RECONF_ENV:
1518 case IMSG_RECONF_ALIAS:
1519 case IMSG_RECONF_PROXY:
1520 case IMSG_RECONF_PROXY_CERT:
1521 case IMSG_RECONF_PROXY_KEY:
1522 return config_recv(conf, imsg);
1523 case IMSG_RECONF_END:
1524 if (config_recv(conf, imsg) == -1)
1525 return -1;
1526 if (server_configure_done(conf) == -1)
1527 return -1;
1528 break;
1529 default:
1530 return -1;
1533 return 0;
1536 static int
1537 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1539 return -1;
1542 static int
1543 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1545 return -1;
1548 int
1549 client_tree_cmp(struct client *a, struct client *b)
1551 if (a->id == b->id)
1552 return 0;
1553 else if (a->id < b->id)
1554 return -1;
1555 else
1556 return +1;
1559 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)