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 #ifdef SIGINFO
45 static struct event siginfo;
46 #endif
47 static struct event sigusr2;
49 int connected_clients;
51 /*
52 * This function is not publicy exported because it is a hack until libtls
53 * has a proper privsep setup.
54 */
55 void tls_config_use_fake_private_key(struct tls_config *);
57 static inline int matches(const char*, const char*);
59 static int check_path(struct client*, const char*, int*);
60 static void open_file(struct client*);
61 static void handle_handshake(int, short, void*);
62 static const char *strip_path(const char*, int);
63 static void fmt_sbuf(const char*, struct client*, const char*);
64 static int apply_block_return(struct client*);
65 static int check_matching_certificate(X509_STORE *, struct client *);
66 static int apply_reverse_proxy(struct client *);
67 static int apply_fastcgi(struct client*);
68 static int apply_require_ca(struct client*);
69 static void open_dir(struct client*);
70 static void redirect_canonical_dir(struct client*);
72 static void client_tls_readcb(int, short, void *);
73 static void client_tls_writecb(int, short, void *);
75 static void client_read(struct bufferevent *, void *);
76 void client_write(struct bufferevent *, void *);
77 static void client_error(struct bufferevent *, short, void *);
79 static void client_close_ev(int, short, void *);
81 static void handle_siginfo(int, short, void*);
83 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
84 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
85 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
87 static struct privsep_proc procs[] = {
88 { "parent", PROC_PARENT, server_dispatch_parent },
89 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
90 { "logger", PROC_LOGGER, server_dispatch_logger },
91 };
93 static uint32_t server_client_id;
95 struct client_tree_id clients;
97 static inline int
98 matches(const char *pattern, const char *path)
99 {
100 if (*path == '/')
101 path++;
102 return !fnmatch(pattern, path, 0);
105 const char *
106 vhost_lang(struct vhost *v, const char *path)
108 struct location *loc;
110 if (v == NULL || path == NULL)
111 return NULL;
113 loc = TAILQ_FIRST(&v->locations);
114 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
115 if (*loc->lang != '\0') {
116 if (matches(loc->match, path))
117 return loc->lang;
121 loc = TAILQ_FIRST(&v->locations);
122 if (*loc->lang == '\0')
123 return NULL;
124 return loc->lang;
127 const char *
128 vhost_default_mime(struct vhost *v, const char *path)
130 struct location *loc;
131 const char *default_mime = "application/octet-stream";
133 if (v == NULL || path == NULL)
134 return default_mime;
136 loc = TAILQ_FIRST(&v->locations);
137 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
138 if (*loc->default_mime != '\0') {
139 if (matches(loc->match, path))
140 return loc->default_mime;
144 loc = TAILQ_FIRST(&v->locations);
145 if (*loc->default_mime != '\0')
146 return loc->default_mime;
147 return default_mime;
150 const char *
151 vhost_index(struct vhost *v, const char *path)
153 struct location *loc;
154 const char *index = "index.gmi";
156 if (v == NULL || path == NULL)
157 return index;
159 loc = TAILQ_FIRST(&v->locations);
160 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
161 if (*loc->index != '\0') {
162 if (matches(loc->match, path))
163 return loc->index;
167 loc = TAILQ_FIRST(&v->locations);
168 if (*loc->index != '\0')
169 return loc->index;
170 return index;
173 int
174 vhost_auto_index(struct vhost *v, const char *path)
176 struct location *loc;
178 if (v == NULL || path == NULL)
179 return 0;
181 loc = TAILQ_FIRST(&v->locations);
182 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
183 if (loc->auto_index != 0) {
184 if (matches(loc->match, path))
185 return loc->auto_index == 1;
189 loc = TAILQ_FIRST(&v->locations);
190 return loc->auto_index == 1;
193 int
194 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
196 struct location *loc;
198 if (v == NULL || path == NULL)
199 return 0;
201 loc = TAILQ_FIRST(&v->locations);
202 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
203 if (loc->block_code != 0) {
204 if (matches(loc->match, path)) {
205 *code = loc->block_code;
206 *fmt = loc->block_fmt;
207 return 1;
212 loc = TAILQ_FIRST(&v->locations);
213 *code = loc->block_code;
214 *fmt = loc->block_fmt;
215 return loc->block_code != 0;
218 int
219 vhost_fastcgi(struct vhost *v, const char *path)
221 struct location *loc;
223 if (v == NULL || path == NULL)
224 return -1;
226 loc = TAILQ_FIRST(&v->locations);
227 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
228 if (loc->fcgi != -1)
229 if (matches(loc->match, path))
230 return loc->fcgi;
233 loc = TAILQ_FIRST(&v->locations);
234 return loc->fcgi;
237 int
238 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
240 struct location *loc;
241 size_t l = 0;
243 if (v == NULL || path == NULL)
244 return -1;
246 loc = TAILQ_FIRST(&v->locations);
247 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
248 l++;
249 if (loc->dirfd != -1)
250 if (matches(loc->match, path)) {
251 *retloc = l;
252 return loc->dirfd;
256 *retloc = 0;
257 loc = TAILQ_FIRST(&v->locations);
258 return loc->dirfd;
261 int
262 vhost_strip(struct vhost *v, const char *path)
264 struct location *loc;
266 if (v == NULL || path == NULL)
267 return 0;
269 loc = TAILQ_FIRST(&v->locations);
270 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
271 if (loc->strip != 0) {
272 if (matches(loc->match, path))
273 return loc->strip;
277 loc = TAILQ_FIRST(&v->locations);
278 return loc->strip;
281 X509_STORE *
282 vhost_require_ca(struct vhost *v, const char *path)
284 struct location *loc;
286 if (v == NULL || path == NULL)
287 return NULL;
289 loc = TAILQ_FIRST(&v->locations);
290 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
291 if (loc->reqca != NULL) {
292 if (matches(loc->match, path))
293 return loc->reqca;
297 loc = TAILQ_FIRST(&v->locations);
298 return loc->reqca;
301 int
302 vhost_disable_log(struct vhost *v, const char *path)
304 struct location *loc;
306 if (v == NULL || path == NULL)
307 return 0;
309 loc = TAILQ_FIRST(&v->locations);
310 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
311 if (loc->disable_log && matches(loc->match, path))
312 return 1;
315 loc = TAILQ_FIRST(&v->locations);
316 return loc->disable_log;
319 static int
320 check_path(struct client *c, const char *path, int *fd)
322 struct stat sb;
323 const char *p;
324 int dirfd, strip;
326 assert(path != NULL);
328 /*
329 * in send_dir we add an initial / (to be redirect-friendly),
330 * but here we want to skip it
331 */
332 if (*path == '/')
333 path++;
335 strip = vhost_strip(c->host, path);
336 p = strip_path(path, strip);
338 if (*p == '/')
339 p = p+1;
340 if (*p == '\0')
341 p = ".";
343 dirfd = vhost_dirfd(c->host, path, &c->loc);
344 log_debug("check_path: strip=%d path=%s original=%s",
345 strip, p, path);
346 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
347 if (errno == EACCES)
348 log_info("can't open %s: %s", p, strerror(errno));
349 return FILE_MISSING;
352 if (fstat(*fd, &sb) == -1) {
353 log_warn("fstat %s", path);
354 return FILE_MISSING;
357 if (S_ISDIR(sb.st_mode))
358 return FILE_DIRECTORY;
360 return FILE_EXISTS;
363 static void
364 open_file(struct client *c)
366 switch (check_path(c, c->iri.path, &c->pfd)) {
367 case FILE_EXISTS:
368 c->type = REQUEST_FILE;
369 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
370 return;
372 case FILE_DIRECTORY:
373 open_dir(c);
374 return;
376 case FILE_MISSING:
377 start_reply(c, NOT_FOUND, "not found");
378 return;
380 default:
381 /* unreachable */
382 abort();
386 void
387 mark_nonblock(int fd)
389 int flags;
391 if ((flags = fcntl(fd, F_GETFL)) == -1)
392 fatal("fcntl(F_GETFL)");
393 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
394 fatal("fcntl(F_SETFL)");
397 static void
398 handle_handshake(int fd, short ev, void *d)
400 struct client *c = d;
401 struct conf *conf = c->conf;
402 struct vhost *h;
403 struct alist *a;
404 const char *servname;
405 const char *parse_err = "unknown error";
407 switch (tls_handshake(c->ctx)) {
408 case 0: /* success */
409 case -1: /* already handshaked */
410 break;
411 case TLS_WANT_POLLIN:
412 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
413 return;
414 case TLS_WANT_POLLOUT:
415 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
416 return;
417 default:
418 /* unreachable */
419 abort();
422 c->bev = bufferevent_new(fd, client_read, client_write,
423 client_error, c);
424 if (c->bev == NULL)
425 fatal("%s: failed to allocate client buffer", __func__);
427 event_set(&c->bev->ev_read, c->fd, EV_READ,
428 client_tls_readcb, c->bev);
429 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
430 client_tls_writecb, c->bev);
432 #if HAVE_LIBEVENT2
433 evbuffer_unfreeze(c->bev->input, 0);
434 evbuffer_unfreeze(c->bev->output, 1);
435 #endif
437 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
438 log_debug("handshake: missing SNI");
439 goto err;
442 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
443 log_info("puny_decode: %s", parse_err);
444 goto err;
447 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
448 if (matches(h->domain, c->domain))
449 goto found;
450 TAILQ_FOREACH(a, &h->aliases, aliases) {
451 if (matches(a->alias, c->domain))
452 goto found;
456 found:
457 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
458 servname != NULL ? servname : "(null)",
459 c->domain,
460 h != NULL ? h->domain : "(null)");
462 if (h != NULL) {
463 c->host = h;
464 bufferevent_enable(c->bev, EV_READ);
465 return;
468 err:
469 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
472 static const char *
473 strip_path(const char *path, int strip)
475 char *t;
477 while (strip > 0) {
478 if ((t = strchr(path, '/')) == NULL) {
479 path = strchr(path, '\0');
480 break;
482 path = t;
483 strip--;
486 return path;
489 static void
490 fmt_sbuf(const char *fmt, struct client *c, const char *path)
492 struct conf *conf = c->conf;
493 size_t i;
494 char buf[32];
496 memset(buf, 0, sizeof(buf));
497 for (i = 0; *fmt; ++fmt) {
498 if (i == sizeof(buf)-1 || *fmt == '%') {
499 strlcat(c->sbuf, buf, sizeof(c->sbuf));
500 memset(buf, 0, sizeof(buf));
501 i = 0;
504 if (*fmt != '%') {
505 buf[i++] = *fmt;
506 continue;
509 switch (*++fmt) {
510 case '%':
511 strlcat(c->sbuf, "%", sizeof(c->sbuf));
512 break;
513 case 'p':
514 if (*path != '/')
515 strlcat(c->sbuf, "/", sizeof(c->sbuf));
516 strlcat(c->sbuf, path, sizeof(c->sbuf));
517 break;
518 case 'q':
519 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
520 break;
521 case 'P':
522 snprintf(buf, sizeof(buf), "%d", conf->port);
523 strlcat(c->sbuf, buf, sizeof(c->sbuf));
524 memset(buf, 0, sizeof(buf));
525 break;
526 case 'N':
527 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
528 break;
529 default:
530 fatalx("%s: unknown fmt specifier %c",
531 __func__, *fmt);
535 if (i != 0)
536 strlcat(c->sbuf, buf, sizeof(c->sbuf));
539 /* 1 if a matching `block return' (and apply it), 0 otherwise */
540 static int
541 apply_block_return(struct client *c)
543 const char *fmt, *path;
544 int code;
546 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
547 return 0;
549 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
550 fmt_sbuf(fmt, c, path);
552 start_reply(c, code, c->sbuf);
553 return 1;
556 static struct proxy *
557 matched_proxy(struct client *c)
559 struct proxy *p;
560 const char *proto;
561 const char *host;
562 const char *port;
564 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
565 if (*(proto = p->match_proto) == '\0')
566 proto = "gemini";
567 if (*(host = p->match_host) == '\0')
568 host = "*";
569 if (*(port = p->match_port) == '\0')
570 port = "*";
572 if (matches(proto, c->iri.schema) &&
573 matches(host, c->domain) &&
574 matches(port, c->iri.port))
575 return p;
578 return NULL;
581 static int
582 check_matching_certificate(X509_STORE *store, struct client *c)
584 const uint8_t *cert;
585 size_t len;
587 if (!tls_peer_cert_provided(c->ctx)) {
588 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
589 return 1;
592 cert = tls_peer_cert_chain_pem(c->ctx, &len);
593 if (!validate_against_ca(store, cert, len)) {
594 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
595 return 1;
598 return 0;
601 static int
602 proxy_socket(struct client *c, const char *host, const char *port)
604 struct addrinfo hints, *res, *res0;
605 int r, sock, save_errno;
606 const char *cause = NULL;
608 memset(&hints, 0, sizeof(hints));
609 hints.ai_family = AF_UNSPEC;
610 hints.ai_socktype = SOCK_STREAM;
612 /* XXX: asr_run? :> */
613 r = getaddrinfo(host, port, &hints, &res0);
614 if (r != 0) {
615 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
616 host, port, gai_strerror(r));
617 return -1;
620 for (res = res0; res; res = res->ai_next) {
621 sock = socket(res->ai_family, res->ai_socktype,
622 res->ai_protocol);
623 if (sock == -1) {
624 cause = "socket";
625 continue;
628 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
629 cause = "connect";
630 save_errno = errno;
631 close(sock);
632 errno = save_errno;
633 sock = -1;
634 continue;
637 break;
640 if (sock == -1)
641 log_warn("can't connect to %s:%s: %s", host, port, cause);
643 freeaddrinfo(res0);
645 return sock;
648 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
649 static int
650 apply_reverse_proxy(struct client *c)
652 struct proxy *p;
654 if ((p = matched_proxy(c)) == NULL)
655 return 0;
657 c->proxy = p;
659 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
660 return 1;
662 log_debug("opening proxy connection for %s:%s",
663 p->host, p->port);
665 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
666 start_reply(c, PROXY_ERROR, "proxy error");
667 return 1;
670 mark_nonblock(c->pfd);
671 if (proxy_init(c) == -1)
672 start_reply(c, PROXY_ERROR, "proxy error");
674 return 1;
677 static int
678 fcgi_open_sock(struct fcgi *f)
680 struct sockaddr_un addr;
681 int fd;
683 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
684 log_warn("socket");
685 return -1;
688 memset(&addr, 0, sizeof(addr));
689 addr.sun_family = AF_UNIX;
690 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
692 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
693 log_warn("failed to connect to %s", f->path);
694 close(fd);
695 return -1;
698 return fd;
701 static int
702 fcgi_open_conn(struct fcgi *f)
704 struct addrinfo hints, *servinfo, *p;
705 int r, sock, save_errno;
706 const char *cause = NULL;
708 memset(&hints, 0, sizeof(hints));
709 hints.ai_family = AF_UNSPEC;
710 hints.ai_socktype = SOCK_STREAM;
711 hints.ai_flags = AI_ADDRCONFIG;
713 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
714 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
715 gai_strerror(r));
716 return -1;
719 for (p = servinfo; p != NULL; p = p->ai_next) {
720 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
721 if (sock == -1) {
722 cause = "socket";
723 continue;
725 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
726 cause = "connect";
727 save_errno = errno;
728 close(sock);
729 errno = save_errno;
730 continue;
732 break;
735 if (p == NULL) {
736 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
737 cause);
738 sock = -1;
741 freeaddrinfo(servinfo);
742 return sock;
745 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
746 static int
747 apply_fastcgi(struct client *c)
749 int id, i = 0;
750 struct fcgi *f;
752 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
753 return 0;
755 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
756 if (i == id)
757 break;
758 ++i;
761 if (f == NULL) {
762 log_warnx("can't find fcgi #%d", id);
763 return 0;
766 log_debug("opening fastcgi connection for (%s,%s)",
767 f->path, f->port);
769 if (*f->port == '\0')
770 c->pfd = fcgi_open_sock(f);
771 else
772 c->pfd = fcgi_open_conn(f);
774 if (c->pfd == -1) {
775 start_reply(c, CGI_ERROR, "CGI error");
776 return 1;
779 mark_nonblock(c->pfd);
781 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
782 fcgi_error, c);
783 if (c->cgibev == NULL) {
784 start_reply(c, TEMP_FAILURE, "internal server error");
785 return 1;
788 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
789 fcgi_req(c);
791 return 1;
794 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
795 static int
796 apply_require_ca(struct client *c)
798 X509_STORE *store;
800 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
801 return 0;
802 return check_matching_certificate(store, c);
805 static void
806 open_dir(struct client *c)
808 size_t len;
809 int dirfd, root;
810 char *before_file;
812 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
814 len = strlen(c->iri.path);
815 if (len > 0 && !ends_with(c->iri.path, "/")) {
816 redirect_canonical_dir(c);
817 return;
820 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
821 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
822 if (!ends_with(c->sbuf, "/"))
823 strlcat(c->sbuf, "/", sizeof(c->sbuf));
824 before_file = strchr(c->sbuf, '\0');
825 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
826 sizeof(c->sbuf));
827 if (len >= sizeof(c->sbuf)) {
828 start_reply(c, TEMP_FAILURE, "internal server error");
829 return;
832 c->iri.path = c->sbuf;
834 /* close later unless we have to generate the dir listing */
835 dirfd = c->pfd;
836 c->pfd = -1;
838 switch (check_path(c, c->iri.path, &c->pfd)) {
839 case FILE_EXISTS:
840 c->type = REQUEST_FILE;
841 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
842 break;
844 case FILE_DIRECTORY:
845 start_reply(c, TEMP_REDIRECT, c->sbuf);
846 break;
848 case FILE_MISSING:
849 *before_file = '\0';
851 if (!vhost_auto_index(c->host, c->iri.path)) {
852 start_reply(c, NOT_FOUND, "not found");
853 break;
856 c->type = REQUEST_DIR;
858 c->dirlen = scandir_fd(dirfd, &c->dir,
859 root ? select_non_dotdot : select_non_dot,
860 alphasort);
861 if (c->dirlen == -1) {
862 log_warn("scandir_fd(%d) (vhost:%s) %s",
863 c->pfd, c->host->domain, c->iri.path);
864 start_reply(c, TEMP_FAILURE, "internal server error");
865 return;
867 c->diroff = 0;
868 c->off = 0;
870 start_reply(c, SUCCESS, "text/gemini");
871 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
872 "# Index of %s\n\n", c->iri.path);
873 return;
875 default:
876 /* unreachable */
877 abort();
880 close(dirfd);
883 static void
884 redirect_canonical_dir(struct client *c)
886 size_t len;
888 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
889 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
890 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
892 if (len >= sizeof(c->sbuf)) {
893 start_reply(c, TEMP_FAILURE, "internal server error");
894 return;
897 start_reply(c, TEMP_REDIRECT, c->sbuf);
900 static void
901 client_tls_readcb(int fd, short event, void *d)
903 struct bufferevent *bufev = d;
904 struct client *client = bufev->cbarg;
905 ssize_t ret;
906 size_t len;
907 int what = EVBUFFER_READ;
908 int howmuch = IBUF_READ_SIZE;
909 char buf[IBUF_READ_SIZE];
911 if (event == EV_TIMEOUT) {
912 what |= EVBUFFER_TIMEOUT;
913 goto err;
916 if (bufev->wm_read.high != 0)
917 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
919 switch (ret = tls_read(client->ctx, buf, howmuch)) {
920 case TLS_WANT_POLLIN:
921 case TLS_WANT_POLLOUT:
922 goto retry;
923 case -1:
924 what |= EVBUFFER_ERROR;
925 goto err;
927 len = ret;
929 if (len == 0) {
930 what |= EVBUFFER_EOF;
931 goto err;
934 if (evbuffer_add(bufev->input, buf, len) == -1) {
935 what |= EVBUFFER_ERROR;
936 goto err;
939 event_add(&bufev->ev_read, NULL);
940 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
941 return;
942 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
943 /*
944 * here we could implement a read pressure policy.
945 */
948 if (bufev->readcb != NULL)
949 (*bufev->readcb)(bufev, bufev->cbarg);
951 return;
953 retry:
954 event_add(&bufev->ev_read, NULL);
955 return;
957 err:
958 (*bufev->errorcb)(bufev, what, bufev->cbarg);
961 static void
962 client_tls_writecb(int fd, short event, void *d)
964 struct bufferevent *bufev = d;
965 struct client *client = bufev->cbarg;
966 ssize_t ret;
967 size_t len;
968 short what = EVBUFFER_WRITE;
970 if (event == EV_TIMEOUT) {
971 what |= EVBUFFER_TIMEOUT;
972 goto err;
975 if (EVBUFFER_LENGTH(bufev->output) != 0) {
976 ret = tls_write(client->ctx,
977 EVBUFFER_DATA(bufev->output),
978 EVBUFFER_LENGTH(bufev->output));
979 switch (ret) {
980 case TLS_WANT_POLLIN:
981 case TLS_WANT_POLLOUT:
982 goto retry;
983 case -1:
984 what |= EVBUFFER_ERROR;
985 goto err;
987 len = ret;
988 evbuffer_drain(bufev->output, len);
991 if (EVBUFFER_LENGTH(bufev->output) != 0)
992 event_add(&bufev->ev_write, NULL);
994 if (bufev->writecb != NULL &&
995 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
996 (*bufev->writecb)(bufev, bufev->cbarg);
997 return;
999 retry:
1000 event_add(&bufev->ev_write, NULL);
1001 return;
1002 err:
1003 log_warnx("tls error: %s", tls_error(client->ctx));
1004 (*bufev->errorcb)(bufev, what, bufev->cbarg);
1007 static void
1008 client_read(struct bufferevent *bev, void *d)
1010 struct client *c = d;
1011 struct evbuffer *src = EVBUFFER_INPUT(bev);
1012 const char *parse_err = "invalid request";
1013 char decoded[DOMAIN_NAME_LEN];
1014 size_t len;
1016 bufferevent_disable(bev, EVBUFFER_READ);
1019 * libevent2 can still somehow call this function, even
1020 * though I never enable EV_READ in the bufferevent. If
1021 * that's the case, bail out.
1023 if (c->type != REQUEST_UNDECIDED)
1024 return;
1026 /* max url len + \r\n */
1027 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1028 log_debug("too much data received");
1029 start_reply(c, BAD_REQUEST, "bad request");
1030 return;
1033 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1034 if (c->req == NULL) {
1035 /* not enough data yet. */
1036 bufferevent_enable(bev, EVBUFFER_READ);
1037 return;
1039 c->reqlen = strlen(c->req);
1040 if (c->reqlen > 1024+2) {
1041 log_debug("URL too long");
1042 start_reply(c, BAD_REQUEST, "bad request");
1043 return;
1046 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1047 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1048 log_debug("IRI parse error: %s", parse_err);
1049 start_reply(c, BAD_REQUEST, "bad request");
1050 return;
1053 if (apply_reverse_proxy(c))
1054 return;
1056 /* ignore the port number */
1057 if (strcmp(c->iri.schema, "gemini") ||
1058 strcmp(decoded, c->domain)) {
1059 start_reply(c, PROXY_REFUSED, "won't proxy request");
1060 return;
1063 if (apply_require_ca(c) ||
1064 apply_block_return(c)||
1065 apply_fastcgi(c))
1066 return;
1068 open_file(c);
1071 void
1072 client_write(struct bufferevent *bev, void *d)
1074 struct client *c = d;
1075 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1076 char nam[PATH_MAX];
1077 char buf[BUFSIZ];
1078 ssize_t r;
1080 switch (c->type) {
1081 case REQUEST_UNDECIDED:
1083 * Ignore spurious calls when we still don't have idea
1084 * what to do with the request.
1086 break;
1088 case REQUEST_FILE:
1089 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1090 log_warn("read");
1091 client_error(bev, EVBUFFER_ERROR, c);
1092 return;
1093 } else if (r == 0) {
1094 client_close(c);
1095 return;
1096 } else if (r != sizeof(buf))
1097 c->type = REQUEST_DONE;
1098 bufferevent_write(bev, buf, r);
1099 break;
1101 case REQUEST_DIR:
1102 /* TODO: handle big big directories better */
1103 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1104 const char *sufx = "";
1106 encode_path(nam, sizeof(nam),
1107 c->dir[c->diroff]->d_name);
1108 if (c->dir[c->diroff]->d_type == DT_DIR)
1109 sufx = "/";
1110 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1111 free(c->dir[c->diroff]);
1113 free(c->dir);
1114 c->dir = NULL;
1116 c->type = REQUEST_DONE;
1118 event_add(&c->bev->ev_write, NULL);
1119 break;
1121 case REQUEST_FCGI:
1122 case REQUEST_PROXY:
1124 * Here we depend on fastcgi or proxy connection to
1125 * provide data.
1127 break;
1129 case REQUEST_DONE:
1130 if (EVBUFFER_LENGTH(out) == 0)
1131 client_close(c);
1132 break;
1136 static void
1137 client_error(struct bufferevent *bev, short error, void *d)
1139 struct client *c = d;
1141 c->type = REQUEST_DONE;
1143 if (error & EVBUFFER_TIMEOUT) {
1144 log_debug("timeout; forcefully closing the connection");
1145 if (c->code == 0)
1146 start_reply(c, BAD_REQUEST, "timeout");
1147 else
1148 client_close(c);
1149 return;
1152 if (error & EVBUFFER_EOF) {
1153 client_close(c);
1154 return;
1157 log_warnx("unknown bufferevent error 0x%x", error);
1158 client_close(c);
1161 void
1162 start_reply(struct client *c, int code, const char *meta)
1164 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1165 const char *lang;
1166 int r, rr;
1168 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1170 c->code = code;
1171 c->meta = meta;
1173 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1174 if (r == -1)
1175 goto err;
1177 /* 2 digit status + space + 1024 max reply */
1178 if (r > 1027)
1179 goto overflow;
1181 if (c->type != REQUEST_FCGI &&
1182 c->type != REQUEST_PROXY &&
1183 !strcmp(meta, "text/gemini") &&
1184 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1185 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1186 if (rr == -1)
1187 goto err;
1188 if (r + rr > 1027)
1189 goto overflow;
1192 bufferevent_write(c->bev, "\r\n", 2);
1194 if (!vhost_disable_log(c->host, c->iri.path))
1195 log_request(c, (char *)EVBUFFER_DATA(evb),
1196 EVBUFFER_LENGTH(evb));
1198 if (code != 20)
1199 c->type = REQUEST_DONE;
1201 return;
1203 err:
1204 log_warnx("evbuffer_add_printf error: no memory");
1205 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1206 client_close(c);
1207 return;
1209 overflow:
1210 log_warnx("reply header overflow");
1211 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1212 start_reply(c, TEMP_FAILURE, "internal error");
1215 static void
1216 client_close_ev(int fd, short event, void *d)
1218 struct client *c = d;
1220 switch (tls_close(c->ctx)) {
1221 case TLS_WANT_POLLIN:
1222 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1223 break;
1224 case TLS_WANT_POLLOUT:
1225 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1226 break;
1229 connected_clients--;
1231 free(c->req);
1233 tls_free(c->ctx);
1234 c->ctx = NULL;
1236 free(c->header);
1238 if (c->pfd != -1)
1239 close(c->pfd);
1241 if (c->dir != NULL)
1242 free(c->dir);
1244 close(c->fd);
1245 c->fd = -1;
1248 static void
1249 client_proxy_close(int fd, short event, void *d)
1251 struct tls *ctx = d;
1253 if (ctx == NULL) {
1254 close(fd);
1255 return;
1258 switch (tls_close(ctx)) {
1259 case TLS_WANT_POLLIN:
1260 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1261 break;
1262 case TLS_WANT_POLLOUT:
1263 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1264 break;
1267 tls_free(ctx);
1268 close(fd);
1271 void
1272 client_close(struct client *c)
1275 * We may end up calling client_close in various situations
1276 * and for the most unexpected reasons. Therefore, we need to
1277 * ensure that everything gets properly released once we reach
1278 * this point.
1281 SPLAY_REMOVE(client_tree_id, &clients, c);
1283 if (c->cgibev != NULL) {
1284 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1285 bufferevent_free(c->cgibev);
1286 c->cgibev = NULL;
1287 close(c->pfd);
1288 c->pfd = -1;
1291 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1292 bufferevent_free(c->bev);
1293 c->bev = NULL;
1295 if (c->proxyevset &&
1296 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1297 c->proxyevset = 0;
1298 event_del(&c->proxyev);
1301 if (c->pfd != -1 && c->proxyctx != NULL) {
1302 /* shut down the proxy TLS connection */
1303 client_proxy_close(c->pfd, 0, c->proxyctx);
1304 c->pfd = -1;
1307 if (c->proxybev != NULL)
1308 bufferevent_free(c->proxybev);
1310 client_close_ev(c->fd, 0, c);
1313 void
1314 do_accept(int sock, short et, void *d)
1316 struct conf *conf = d;
1317 struct client *c;
1318 struct sockaddr_storage addr;
1319 struct sockaddr *saddr;
1320 socklen_t len;
1321 int fd;
1323 saddr = (struct sockaddr*)&addr;
1324 len = sizeof(addr);
1325 if ((fd = accept(sock, saddr, &len)) == -1) {
1326 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1327 errno == ECONNABORTED)
1328 return;
1329 fatal("accept");
1332 mark_nonblock(fd);
1334 c = xcalloc(1, sizeof(*c));
1335 c->conf = conf;
1336 c->id = ++server_client_id;
1337 c->fd = fd;
1338 c->pfd = -1;
1339 c->addr = addr;
1341 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1342 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1343 close(c->fd);
1344 free(c);
1345 return;
1348 SPLAY_INSERT(client_tree_id, &clients, c);
1349 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1350 connected_clients++;
1353 struct client *
1354 client_by_id(int id)
1356 struct client find;
1358 find.id = id;
1359 return SPLAY_FIND(client_tree_id, &clients, &find);
1362 static void
1363 handle_siginfo(int fd, short ev, void *d)
1365 log_info("%d connected clients", connected_clients);
1368 static void
1369 add_keypair(struct vhost *h, struct tls_config *conf)
1371 if (h->ocsp == NULL) {
1372 if (tls_config_add_keypair_mem(conf, h->cert, h->certlen,
1373 h->key, h->keylen) == -1)
1374 fatalx("failed to load the keypair: %s",
1375 tls_config_error(conf));
1376 } else {
1377 if (tls_config_add_keypair_ocsp_mem(conf, h->cert, h->certlen,
1378 h->key, h->keylen, h->ocsp, h->ocsplen) == -1)
1379 fatalx("failed to load the keypair: %s",
1380 tls_config_error(conf));
1384 static void
1385 setup_tls(struct conf *conf)
1387 struct tls_config *tlsconf;
1388 struct vhost *h;
1390 if (ctx == NULL) {
1391 if ((ctx = tls_server()) == NULL)
1392 fatal("tls_server failure");
1395 if ((tlsconf = tls_config_new()) == NULL)
1396 fatal("tls_config_new");
1398 if (conf->use_privsep_crypto)
1399 tls_config_use_fake_private_key(tlsconf);
1401 /* optionally accept client certs, but don't try to verify them */
1402 tls_config_verify_client_optional(tlsconf);
1403 tls_config_insecure_noverifycert(tlsconf);
1405 if (tls_config_set_protocols(tlsconf, conf->protos) == -1)
1406 fatalx("tls_config_set_protocols: %s",
1407 tls_config_error(tlsconf));
1409 h = TAILQ_FIRST(&conf->hosts);
1411 /* we need to set something, then we can add how many key we want */
1412 if (tls_config_set_keypair_mem(tlsconf, h->cert, h->certlen,
1413 h->key, h->keylen) == -1)
1414 fatalx("tls_config_set_keypair_mem failed: %s",
1415 tls_config_error(tlsconf));
1417 /* same for OCSP */
1418 if (h->ocsp != NULL &&
1419 tls_config_set_ocsp_staple_mem(tlsconf, h->ocsp, h->ocsplen)
1420 == -1)
1421 fatalx("tls_config_set_ocsp_staple_file failed: %s",
1422 tls_config_error(tlsconf));
1424 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1425 add_keypair(h, tlsconf);
1427 tls_reset(ctx);
1428 if (tls_configure(ctx, tlsconf) == -1)
1429 fatalx("tls_configure: %s", tls_error(ctx));
1431 tls_config_free(tlsconf);
1434 static void
1435 load_vhosts(struct conf *conf)
1437 struct vhost *h;
1438 struct location *l;
1440 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1441 TAILQ_FOREACH(l, &h->locations, locations) {
1442 if (*l->dir == '\0')
1443 continue;
1444 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1445 if (l->dirfd == -1)
1446 fatal("open %s for domain %s", l->dir,
1447 h->domain);
1452 void
1453 server(struct privsep *ps, struct privsep_proc *p)
1455 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1458 void
1459 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1461 struct conf *c;
1463 SPLAY_INIT(&clients);
1465 #ifdef SIGINFO
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 c = ps->ps_env;
1480 if (c->use_privsep_crypto)
1481 crypto_engine_init(ps->ps_env);
1485 int
1486 server_configure_done(struct conf *conf)
1488 if (load_default_mime(&conf->mime) == -1)
1489 fatal("can't load default mime");
1490 sort_mime(&conf->mime);
1491 setup_tls(conf);
1492 load_vhosts(conf);
1493 if (conf->sock4 != -1)
1494 event_add(&conf->evsock4, NULL);
1495 if (conf->sock6 != -1)
1496 event_add(&conf->evsock6, NULL);
1498 return 0;
1501 static int
1502 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1504 struct privsep *ps = p->p_ps;
1505 struct conf *conf = ps->ps_env;
1507 switch (imsg->hdr.type) {
1508 case IMSG_RECONF_START:
1509 case IMSG_RECONF_MIME:
1510 case IMSG_RECONF_PROTOS:
1511 case IMSG_RECONF_PORT:
1512 case IMSG_RECONF_SOCK4:
1513 case IMSG_RECONF_SOCK6:
1514 case IMSG_RECONF_FCGI:
1515 case IMSG_RECONF_HOST:
1516 case IMSG_RECONF_CERT:
1517 case IMSG_RECONF_KEY:
1518 case IMSG_RECONF_OCSP:
1519 case IMSG_RECONF_LOC:
1520 case IMSG_RECONF_ENV:
1521 case IMSG_RECONF_ALIAS:
1522 case IMSG_RECONF_PROXY:
1523 case IMSG_RECONF_PROXY_CERT:
1524 case IMSG_RECONF_PROXY_KEY:
1525 return config_recv(conf, imsg);
1526 case IMSG_RECONF_END:
1527 if (config_recv(conf, imsg) == -1)
1528 return -1;
1529 if (server_configure_done(conf) == -1)
1530 return -1;
1531 break;
1532 default:
1533 return -1;
1536 return 0;
1539 static int
1540 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1542 return -1;
1545 static int
1546 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1548 return -1;
1551 int
1552 client_tree_cmp(struct client *a, struct client *b)
1554 if (a->id == b->id)
1555 return 0;
1556 else if (a->id < b->id)
1557 return -1;
1558 else
1559 return +1;
1562 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)