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 "logger.h"
32 #include "log.h"
34 #define MIN(a, b) ((a) < (b) ? (a) : (b))
36 int shutting_down;
38 static struct tls *ctx;
40 static struct event e4, e6, imsgev, siginfo, sigusr2;
41 static int has_ipv6, has_siginfo;
43 int connected_clients;
45 static inline int matches(const char*, const char*);
47 static int check_path(struct client*, const char*, int*);
48 static void open_file(struct client*);
49 static void handle_handshake(int, short, void*);
50 static const char *strip_path(const char*, int);
51 static void fmt_sbuf(const char*, struct client*, const char*);
52 static int apply_block_return(struct client*);
53 static int check_matching_certificate(X509_STORE *, struct client *);
54 static int apply_reverse_proxy(struct client *);
55 static int apply_fastcgi(struct client*);
56 static int apply_require_ca(struct client*);
57 static void open_dir(struct client*);
58 static void redirect_canonical_dir(struct client*);
60 static void client_tls_readcb(int, short, void *);
61 static void client_tls_writecb(int, short, void *);
63 static void client_read(struct bufferevent *, void *);
64 void client_write(struct bufferevent *, void *);
65 static void client_error(struct bufferevent *, short, void *);
67 static void client_close_ev(int, short, void *);
69 static void do_accept(int, short, void*);
71 static void handle_dispatch_imsg(int, short, void *);
72 static void handle_siginfo(int, short, void*);
74 static uint32_t server_client_id;
76 struct client_tree_id clients;
78 static inline int
79 matches(const char *pattern, const char *path)
80 {
81 if (*path == '/')
82 path++;
83 return !fnmatch(pattern, path, 0);
84 }
86 const char *
87 vhost_lang(struct vhost *v, const char *path)
88 {
89 struct location *loc;
91 if (v == NULL || path == NULL)
92 return NULL;
94 loc = TAILQ_FIRST(&v->locations);
95 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
96 if (*loc->lang != '\0') {
97 if (matches(loc->match, path))
98 return loc->lang;
99 }
102 loc = TAILQ_FIRST(&v->locations);
103 if (*loc->lang == '\0')
104 return NULL;
105 return loc->lang;
108 const char *
109 vhost_default_mime(struct vhost *v, const char *path)
111 struct location *loc;
112 const char *default_mime = "application/octet-stream";
114 if (v == NULL || path == NULL)
115 return default_mime;
117 loc = TAILQ_FIRST(&v->locations);
118 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
119 if (*loc->default_mime != '\0') {
120 if (matches(loc->match, path))
121 return loc->default_mime;
125 loc = TAILQ_FIRST(&v->locations);
126 if (*loc->default_mime != '\0')
127 return loc->default_mime;
128 return default_mime;
131 const char *
132 vhost_index(struct vhost *v, const char *path)
134 struct location *loc;
135 const char *index = "index.gmi";
137 if (v == NULL || path == NULL)
138 return index;
140 loc = TAILQ_FIRST(&v->locations);
141 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
142 if (*loc->index != '\0') {
143 if (matches(loc->match, path))
144 return loc->index;
148 loc = TAILQ_FIRST(&v->locations);
149 if (*loc->index != '\0')
150 return loc->index;
151 return index;
154 int
155 vhost_auto_index(struct vhost *v, const char *path)
157 struct location *loc;
159 if (v == NULL || path == NULL)
160 return 0;
162 loc = TAILQ_FIRST(&v->locations);
163 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
164 if (loc->auto_index != 0) {
165 if (matches(loc->match, path))
166 return loc->auto_index == 1;
170 loc = TAILQ_FIRST(&v->locations);
171 return loc->auto_index == 1;
174 int
175 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
177 struct location *loc;
179 if (v == NULL || path == NULL)
180 return 0;
182 loc = TAILQ_FIRST(&v->locations);
183 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
184 if (loc->block_code != 0) {
185 if (matches(loc->match, path)) {
186 *code = loc->block_code;
187 *fmt = loc->block_fmt;
188 return 1;
193 loc = TAILQ_FIRST(&v->locations);
194 *code = loc->block_code;
195 *fmt = loc->block_fmt;
196 return loc->block_code != 0;
199 int
200 vhost_fastcgi(struct vhost *v, const char *path)
202 struct location *loc;
204 if (v == NULL || path == NULL)
205 return -1;
207 loc = TAILQ_FIRST(&v->locations);
208 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
209 if (loc->fcgi != -1)
210 if (matches(loc->match, path))
211 return loc->fcgi;
214 loc = TAILQ_FIRST(&v->locations);
215 return loc->fcgi;
218 int
219 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
221 struct location *loc;
222 size_t l = 0;
224 if (v == NULL || path == NULL)
225 return -1;
227 loc = TAILQ_FIRST(&v->locations);
228 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
229 l++;
230 if (loc->dirfd != -1)
231 if (matches(loc->match, path)) {
232 *retloc = l;
233 return loc->dirfd;
237 *retloc = 0;
238 loc = TAILQ_FIRST(&v->locations);
239 return loc->dirfd;
242 int
243 vhost_strip(struct vhost *v, const char *path)
245 struct location *loc;
247 if (v == NULL || path == NULL)
248 return 0;
250 loc = TAILQ_FIRST(&v->locations);
251 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
252 if (loc->strip != 0) {
253 if (matches(loc->match, path))
254 return loc->strip;
258 loc = TAILQ_FIRST(&v->locations);
259 return loc->strip;
262 X509_STORE *
263 vhost_require_ca(struct vhost *v, const char *path)
265 struct location *loc;
267 if (v == NULL || path == NULL)
268 return NULL;
270 loc = TAILQ_FIRST(&v->locations);
271 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
272 if (loc->reqca != NULL) {
273 if (matches(loc->match, path))
274 return loc->reqca;
278 loc = TAILQ_FIRST(&v->locations);
279 return loc->reqca;
282 int
283 vhost_disable_log(struct vhost *v, const char *path)
285 struct location *loc;
287 if (v == NULL || path == NULL)
288 return 0;
290 loc = TAILQ_FIRST(&v->locations);
291 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
292 if (loc->disable_log && matches(loc->match, path))
293 return 1;
296 loc = TAILQ_FIRST(&v->locations);
297 return loc->disable_log;
300 static int
301 check_path(struct client *c, const char *path, int *fd)
303 struct stat sb;
304 const char *p;
305 int dirfd, strip;
307 assert(path != NULL);
309 /*
310 * in send_dir we add an initial / (to be redirect-friendly),
311 * but here we want to skip it
312 */
313 if (*path == '/')
314 path++;
316 strip = vhost_strip(c->host, path);
317 p = strip_path(path, strip);
319 if (*p == '/')
320 p = p+1;
321 if (*p == '\0')
322 p = ".";
324 dirfd = vhost_dirfd(c->host, path, &c->loc);
325 log_debug("check_path: strip=%d path=%s original=%s",
326 strip, p, path);
327 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
328 if (errno == EACCES)
329 log_info("can't open %s: %s", p, strerror(errno));
330 return FILE_MISSING;
333 if (fstat(*fd, &sb) == -1) {
334 log_warn("fstat %s", path);
335 return FILE_MISSING;
338 if (S_ISDIR(sb.st_mode))
339 return FILE_DIRECTORY;
341 return FILE_EXISTS;
344 static void
345 open_file(struct client *c)
347 switch (check_path(c, c->iri.path, &c->pfd)) {
348 case FILE_EXISTS:
349 c->type = REQUEST_FILE;
350 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
351 return;
353 case FILE_DIRECTORY:
354 open_dir(c);
355 return;
357 case FILE_MISSING:
358 start_reply(c, NOT_FOUND, "not found");
359 return;
361 default:
362 /* unreachable */
363 abort();
367 void
368 mark_nonblock(int fd)
370 int flags;
372 if ((flags = fcntl(fd, F_GETFL)) == -1)
373 fatal("fcntl(F_GETFL)");
374 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
375 fatal("fcntl(F_SETFL)");
378 static void
379 handle_handshake(int fd, short ev, void *d)
381 struct client *c = d;
382 struct vhost *h;
383 struct alist *a;
384 const char *servname;
385 const char *parse_err = "unknown error";
387 switch (tls_handshake(c->ctx)) {
388 case 0: /* success */
389 case -1: /* already handshaked */
390 break;
391 case TLS_WANT_POLLIN:
392 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
393 return;
394 case TLS_WANT_POLLOUT:
395 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
396 return;
397 default:
398 /* unreachable */
399 abort();
402 c->bev = bufferevent_new(fd, client_read, client_write,
403 client_error, c);
404 if (c->bev == NULL)
405 fatal("%s: failed to allocate client buffer", __func__);
407 event_set(&c->bev->ev_read, c->fd, EV_READ,
408 client_tls_readcb, c->bev);
409 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
410 client_tls_writecb, c->bev);
412 #if HAVE_LIBEVENT2
413 evbuffer_unfreeze(c->bev->input, 0);
414 evbuffer_unfreeze(c->bev->output, 1);
415 #endif
417 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
418 log_debug("handshake: missing SNI");
419 goto err;
422 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
423 log_info("puny_decode: %s", parse_err);
424 goto err;
427 TAILQ_FOREACH(h, &hosts, vhosts) {
428 if (matches(h->domain, c->domain))
429 goto found;
430 TAILQ_FOREACH(a, &h->aliases, aliases) {
431 if (matches(a->alias, c->domain))
432 goto found;
436 found:
437 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
438 servname != NULL ? servname : "(null)",
439 c->domain,
440 h != NULL ? h->domain : "(null)");
442 if (h != NULL) {
443 c->host = h;
444 bufferevent_enable(c->bev, EV_READ);
445 return;
448 err:
449 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
452 static const char *
453 strip_path(const char *path, int strip)
455 char *t;
457 while (strip > 0) {
458 if ((t = strchr(path, '/')) == NULL) {
459 path = strchr(path, '\0');
460 break;
462 path = t;
463 strip--;
466 return path;
469 static void
470 fmt_sbuf(const char *fmt, struct client *c, const char *path)
472 size_t i;
473 char buf[32];
475 memset(buf, 0, sizeof(buf));
476 for (i = 0; *fmt; ++fmt) {
477 if (i == sizeof(buf)-1 || *fmt == '%') {
478 strlcat(c->sbuf, buf, sizeof(c->sbuf));
479 memset(buf, 0, sizeof(buf));
480 i = 0;
483 if (*fmt != '%') {
484 buf[i++] = *fmt;
485 continue;
488 switch (*++fmt) {
489 case '%':
490 strlcat(c->sbuf, "%", sizeof(c->sbuf));
491 break;
492 case 'p':
493 if (*path != '/')
494 strlcat(c->sbuf, "/", sizeof(c->sbuf));
495 strlcat(c->sbuf, path, sizeof(c->sbuf));
496 break;
497 case 'q':
498 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
499 break;
500 case 'P':
501 snprintf(buf, sizeof(buf), "%d", conf.port);
502 strlcat(c->sbuf, buf, sizeof(c->sbuf));
503 memset(buf, 0, sizeof(buf));
504 break;
505 case 'N':
506 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
507 break;
508 default:
509 fatalx("%s: unknown fmt specifier %c",
510 __func__, *fmt);
514 if (i != 0)
515 strlcat(c->sbuf, buf, sizeof(c->sbuf));
518 /* 1 if a matching `block return' (and apply it), 0 otherwise */
519 static int
520 apply_block_return(struct client *c)
522 const char *fmt, *path;
523 int code;
525 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
526 return 0;
528 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
529 fmt_sbuf(fmt, c, path);
531 start_reply(c, code, c->sbuf);
532 return 1;
535 static struct proxy *
536 matched_proxy(struct client *c)
538 struct proxy *p;
539 const char *proto;
540 const char *host;
541 const char *port;
543 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
544 if (*(proto = p->match_proto) == '\0')
545 proto = "gemini";
546 if (*(host = p->match_host) == '\0')
547 host = "*";
548 if (*(port = p->match_port) == '\0')
549 port = "*";
551 if (matches(proto, c->iri.schema) &&
552 matches(host, c->domain) &&
553 matches(port, c->iri.port))
554 return p;
557 return NULL;
560 static int
561 check_matching_certificate(X509_STORE *store, struct client *c)
563 const uint8_t *cert;
564 size_t len;
566 if (!tls_peer_cert_provided(c->ctx)) {
567 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
568 return 1;
571 cert = tls_peer_cert_chain_pem(c->ctx, &len);
572 if (!validate_against_ca(store, cert, len)) {
573 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
574 return 1;
577 return 0;
580 static int
581 proxy_socket(struct client *c, const char *host, const char *port)
583 struct addrinfo hints, *res, *res0;
584 int r, sock, save_errno;
585 const char *cause = NULL;
587 memset(&hints, 0, sizeof(hints));
588 hints.ai_family = AF_UNSPEC;
589 hints.ai_socktype = SOCK_STREAM;
591 /* XXX: asr_run? :> */
592 r = getaddrinfo(host, port, &hints, &res0);
593 if (r != 0) {
594 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
595 host, port, gai_strerror(r));
596 return -1;
599 for (res = res0; res; res = res->ai_next) {
600 sock = socket(res->ai_family, res->ai_socktype,
601 res->ai_protocol);
602 if (sock == -1) {
603 cause = "socket";
604 continue;
607 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
608 cause = "connect";
609 save_errno = errno;
610 close(sock);
611 errno = save_errno;
612 sock = -1;
613 continue;
616 break;
619 if (sock == -1)
620 log_warn("can't connect to %s:%s: %s", host, port, cause);
622 freeaddrinfo(res0);
624 return sock;
627 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
628 static int
629 apply_reverse_proxy(struct client *c)
631 struct proxy *p;
633 if ((p = matched_proxy(c)) == NULL)
634 return 0;
636 c->proxy = p;
638 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
639 return 1;
641 log_debug("opening proxy connection for %s:%s",
642 p->host, p->port);
644 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
645 start_reply(c, PROXY_ERROR, "proxy error");
646 return 1;
649 mark_nonblock(c->pfd);
650 if (proxy_init(c) == -1)
651 start_reply(c, PROXY_ERROR, "proxy error");
653 return 1;
656 static int
657 fcgi_open_sock(struct fcgi *f)
659 struct sockaddr_un addr;
660 int fd;
662 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
663 log_warn("socket");
664 return -1;
667 memset(&addr, 0, sizeof(addr));
668 addr.sun_family = AF_UNIX;
669 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
671 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
672 log_warn("failed to connect to %s", f->path);
673 close(fd);
674 return -1;
677 return fd;
680 static int
681 fcgi_open_conn(struct fcgi *f)
683 struct addrinfo hints, *servinfo, *p;
684 int r, sock, save_errno;
685 const char *cause = NULL;
687 memset(&hints, 0, sizeof(hints));
688 hints.ai_family = AF_UNSPEC;
689 hints.ai_socktype = SOCK_STREAM;
690 hints.ai_flags = AI_ADDRCONFIG;
692 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
693 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
694 gai_strerror(r));
695 return -1;
698 for (p = servinfo; p != NULL; p = p->ai_next) {
699 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
700 if (sock == -1) {
701 cause = "socket";
702 continue;
704 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
705 cause = "connect";
706 save_errno = errno;
707 close(sock);
708 errno = save_errno;
709 continue;
711 break;
714 if (p == NULL) {
715 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
716 cause);
717 sock = -1;
720 freeaddrinfo(servinfo);
721 return sock;
724 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
725 static int
726 apply_fastcgi(struct client *c)
728 int id;
729 struct fcgi *f;
731 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
732 return 0;
734 f = &fcgi[id];
736 log_debug("opening fastcgi connection for (%s,%s)",
737 f->path, f->port);
739 if (*f->port == '\0')
740 c->pfd = fcgi_open_sock(f);
741 else
742 c->pfd = fcgi_open_conn(f);
744 if (c->pfd == -1) {
745 start_reply(c, CGI_ERROR, "CGI error");
746 return 1;
749 mark_nonblock(c->pfd);
751 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
752 fcgi_error, c);
753 if (c->cgibev == NULL) {
754 start_reply(c, TEMP_FAILURE, "internal server error");
755 return 1;
758 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
759 fcgi_req(c);
761 return 1;
764 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
765 static int
766 apply_require_ca(struct client *c)
768 X509_STORE *store;
770 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
771 return 0;
772 return check_matching_certificate(store, c);
775 static void
776 open_dir(struct client *c)
778 size_t len;
779 int dirfd, root;
780 char *before_file;
782 log_debug("in open_dir");
784 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
786 len = strlen(c->iri.path);
787 if (len > 0 && !ends_with(c->iri.path, "/")) {
788 redirect_canonical_dir(c);
789 return;
792 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
793 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
794 if (!ends_with(c->sbuf, "/"))
795 strlcat(c->sbuf, "/", sizeof(c->sbuf));
796 before_file = strchr(c->sbuf, '\0');
797 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
798 sizeof(c->sbuf));
799 if (len >= sizeof(c->sbuf)) {
800 start_reply(c, TEMP_FAILURE, "internal server error");
801 return;
804 c->iri.path = c->sbuf;
806 /* close later unless we have to generate the dir listing */
807 dirfd = c->pfd;
808 c->pfd = -1;
810 switch (check_path(c, c->iri.path, &c->pfd)) {
811 case FILE_EXISTS:
812 c->type = REQUEST_FILE;
813 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
814 break;
816 case FILE_DIRECTORY:
817 start_reply(c, TEMP_REDIRECT, c->sbuf);
818 break;
820 case FILE_MISSING:
821 *before_file = '\0';
823 if (!vhost_auto_index(c->host, c->iri.path)) {
824 start_reply(c, NOT_FOUND, "not found");
825 break;
828 c->type = REQUEST_DIR;
830 c->dirlen = scandir_fd(dirfd, &c->dir,
831 root ? select_non_dotdot : select_non_dot,
832 alphasort);
833 if (c->dirlen == -1) {
834 log_warn("scandir_fd(%d) (vhost:%s) %s",
835 c->pfd, c->host->domain, c->iri.path);
836 start_reply(c, TEMP_FAILURE, "internal server error");
837 return;
839 c->diroff = 0;
840 c->off = 0;
842 start_reply(c, SUCCESS, "text/gemini");
843 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
844 "# Index of %s\n\n", c->iri.path);
845 return;
847 default:
848 /* unreachable */
849 abort();
852 close(dirfd);
855 static void
856 redirect_canonical_dir(struct client *c)
858 size_t len;
860 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
861 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
862 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
864 if (len >= sizeof(c->sbuf)) {
865 start_reply(c, TEMP_FAILURE, "internal server error");
866 return;
869 start_reply(c, TEMP_REDIRECT, c->sbuf);
872 static void
873 client_tls_readcb(int fd, short event, void *d)
875 struct bufferevent *bufev = d;
876 struct client *client = bufev->cbarg;
877 ssize_t ret;
878 size_t len;
879 int what = EVBUFFER_READ;
880 int howmuch = IBUF_READ_SIZE;
881 char buf[IBUF_READ_SIZE];
883 if (event == EV_TIMEOUT) {
884 what |= EVBUFFER_TIMEOUT;
885 goto err;
888 if (bufev->wm_read.high != 0)
889 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
891 switch (ret = tls_read(client->ctx, buf, howmuch)) {
892 case TLS_WANT_POLLIN:
893 case TLS_WANT_POLLOUT:
894 goto retry;
895 case -1:
896 what |= EVBUFFER_ERROR;
897 goto err;
899 len = ret;
901 if (len == 0) {
902 what |= EVBUFFER_EOF;
903 goto err;
906 if (evbuffer_add(bufev->input, buf, len) == -1) {
907 what |= EVBUFFER_ERROR;
908 goto err;
911 event_add(&bufev->ev_read, NULL);
912 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
913 return;
914 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
915 /*
916 * here we could implement a read pressure policy.
917 */
920 if (bufev->readcb != NULL)
921 (*bufev->readcb)(bufev, bufev->cbarg);
923 return;
925 retry:
926 event_add(&bufev->ev_read, NULL);
927 return;
929 err:
930 (*bufev->errorcb)(bufev, what, bufev->cbarg);
933 static void
934 client_tls_writecb(int fd, short event, void *d)
936 struct bufferevent *bufev = d;
937 struct client *client = bufev->cbarg;
938 ssize_t ret;
939 size_t len;
940 short what = EVBUFFER_WRITE;
942 if (event == EV_TIMEOUT) {
943 what |= EVBUFFER_TIMEOUT;
944 goto err;
947 if (EVBUFFER_LENGTH(bufev->output) != 0) {
948 ret = tls_write(client->ctx,
949 EVBUFFER_DATA(bufev->output),
950 EVBUFFER_LENGTH(bufev->output));
951 switch (ret) {
952 case TLS_WANT_POLLIN:
953 case TLS_WANT_POLLOUT:
954 goto retry;
955 case -1:
956 what |= EVBUFFER_ERROR;
957 goto err;
959 len = ret;
960 evbuffer_drain(bufev->output, len);
963 if (EVBUFFER_LENGTH(bufev->output) != 0)
964 event_add(&bufev->ev_write, NULL);
966 if (bufev->writecb != NULL &&
967 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
968 (*bufev->writecb)(bufev, bufev->cbarg);
969 return;
971 retry:
972 event_add(&bufev->ev_write, NULL);
973 return;
974 err:
975 log_warnx("tls error: %s", tls_error(client->ctx));
976 (*bufev->errorcb)(bufev, what, bufev->cbarg);
979 static void
980 client_read(struct bufferevent *bev, void *d)
982 struct client *c = d;
983 struct evbuffer *src = EVBUFFER_INPUT(bev);
984 const char *parse_err = "invalid request";
985 char decoded[DOMAIN_NAME_LEN];
986 size_t len;
988 bufferevent_disable(bev, EVBUFFER_READ);
990 /*
991 * libevent2 can still somehow call this function, even
992 * though I never enable EV_READ in the bufferevent. If
993 * that's the case, bail out.
994 */
995 if (c->type != REQUEST_UNDECIDED)
996 return;
998 /* max url len + \r\n */
999 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1000 log_debug("too much data received");
1001 start_reply(c, BAD_REQUEST, "bad request");
1002 return;
1005 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1006 if (c->req == NULL) {
1007 /* not enough data yet. */
1008 bufferevent_enable(bev, EVBUFFER_READ);
1009 return;
1011 c->reqlen = strlen(c->req);
1012 if (c->reqlen > 1024+2) {
1013 log_debug("URL too long");
1014 start_reply(c, BAD_REQUEST, "bad request");
1015 return;
1018 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1019 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1020 log_debug("IRI parse error: %s", parse_err);
1021 start_reply(c, BAD_REQUEST, "bad request");
1022 return;
1025 if (apply_reverse_proxy(c))
1026 return;
1028 /* ignore the port number */
1029 if (strcmp(c->iri.schema, "gemini") ||
1030 strcmp(decoded, c->domain)) {
1031 start_reply(c, PROXY_REFUSED, "won't proxy request");
1032 return;
1035 if (apply_require_ca(c) ||
1036 apply_block_return(c)||
1037 apply_fastcgi(c))
1038 return;
1040 open_file(c);
1043 void
1044 client_write(struct bufferevent *bev, void *d)
1046 struct client *c = d;
1047 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1048 char nam[PATH_MAX];
1049 char buf[BUFSIZ];
1050 ssize_t r;
1052 switch (c->type) {
1053 case REQUEST_UNDECIDED:
1055 * Ignore spurious calls when we still don't have idea
1056 * what to do with the request.
1058 break;
1060 case REQUEST_FILE:
1061 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1062 log_warn("read");
1063 client_error(bev, EVBUFFER_ERROR, c);
1064 return;
1065 } else if (r == 0) {
1066 client_close(c);
1067 return;
1068 } else if (r != sizeof(buf))
1069 c->type = REQUEST_DONE;
1070 bufferevent_write(bev, buf, r);
1071 break;
1073 case REQUEST_DIR:
1074 /* TODO: handle big big directories better */
1075 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1076 const char *sufx = "";
1078 encode_path(nam, sizeof(nam),
1079 c->dir[c->diroff]->d_name);
1080 if (c->dir[c->diroff]->d_type == DT_DIR)
1081 sufx = "/";
1082 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1083 free(c->dir[c->diroff]);
1085 free(c->dir);
1086 c->dir = NULL;
1088 c->type = REQUEST_DONE;
1090 event_add(&c->bev->ev_write, NULL);
1091 break;
1093 case REQUEST_FCGI:
1094 case REQUEST_PROXY:
1096 * Here we depend on fastcgi or proxy connection to
1097 * provide data.
1099 break;
1101 case REQUEST_DONE:
1102 if (EVBUFFER_LENGTH(out) == 0)
1103 client_close(c);
1104 break;
1108 static void
1109 client_error(struct bufferevent *bev, short error, void *d)
1111 struct client *c = d;
1113 c->type = REQUEST_DONE;
1115 if (error & EVBUFFER_TIMEOUT) {
1116 log_debug("timeout; forcefully closing the connection");
1117 if (c->code == 0)
1118 start_reply(c, BAD_REQUEST, "timeout");
1119 else
1120 client_close(c);
1121 return;
1124 if (error & EVBUFFER_EOF) {
1125 client_close(c);
1126 return;
1129 log_warnx("unknown bufferevent error 0x%x", error);
1130 client_close(c);
1133 void
1134 start_reply(struct client *c, int code, const char *meta)
1136 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1137 const char *lang;
1138 int r, rr;
1140 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1142 c->code = code;
1143 c->meta = meta;
1145 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1146 if (r == -1)
1147 goto err;
1149 /* 2 digit status + space + 1024 max reply */
1150 if (r > 1027)
1151 goto overflow;
1153 if (c->type != REQUEST_FCGI &&
1154 c->type != REQUEST_PROXY &&
1155 !strcmp(meta, "text/gemini") &&
1156 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1157 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1158 if (rr == -1)
1159 goto err;
1160 if (r + rr > 1027)
1161 goto overflow;
1164 bufferevent_write(c->bev, "\r\n", 2);
1166 if (!vhost_disable_log(c->host, c->iri.path))
1167 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1169 if (code != 20)
1170 c->type = REQUEST_DONE;
1172 return;
1174 err:
1175 log_warnx("evbuffer_add_printf error: no memory");
1176 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1177 client_close(c);
1178 return;
1180 overflow:
1181 log_warnx("reply header overflow");
1182 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1183 start_reply(c, TEMP_FAILURE, "internal error");
1186 static void
1187 client_close_ev(int fd, short event, void *d)
1189 struct client *c = d;
1191 switch (tls_close(c->ctx)) {
1192 case TLS_WANT_POLLIN:
1193 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1194 break;
1195 case TLS_WANT_POLLOUT:
1196 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1197 break;
1200 connected_clients--;
1202 free(c->req);
1204 tls_free(c->ctx);
1205 c->ctx = NULL;
1207 free(c->header);
1209 if (c->pfd != -1)
1210 close(c->pfd);
1212 if (c->dir != NULL)
1213 free(c->dir);
1215 close(c->fd);
1216 c->fd = -1;
1219 static void
1220 client_proxy_close(int fd, short event, void *d)
1222 struct tls *ctx = d;
1224 if (ctx == NULL) {
1225 close(fd);
1226 return;
1229 switch (tls_close(ctx)) {
1230 case TLS_WANT_POLLIN:
1231 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1232 break;
1233 case TLS_WANT_POLLOUT:
1234 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1235 break;
1238 tls_free(ctx);
1239 close(fd);
1242 void
1243 client_close(struct client *c)
1246 * We may end up calling client_close in various situations
1247 * and for the most unexpected reasons. Therefore, we need to
1248 * ensure that everything gets properly released once we reach
1249 * this point.
1252 SPLAY_REMOVE(client_tree_id, &clients, c);
1254 if (c->cgibev != NULL) {
1255 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1256 bufferevent_free(c->cgibev);
1257 c->cgibev = NULL;
1258 close(c->pfd);
1259 c->pfd = -1;
1262 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1263 bufferevent_free(c->bev);
1264 c->bev = NULL;
1266 if (c->proxyevset &&
1267 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1268 c->proxyevset = 0;
1269 event_del(&c->proxyev);
1272 if (c->pfd != -1 && c->proxyctx != NULL) {
1273 /* shut down the proxy TLS connection */
1274 client_proxy_close(c->pfd, 0, c->proxyctx);
1275 c->pfd = -1;
1278 if (c->proxybev != NULL)
1279 bufferevent_free(c->proxybev);
1281 client_close_ev(c->fd, 0, c);
1284 static void
1285 do_accept(int sock, short et, void *d)
1287 struct client *c;
1288 struct sockaddr_storage addr;
1289 struct sockaddr *saddr;
1290 socklen_t len;
1291 int fd;
1293 saddr = (struct sockaddr*)&addr;
1294 len = sizeof(addr);
1295 if ((fd = accept(sock, saddr, &len)) == -1) {
1296 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1297 errno == ECONNABORTED)
1298 return;
1299 fatal("accept");
1302 mark_nonblock(fd);
1304 c = xcalloc(1, sizeof(*c));
1305 c->id = ++server_client_id;
1306 c->fd = fd;
1307 c->pfd = -1;
1308 c->addr = addr;
1310 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1311 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1312 close(c->fd);
1313 free(c);
1314 return;
1317 SPLAY_INSERT(client_tree_id, &clients, c);
1318 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1319 connected_clients++;
1322 struct client *
1323 client_by_id(int id)
1325 struct client find;
1327 find.id = id;
1328 return SPLAY_FIND(client_tree_id, &clients, &find);
1331 static void
1332 handle_dispatch_imsg(int fd, short ev, void *d)
1334 struct imsgbuf *ibuf = d;
1335 struct imsg imsg;
1336 ssize_t n;
1338 if ((n = imsg_read(ibuf)) == -1) {
1339 if (errno == EAGAIN || errno == EWOULDBLOCK)
1340 return;
1341 fatal("imsg_read");
1344 if (n == 0)
1345 fatalx("connection closed.");
1347 for (;;) {
1348 if ((n = imsg_get(ibuf, &imsg)) == -1)
1349 fatal("imsg_get");
1350 if (n == 0)
1351 return;
1353 switch (imsg.hdr.type) {
1354 case IMSG_QUIT:
1356 * Don't call event_loopbreak since we want to
1357 * finish handling the ongoing connections.
1359 shutting_down = 1;
1361 event_del(&e4);
1362 if (has_ipv6)
1363 event_del(&e6);
1364 if (has_siginfo)
1365 signal_del(&siginfo);
1366 event_del(&imsgev);
1367 signal_del(&sigusr2);
1368 break;
1369 default:
1370 fatalx("Unknown message %d", imsg.hdr.type);
1372 imsg_free(&imsg);
1376 static void
1377 handle_siginfo(int fd, short ev, void *d)
1379 log_info("%d connected clients", connected_clients);
1382 static void
1383 loop(int sock4, int sock6, struct imsgbuf *ibuf)
1385 SPLAY_INIT(&clients);
1387 event_init();
1389 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1390 event_add(&e4, NULL);
1392 if (sock6 != -1) {
1393 has_ipv6 = 1;
1394 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1395 event_add(&e6, NULL);
1398 if (ibuf) {
1399 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1400 handle_dispatch_imsg, ibuf);
1401 event_add(&imsgev, NULL);
1404 #ifdef SIGINFO
1405 has_siginfo = 1;
1406 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1407 signal_add(&siginfo, NULL);
1408 #endif
1409 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1410 signal_add(&sigusr2, NULL);
1412 sandbox_server_process();
1413 event_dispatch();
1414 _exit(0);
1417 static void
1418 add_keypair(struct vhost *h, struct tls_config *conf)
1420 if (*h->ocsp == '\0') {
1421 if (tls_config_add_keypair_file(conf, h->cert, h->key) == -1)
1422 fatalx("failed to load the keypair (%s, %s): %s",
1423 h->cert, h->key, tls_config_error(conf));
1424 } else {
1425 if (tls_config_add_keypair_ocsp_file(conf, h->cert, h->key,
1426 h->ocsp) == -1)
1427 fatalx("failed to load the keypair (%s, %s, %s): %s",
1428 h->cert, h->key, h->ocsp,
1429 tls_config_error(conf));
1434 * XXX: in a ideal privsep world, this is done by the parent process
1435 * and its content sent to us.
1437 static void
1438 setup_tls(void)
1440 struct tls_config *tlsconf;
1441 struct vhost *h;
1443 if ((tlsconf = tls_config_new()) == NULL)
1444 fatal("tls_config_new");
1446 /* optionally accept client certs, but don't try to verify them */
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 h = TAILQ_FIRST(&hosts);
1456 log_info("loading %s, %s, %s", h->cert, h->key, h->ocsp);
1458 /* we need to set something, then we can add how many key we want */
1459 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
1460 fatalx("tls_config_set_keypair_file failed for (%s, %s): %s",
1461 h->cert, h->key, tls_config_error(tlsconf));
1463 /* same for OCSP */
1464 if (*h->ocsp != '\0' &&
1465 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
1466 fatalx("tls_config_set_ocsp_staple_file failed for (%s): %s",
1467 h->ocsp, tls_config_error(tlsconf));
1469 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1470 add_keypair(h, tlsconf);
1472 if ((ctx = tls_server()) == NULL)
1473 fatal("tls_server failure");
1475 if (tls_configure(ctx, tlsconf) == -1)
1476 fatalx("tls_configure: %s", tls_error(ctx));
1478 tls_config_free(tlsconf);
1481 static void
1482 load_vhosts(void)
1484 struct vhost *h;
1485 struct location *l;
1487 TAILQ_FOREACH(h, &hosts, vhosts) {
1488 TAILQ_FOREACH(l, &h->locations, locations) {
1489 if (*l->dir == '\0')
1490 continue;
1491 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1492 if (l->dirfd == -1)
1493 fatal("open %s for domain %s", l->dir,
1494 h->domain);
1499 int
1500 server_main(struct imsgbuf *ibuf, int sock4, int sock6)
1503 * setup tls before dropping privileges: we don't want user
1504 * to put private certs inside the chroot.
1506 setup_tls();
1507 drop_priv();
1508 if (load_default_mime(&conf.mime) == -1)
1509 fatal("can't load default mime");
1510 sort_mime(&conf.mime);
1511 load_vhosts();
1512 loop(sock4, sock6, ibuf);
1513 return 0;
1516 int
1517 client_tree_cmp(struct client *a, struct client *b)
1519 if (a->id == b->id)
1520 return 0;
1521 else if (a->id < b->id)
1522 return -1;
1523 else
1524 return +1;
1527 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)