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"
33 #define MIN(a, b) ((a) < (b) ? (a) : (b))
35 int shutting_down;
37 static struct tls *ctx;
39 static struct event e4, e6, imsgev, siginfo, sigusr2;
40 static int has_ipv6, has_siginfo;
42 int connected_clients;
44 static inline int matches(const char*, const char*);
46 static int check_path(struct client*, const char*, int*);
47 static void open_file(struct client*);
48 static void handle_handshake(int, short, void*);
49 static const char *strip_path(const char*, int);
50 static void fmt_sbuf(const char*, struct client*, const char*);
51 static int apply_block_return(struct client*);
52 static int check_matching_certificate(X509_STORE *, struct client *);
53 static int apply_reverse_proxy(struct client *);
54 static int apply_fastcgi(struct client*);
55 static int apply_require_ca(struct client*);
56 static void open_dir(struct client*);
57 static void redirect_canonical_dir(struct client*);
59 static void client_tls_readcb(int, short, void *);
60 static void client_tls_writecb(int, short, void *);
62 static void client_read(struct bufferevent *, void *);
63 void client_write(struct bufferevent *, void *);
64 static void client_error(struct bufferevent *, short, void *);
66 static void client_close_ev(int, short, void *);
68 static void do_accept(int, short, void*);
70 static void handle_dispatch_imsg(int, short, void *);
71 static void handle_siginfo(int, short, void*);
73 static uint32_t server_client_id;
75 struct client_tree_id clients;
77 static inline int
78 matches(const char *pattern, const char *path)
79 {
80 if (*path == '/')
81 path++;
82 return !fnmatch(pattern, path, 0);
83 }
85 const char *
86 vhost_lang(struct vhost *v, const char *path)
87 {
88 struct location *loc;
90 if (v == NULL || path == NULL)
91 return NULL;
93 loc = TAILQ_FIRST(&v->locations);
94 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
95 if (*loc->lang != '\0') {
96 if (matches(loc->match, path))
97 return loc->lang;
98 }
99 }
101 loc = TAILQ_FIRST(&v->locations);
102 if (*loc->lang == '\0')
103 return NULL;
104 return loc->lang;
107 const char *
108 vhost_default_mime(struct vhost *v, const char *path)
110 struct location *loc;
111 const char *default_mime = "application/octet-stream";
113 if (v == NULL || path == NULL)
114 return default_mime;
116 loc = TAILQ_FIRST(&v->locations);
117 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
118 if (*loc->default_mime != '\0') {
119 if (matches(loc->match, path))
120 return loc->default_mime;
124 loc = TAILQ_FIRST(&v->locations);
125 if (*loc->default_mime != '\0')
126 return loc->default_mime;
127 return default_mime;
130 const char *
131 vhost_index(struct vhost *v, const char *path)
133 struct location *loc;
134 const char *index = "index.gmi";
136 if (v == NULL || path == NULL)
137 return index;
139 loc = TAILQ_FIRST(&v->locations);
140 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
141 if (*loc->index != '\0') {
142 if (matches(loc->match, path))
143 return loc->index;
147 loc = TAILQ_FIRST(&v->locations);
148 if (*loc->index != '\0')
149 return loc->index;
150 return index;
153 int
154 vhost_auto_index(struct vhost *v, const char *path)
156 struct location *loc;
158 if (v == NULL || path == NULL)
159 return 0;
161 loc = TAILQ_FIRST(&v->locations);
162 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
163 if (loc->auto_index != 0) {
164 if (matches(loc->match, path))
165 return loc->auto_index == 1;
169 loc = TAILQ_FIRST(&v->locations);
170 return loc->auto_index == 1;
173 int
174 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
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->block_code != 0) {
184 if (matches(loc->match, path)) {
185 *code = loc->block_code;
186 *fmt = loc->block_fmt;
187 return 1;
192 loc = TAILQ_FIRST(&v->locations);
193 *code = loc->block_code;
194 *fmt = loc->block_fmt;
195 return loc->block_code != 0;
198 int
199 vhost_fastcgi(struct vhost *v, const char *path)
201 struct location *loc;
203 if (v == NULL || path == NULL)
204 return -1;
206 loc = TAILQ_FIRST(&v->locations);
207 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
208 if (loc->fcgi != -1)
209 if (matches(loc->match, path))
210 return loc->fcgi;
213 loc = TAILQ_FIRST(&v->locations);
214 return loc->fcgi;
217 int
218 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
220 struct location *loc;
221 size_t l = 0;
223 if (v == NULL || path == NULL)
224 return -1;
226 loc = TAILQ_FIRST(&v->locations);
227 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
228 l++;
229 if (loc->dirfd != -1)
230 if (matches(loc->match, path)) {
231 *retloc = l;
232 return loc->dirfd;
236 *retloc = 0;
237 loc = TAILQ_FIRST(&v->locations);
238 return loc->dirfd;
241 int
242 vhost_strip(struct vhost *v, const char *path)
244 struct location *loc;
246 if (v == NULL || path == NULL)
247 return 0;
249 loc = TAILQ_FIRST(&v->locations);
250 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
251 if (loc->strip != 0) {
252 if (matches(loc->match, path))
253 return loc->strip;
257 loc = TAILQ_FIRST(&v->locations);
258 return loc->strip;
261 X509_STORE *
262 vhost_require_ca(struct vhost *v, const char *path)
264 struct location *loc;
266 if (v == NULL || path == NULL)
267 return NULL;
269 loc = TAILQ_FIRST(&v->locations);
270 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
271 if (loc->reqca != NULL) {
272 if (matches(loc->match, path))
273 return loc->reqca;
277 loc = TAILQ_FIRST(&v->locations);
278 return loc->reqca;
281 int
282 vhost_disable_log(struct vhost *v, const char *path)
284 struct location *loc;
286 if (v == NULL || path == NULL)
287 return 0;
289 loc = TAILQ_FIRST(&v->locations);
290 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
291 if (loc->disable_log && matches(loc->match, path))
292 return 1;
295 loc = TAILQ_FIRST(&v->locations);
296 return loc->disable_log;
299 static int
300 check_path(struct client *c, const char *path, int *fd)
302 struct stat sb;
303 const char *p;
304 int dirfd, strip;
306 assert(path != NULL);
308 /*
309 * in send_dir we add an initial / (to be redirect-friendly),
310 * but here we want to skip it
311 */
312 if (*path == '/')
313 path++;
315 strip = vhost_strip(c->host, path);
316 p = strip_path(path, strip);
318 if (*p == '/')
319 p = p+1;
320 if (*p == '\0')
321 p = ".";
323 dirfd = vhost_dirfd(c->host, path, &c->loc);
324 log_debug(c, "check_path: strip=%d path=%s original=%s",
325 strip, p, path);
326 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
327 if (errno == EACCES)
328 log_info(c, "can't open %s: %s", p, strerror(errno));
329 return FILE_MISSING;
332 if (fstat(*fd, &sb) == -1) {
333 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
334 return FILE_MISSING;
337 if (S_ISDIR(sb.st_mode))
338 return FILE_DIRECTORY;
340 return FILE_EXISTS;
343 static void
344 open_file(struct client *c)
346 switch (check_path(c, c->iri.path, &c->pfd)) {
347 case FILE_EXISTS:
348 c->type = REQUEST_FILE;
349 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
350 return;
352 case FILE_DIRECTORY:
353 open_dir(c);
354 return;
356 case FILE_MISSING:
357 start_reply(c, NOT_FOUND, "not found");
358 return;
360 default:
361 /* unreachable */
362 abort();
366 void
367 mark_nonblock(int fd)
369 int flags;
371 if ((flags = fcntl(fd, F_GETFL)) == -1)
372 fatal("fcntl(F_GETFL)");
373 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
374 fatal("fcntl(F_SETFL)");
377 static void
378 handle_handshake(int fd, short ev, void *d)
380 struct client *c = d;
381 struct vhost *h;
382 struct alist *a;
383 const char *servname;
384 const char *parse_err = "unknown error";
386 switch (tls_handshake(c->ctx)) {
387 case 0: /* success */
388 case -1: /* already handshaked */
389 break;
390 case TLS_WANT_POLLIN:
391 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
392 return;
393 case TLS_WANT_POLLOUT:
394 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
395 return;
396 default:
397 /* unreachable */
398 abort();
401 c->bev = bufferevent_new(fd, client_read, client_write,
402 client_error, c);
403 if (c->bev == NULL)
404 fatal("%s: failed to allocate client buffer", __func__);
406 event_set(&c->bev->ev_read, c->fd, EV_READ,
407 client_tls_readcb, c->bev);
408 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
409 client_tls_writecb, c->bev);
411 #if HAVE_LIBEVENT2
412 evbuffer_unfreeze(c->bev->input, 0);
413 evbuffer_unfreeze(c->bev->output, 1);
414 #endif
416 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
417 log_debug(c, "handshake: missing SNI");
418 goto err;
421 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
422 log_info(c, "puny_decode: %s", parse_err);
423 goto err;
426 TAILQ_FOREACH(h, &hosts, vhosts) {
427 if (matches(h->domain, c->domain))
428 goto found;
429 TAILQ_FOREACH(a, &h->aliases, aliases) {
430 if (matches(a->alias, c->domain))
431 goto found;
435 found:
436 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
437 servname != NULL ? servname : "(null)",
438 c->domain,
439 h != NULL ? h->domain : "(null)");
441 if (h != NULL) {
442 c->host = h;
443 bufferevent_enable(c->bev, EV_READ);
444 return;
447 err:
448 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
451 static const char *
452 strip_path(const char *path, int strip)
454 char *t;
456 while (strip > 0) {
457 if ((t = strchr(path, '/')) == NULL) {
458 path = strchr(path, '\0');
459 break;
461 path = t;
462 strip--;
465 return path;
468 static void
469 fmt_sbuf(const char *fmt, struct client *c, const char *path)
471 size_t i;
472 char buf[32];
474 memset(buf, 0, sizeof(buf));
475 for (i = 0; *fmt; ++fmt) {
476 if (i == sizeof(buf)-1 || *fmt == '%') {
477 strlcat(c->sbuf, buf, sizeof(c->sbuf));
478 memset(buf, 0, sizeof(buf));
479 i = 0;
482 if (*fmt != '%') {
483 buf[i++] = *fmt;
484 continue;
487 switch (*++fmt) {
488 case '%':
489 strlcat(c->sbuf, "%", sizeof(c->sbuf));
490 break;
491 case 'p':
492 if (*path != '/')
493 strlcat(c->sbuf, "/", sizeof(c->sbuf));
494 strlcat(c->sbuf, path, sizeof(c->sbuf));
495 break;
496 case 'q':
497 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
498 break;
499 case 'P':
500 snprintf(buf, sizeof(buf), "%d", conf.port);
501 strlcat(c->sbuf, buf, sizeof(c->sbuf));
502 memset(buf, 0, sizeof(buf));
503 break;
504 case 'N':
505 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
506 break;
507 default:
508 fatalx("%s: unknown fmt specifier %c",
509 __func__, *fmt);
513 if (i != 0)
514 strlcat(c->sbuf, buf, sizeof(c->sbuf));
517 /* 1 if a matching `block return' (and apply it), 0 otherwise */
518 static int
519 apply_block_return(struct client *c)
521 const char *fmt, *path;
522 int code;
524 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
525 return 0;
527 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
528 fmt_sbuf(fmt, c, path);
530 start_reply(c, code, c->sbuf);
531 return 1;
534 static struct proxy *
535 matched_proxy(struct client *c)
537 struct proxy *p;
538 const char *proto;
539 const char *host;
540 const char *port;
542 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
543 if (*(proto = p->match_proto) == '\0')
544 proto = "gemini";
545 if (*(host = p->match_host) == '\0')
546 host = "*";
547 if (*(port = p->match_port) == '\0')
548 port = "*";
550 if (matches(proto, c->iri.schema) &&
551 matches(host, c->domain) &&
552 matches(port, c->iri.port))
553 return p;
556 return NULL;
559 static int
560 check_matching_certificate(X509_STORE *store, struct client *c)
562 const uint8_t *cert;
563 size_t len;
565 if (!tls_peer_cert_provided(c->ctx)) {
566 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
567 return 1;
570 cert = tls_peer_cert_chain_pem(c->ctx, &len);
571 if (!validate_against_ca(store, cert, len)) {
572 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
573 return 1;
576 return 0;
579 static int
580 proxy_socket(struct client *c, const char *host, const char *port)
582 struct addrinfo hints, *res, *res0;
583 int r, sock;
585 memset(&hints, 0, sizeof(hints));
586 hints.ai_family = AF_UNSPEC;
587 hints.ai_socktype = SOCK_STREAM;
589 /* XXX: asr_run? :> */
590 r = getaddrinfo(host, port, &hints, &res0);
591 if (r != 0) {
592 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
593 host, port, gai_strerror(r));
594 return -1;
597 for (res = res0; res; res = res->ai_next) {
598 sock = socket(res->ai_family, res->ai_socktype,
599 res->ai_protocol);
600 if (sock == -1)
601 continue;
603 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
604 close(sock);
605 sock = -1;
606 continue;
609 break;
612 freeaddrinfo(res0);
614 if (sock == -1)
615 log_warn(c, "can't connect to %s:%s", host, port);
617 return sock;
620 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
621 static int
622 apply_reverse_proxy(struct client *c)
624 struct proxy *p;
626 if ((p = matched_proxy(c)) == NULL)
627 return 0;
629 c->proxy = p;
631 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
632 return 1;
634 log_debug(c, "opening proxy connection for %s:%s",
635 p->host, p->port);
637 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
638 start_reply(c, PROXY_ERROR, "proxy error");
639 return 1;
642 mark_nonblock(c->pfd);
643 if (proxy_init(c) == -1)
644 start_reply(c, PROXY_ERROR, "proxy error");
646 return 1;
649 static int
650 fcgi_open_sock(struct fcgi *f)
652 struct sockaddr_un addr;
653 int fd;
655 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
656 log_err(NULL, "socket: %s", strerror(errno));
657 return -1;
660 memset(&addr, 0, sizeof(addr));
661 addr.sun_family = AF_UNIX;
662 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
664 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
665 log_warn(NULL, "failed to connect to %s: %s", f->path,
666 strerror(errno));
667 close(fd);
668 return -1;
671 return fd;
674 static int
675 fcgi_open_conn(struct fcgi *f)
677 struct addrinfo hints, *servinfo, *p;
678 int r, sock;
680 memset(&hints, 0, sizeof(hints));
681 hints.ai_family = AF_UNSPEC;
682 hints.ai_socktype = SOCK_STREAM;
683 hints.ai_flags = AI_ADDRCONFIG;
685 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
686 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
687 gai_strerror(r));
688 return -1;
691 for (p = servinfo; p != NULL; p = p->ai_next) {
692 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
693 if (sock == -1)
694 continue;
695 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
696 close(sock);
697 continue;
699 break;
702 if (p == NULL) {
703 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
704 sock = -1;
707 freeaddrinfo(servinfo);
708 return sock;
711 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
712 static int
713 apply_fastcgi(struct client *c)
715 int id;
716 struct fcgi *f;
718 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
719 return 0;
721 f = &fcgi[id];
723 log_debug(c, "opening fastcgi connection for (%s,%s)",
724 f->path, f->port);
726 if (*f->port == '\0')
727 c->pfd = fcgi_open_sock(f);
728 else
729 c->pfd = fcgi_open_conn(f);
731 if (c->pfd == -1) {
732 start_reply(c, CGI_ERROR, "CGI error");
733 return 1;
736 mark_nonblock(c->pfd);
738 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
739 fcgi_error, c);
740 if (c->cgibev == NULL) {
741 start_reply(c, TEMP_FAILURE, "internal server error");
742 return 1;
745 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
746 fcgi_req(c);
748 return 1;
751 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
752 static int
753 apply_require_ca(struct client *c)
755 X509_STORE *store;
757 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
758 return 0;
759 return check_matching_certificate(store, c);
762 static void
763 open_dir(struct client *c)
765 size_t len;
766 int dirfd, root;
767 char *before_file;
769 log_debug(c, "in open_dir");
771 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
773 len = strlen(c->iri.path);
774 if (len > 0 && !ends_with(c->iri.path, "/")) {
775 redirect_canonical_dir(c);
776 return;
779 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
780 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
781 if (!ends_with(c->sbuf, "/"))
782 strlcat(c->sbuf, "/", sizeof(c->sbuf));
783 before_file = strchr(c->sbuf, '\0');
784 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
785 sizeof(c->sbuf));
786 if (len >= sizeof(c->sbuf)) {
787 start_reply(c, TEMP_FAILURE, "internal server error");
788 return;
791 c->iri.path = c->sbuf;
793 /* close later unless we have to generate the dir listing */
794 dirfd = c->pfd;
795 c->pfd = -1;
797 switch (check_path(c, c->iri.path, &c->pfd)) {
798 case FILE_EXISTS:
799 c->type = REQUEST_FILE;
800 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
801 break;
803 case FILE_DIRECTORY:
804 start_reply(c, TEMP_REDIRECT, c->sbuf);
805 break;
807 case FILE_MISSING:
808 *before_file = '\0';
810 if (!vhost_auto_index(c->host, c->iri.path)) {
811 start_reply(c, NOT_FOUND, "not found");
812 break;
815 c->type = REQUEST_DIR;
817 c->dirlen = scandir_fd(dirfd, &c->dir,
818 root ? select_non_dotdot : select_non_dot,
819 alphasort);
820 if (c->dirlen == -1) {
821 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
822 c->pfd, c->host->domain, c->iri.path, strerror(errno));
823 start_reply(c, TEMP_FAILURE, "internal server error");
824 return;
826 c->diroff = 0;
827 c->off = 0;
829 start_reply(c, SUCCESS, "text/gemini");
830 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
831 "# Index of %s\n\n", c->iri.path);
832 return;
834 default:
835 /* unreachable */
836 abort();
839 close(dirfd);
842 static void
843 redirect_canonical_dir(struct client *c)
845 size_t len;
847 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
848 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
849 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
851 if (len >= sizeof(c->sbuf)) {
852 start_reply(c, TEMP_FAILURE, "internal server error");
853 return;
856 start_reply(c, TEMP_REDIRECT, c->sbuf);
859 static void
860 client_tls_readcb(int fd, short event, void *d)
862 struct bufferevent *bufev = d;
863 struct client *client = bufev->cbarg;
864 ssize_t ret;
865 size_t len;
866 int what = EVBUFFER_READ;
867 int howmuch = IBUF_READ_SIZE;
868 char buf[IBUF_READ_SIZE];
870 if (event == EV_TIMEOUT) {
871 what |= EVBUFFER_TIMEOUT;
872 goto err;
875 if (bufev->wm_read.high != 0)
876 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
878 switch (ret = tls_read(client->ctx, buf, howmuch)) {
879 case TLS_WANT_POLLIN:
880 case TLS_WANT_POLLOUT:
881 goto retry;
882 case -1:
883 what |= EVBUFFER_ERROR;
884 goto err;
886 len = ret;
888 if (len == 0) {
889 what |= EVBUFFER_EOF;
890 goto err;
893 if (evbuffer_add(bufev->input, buf, len) == -1) {
894 what |= EVBUFFER_ERROR;
895 goto err;
898 event_add(&bufev->ev_read, NULL);
899 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
900 return;
901 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
902 /*
903 * here we could implement a read pressure policy.
904 */
907 if (bufev->readcb != NULL)
908 (*bufev->readcb)(bufev, bufev->cbarg);
910 return;
912 retry:
913 event_add(&bufev->ev_read, NULL);
914 return;
916 err:
917 (*bufev->errorcb)(bufev, what, bufev->cbarg);
920 static void
921 client_tls_writecb(int fd, short event, void *d)
923 struct bufferevent *bufev = d;
924 struct client *client = bufev->cbarg;
925 ssize_t ret;
926 size_t len;
927 short what = EVBUFFER_WRITE;
929 if (event == EV_TIMEOUT) {
930 what |= EVBUFFER_TIMEOUT;
931 goto err;
934 if (EVBUFFER_LENGTH(bufev->output) != 0) {
935 ret = tls_write(client->ctx,
936 EVBUFFER_DATA(bufev->output),
937 EVBUFFER_LENGTH(bufev->output));
938 switch (ret) {
939 case TLS_WANT_POLLIN:
940 case TLS_WANT_POLLOUT:
941 goto retry;
942 case -1:
943 what |= EVBUFFER_ERROR;
944 goto err;
946 len = ret;
947 evbuffer_drain(bufev->output, len);
950 if (EVBUFFER_LENGTH(bufev->output) != 0)
951 event_add(&bufev->ev_write, NULL);
953 if (bufev->writecb != NULL &&
954 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
955 (*bufev->writecb)(bufev, bufev->cbarg);
956 return;
958 retry:
959 event_add(&bufev->ev_write, NULL);
960 return;
961 err:
962 log_err(client, "tls error: %s", tls_error(client->ctx));
963 (*bufev->errorcb)(bufev, what, bufev->cbarg);
966 static void
967 client_read(struct bufferevent *bev, void *d)
969 struct client *c = d;
970 struct evbuffer *src = EVBUFFER_INPUT(bev);
971 const char *parse_err = "invalid request";
972 char decoded[DOMAIN_NAME_LEN];
973 size_t len;
975 bufferevent_disable(bev, EVBUFFER_READ);
977 /*
978 * libevent2 can still somehow call this function, even
979 * though I never enable EV_READ in the bufferevent. If
980 * that's the case, bail out.
981 */
982 if (c->type != REQUEST_UNDECIDED)
983 return;
985 /* max url len + \r\n */
986 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
987 log_err(c, "too much data received");
988 start_reply(c, BAD_REQUEST, "bad request");
989 return;
992 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
993 if (c->req == NULL) {
994 /* not enough data yet. */
995 bufferevent_enable(bev, EVBUFFER_READ);
996 return;
998 c->reqlen = strlen(c->req);
999 if (c->reqlen > 1024+2) {
1000 log_err(c, "URL too long");
1001 start_reply(c, BAD_REQUEST, "bad request");
1002 return;
1005 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1006 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1007 log_err(c, "IRI parse error: %s", parse_err);
1008 start_reply(c, BAD_REQUEST, "bad request");
1009 return;
1012 if (apply_reverse_proxy(c))
1013 return;
1015 /* ignore the port number */
1016 if (strcmp(c->iri.schema, "gemini") ||
1017 strcmp(decoded, c->domain)) {
1018 start_reply(c, PROXY_REFUSED, "won't proxy request");
1019 return;
1022 if (apply_require_ca(c) ||
1023 apply_block_return(c)||
1024 apply_fastcgi(c))
1025 return;
1027 open_file(c);
1030 void
1031 client_write(struct bufferevent *bev, void *d)
1033 struct client *c = d;
1034 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1035 char nam[PATH_MAX];
1036 char buf[BUFSIZ];
1037 ssize_t r;
1039 switch (c->type) {
1040 case REQUEST_UNDECIDED:
1042 * Ignore spurious calls when we still don't have idea
1043 * what to do with the request.
1045 break;
1047 case REQUEST_FILE:
1048 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1049 log_warn(c, "read: %s", strerror(errno));
1050 client_error(bev, EVBUFFER_ERROR, c);
1051 return;
1052 } else if (r == 0) {
1053 client_close(c);
1054 return;
1055 } else if (r != sizeof(buf))
1056 c->type = REQUEST_DONE;
1057 bufferevent_write(bev, buf, r);
1058 break;
1060 case REQUEST_DIR:
1061 /* TODO: handle big big directories better */
1062 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1063 const char *sufx = "";
1065 encode_path(nam, sizeof(nam),
1066 c->dir[c->diroff]->d_name);
1067 if (c->dir[c->diroff]->d_type == DT_DIR)
1068 sufx = "/";
1069 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1070 free(c->dir[c->diroff]);
1072 free(c->dir);
1073 c->dir = NULL;
1075 c->type = REQUEST_DONE;
1077 event_add(&c->bev->ev_write, NULL);
1078 break;
1080 case REQUEST_FCGI:
1081 case REQUEST_PROXY:
1083 * Here we depend on fastcgi or proxy connection to
1084 * provide data.
1086 break;
1088 case REQUEST_DONE:
1089 if (EVBUFFER_LENGTH(out) == 0)
1090 client_close(c);
1091 break;
1095 static void
1096 client_error(struct bufferevent *bev, short error, void *d)
1098 struct client *c = d;
1100 c->type = REQUEST_DONE;
1102 if (error & EVBUFFER_TIMEOUT) {
1103 log_warn(c, "timeout reached, "
1104 "forcefully closing the connection");
1105 if (c->code == 0)
1106 start_reply(c, BAD_REQUEST, "timeout");
1107 else
1108 client_close(c);
1109 return;
1112 if (error & EVBUFFER_EOF) {
1113 client_close(c);
1114 return;
1117 log_err(c, "unknown bufferevent error %x", error);
1118 client_close(c);
1121 void
1122 start_reply(struct client *c, int code, const char *meta)
1124 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1125 const char *lang;
1126 int r, rr;
1128 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1130 c->code = code;
1131 c->meta = meta;
1133 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1134 if (r == -1)
1135 goto err;
1137 /* 2 digit status + space + 1024 max reply */
1138 if (r > 1027)
1139 goto overflow;
1141 if (c->type != REQUEST_FCGI &&
1142 c->type != REQUEST_PROXY &&
1143 !strcmp(meta, "text/gemini") &&
1144 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1145 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1146 if (rr == -1)
1147 goto err;
1148 if (r + rr > 1027)
1149 goto overflow;
1152 bufferevent_write(c->bev, "\r\n", 2);
1154 if (!vhost_disable_log(c->host, c->iri.path))
1155 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1157 if (code != 20)
1158 c->type = REQUEST_DONE;
1160 return;
1162 err:
1163 log_err(c, "evbuffer_add_printf error: no memory");
1164 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1165 client_close(c);
1166 return;
1168 overflow:
1169 log_warn(c, "reply header overflow");
1170 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1171 start_reply(c, TEMP_FAILURE, "internal error");
1174 static void
1175 client_close_ev(int fd, short event, void *d)
1177 struct client *c = d;
1179 switch (tls_close(c->ctx)) {
1180 case TLS_WANT_POLLIN:
1181 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1182 break;
1183 case TLS_WANT_POLLOUT:
1184 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1185 break;
1188 connected_clients--;
1190 free(c->req);
1192 tls_free(c->ctx);
1193 c->ctx = NULL;
1195 free(c->header);
1197 if (c->pfd != -1)
1198 close(c->pfd);
1200 if (c->dir != NULL)
1201 free(c->dir);
1203 close(c->fd);
1204 c->fd = -1;
1207 static void
1208 client_proxy_close(int fd, short event, void *d)
1210 struct tls *ctx = d;
1212 if (ctx == NULL) {
1213 close(fd);
1214 return;
1217 switch (tls_close(ctx)) {
1218 case TLS_WANT_POLLIN:
1219 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1220 break;
1221 case TLS_WANT_POLLOUT:
1222 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1223 break;
1226 tls_free(ctx);
1227 close(fd);
1230 void
1231 client_close(struct client *c)
1234 * We may end up calling client_close in various situations
1235 * and for the most unexpected reasons. Therefore, we need to
1236 * ensure that everything gets properly released once we reach
1237 * this point.
1240 SPLAY_REMOVE(client_tree_id, &clients, c);
1242 if (c->cgibev != NULL) {
1243 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1244 bufferevent_free(c->cgibev);
1245 c->cgibev = NULL;
1246 close(c->pfd);
1247 c->pfd = -1;
1250 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1251 bufferevent_free(c->bev);
1252 c->bev = NULL;
1254 if (c->proxyevset &&
1255 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1256 c->proxyevset = 0;
1257 event_del(&c->proxyev);
1260 if (c->pfd != -1 && c->proxyctx != NULL) {
1261 /* shut down the proxy TLS connection */
1262 client_proxy_close(c->pfd, 0, c->proxyctx);
1263 c->pfd = -1;
1266 if (c->proxybev != NULL)
1267 bufferevent_free(c->proxybev);
1269 client_close_ev(c->fd, 0, c);
1272 static void
1273 do_accept(int sock, short et, void *d)
1275 struct client *c;
1276 struct sockaddr_storage addr;
1277 struct sockaddr *saddr;
1278 socklen_t len;
1279 int fd;
1281 saddr = (struct sockaddr*)&addr;
1282 len = sizeof(addr);
1283 if ((fd = accept(sock, saddr, &len)) == -1) {
1284 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1285 errno == ECONNABORTED)
1286 return;
1287 fatal("accept");
1290 mark_nonblock(fd);
1292 c = xcalloc(1, sizeof(*c));
1293 c->id = ++server_client_id;
1294 c->fd = fd;
1295 c->pfd = -1;
1296 c->addr = addr;
1298 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1299 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1300 close(c->fd);
1301 free(c);
1302 return;
1305 SPLAY_INSERT(client_tree_id, &clients, c);
1306 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1307 connected_clients++;
1310 struct client *
1311 client_by_id(int id)
1313 struct client find;
1315 find.id = id;
1316 return SPLAY_FIND(client_tree_id, &clients, &find);
1319 static void
1320 handle_dispatch_imsg(int fd, short ev, void *d)
1322 struct imsgbuf *ibuf = d;
1323 struct imsg imsg;
1324 ssize_t n;
1326 if ((n = imsg_read(ibuf)) == -1) {
1327 if (errno == EAGAIN || errno == EWOULDBLOCK)
1328 return;
1329 fatal("imsg_read");
1332 if (n == 0)
1333 fatalx("connection closed.");
1335 for (;;) {
1336 if ((n = imsg_get(ibuf, &imsg)) == -1)
1337 fatal("imsg_get");
1338 if (n == 0)
1339 return;
1341 switch (imsg.hdr.type) {
1342 case IMSG_QUIT:
1344 * Don't call event_loopbreak since we want to
1345 * finish handling the ongoing connections.
1347 shutting_down = 1;
1349 event_del(&e4);
1350 if (has_ipv6)
1351 event_del(&e6);
1352 if (has_siginfo)
1353 signal_del(&siginfo);
1354 event_del(&imsgev);
1355 signal_del(&sigusr2);
1356 break;
1357 default:
1358 fatalx("Unknown message %d", imsg.hdr.type);
1360 imsg_free(&imsg);
1364 static void
1365 handle_siginfo(int fd, short ev, void *d)
1367 log_info(NULL, "%d connected clients", connected_clients);
1370 static void
1371 loop(int sock4, int sock6, struct imsgbuf *ibuf)
1373 SPLAY_INIT(&clients);
1375 event_init();
1377 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1378 event_add(&e4, NULL);
1380 if (sock6 != -1) {
1381 has_ipv6 = 1;
1382 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1383 event_add(&e6, NULL);
1386 if (ibuf) {
1387 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1388 handle_dispatch_imsg, ibuf);
1389 event_add(&imsgev, NULL);
1392 #ifdef SIGINFO
1393 has_siginfo = 1;
1394 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1395 signal_add(&siginfo, NULL);
1396 #endif
1397 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1398 signal_add(&sigusr2, NULL);
1400 sandbox_server_process();
1401 event_dispatch();
1402 _exit(0);
1405 static void
1406 add_keypair(struct vhost *h, struct tls_config *conf)
1408 if (*h->ocsp == '\0') {
1409 if (tls_config_add_keypair_file(conf, h->cert, h->key) == -1)
1410 fatalx("failed to load the keypair (%s, %s): %s",
1411 h->cert, h->key, tls_config_error(conf));
1412 } else {
1413 if (tls_config_add_keypair_ocsp_file(conf, h->cert, h->key,
1414 h->ocsp) == -1)
1415 fatalx("failed to load the keypair (%s, %s, %s): %s",
1416 h->cert, h->key, h->ocsp,
1417 tls_config_error(conf));
1422 * XXX: in a ideal privsep world, this is done by the parent process
1423 * and its content sent to us.
1425 static void
1426 setup_tls(void)
1428 struct tls_config *tlsconf;
1429 struct vhost *h;
1431 if ((tlsconf = tls_config_new()) == NULL)
1432 fatal("tls_config_new");
1434 /* optionally accept client certs, but don't try to verify them */
1435 tls_config_verify_client_optional(tlsconf);
1436 tls_config_insecure_noverifycert(tlsconf);
1438 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
1439 fatalx("tls_config_set_protocols: %s",
1440 tls_config_error(tlsconf));
1442 h = TAILQ_FIRST(&hosts);
1444 log_warn(NULL, "loading %s, %s, %s", h->cert, h->key, h->ocsp);
1446 /* we need to set something, then we can add how many key we want */
1447 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
1448 fatalx("tls_config_set_keypair_file failed for (%s, %s): %s",
1449 h->cert, h->key, tls_config_error(tlsconf));
1451 /* same for OCSP */
1452 if (*h->ocsp != '\0' &&
1453 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
1454 fatalx("tls_config_set_ocsp_staple_file failed for (%s): %s",
1455 h->ocsp, tls_config_error(tlsconf));
1457 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1458 add_keypair(h, tlsconf);
1460 if ((ctx = tls_server()) == NULL)
1461 fatal("tls_server failure");
1463 if (tls_configure(ctx, tlsconf) == -1)
1464 fatalx("tls_configure: %s", tls_error(ctx));
1466 tls_config_free(tlsconf);
1469 static void
1470 load_vhosts(void)
1472 struct vhost *h;
1473 struct location *l;
1475 TAILQ_FOREACH(h, &hosts, vhosts) {
1476 TAILQ_FOREACH(l, &h->locations, locations) {
1477 if (*l->dir == '\0')
1478 continue;
1479 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1480 if (l->dirfd == -1)
1481 fatal("open %s for domain %s", l->dir,
1482 h->domain);
1487 int
1488 server_main(struct imsgbuf *ibuf, int sock4, int sock6)
1491 * setup tls before dropping privileges: we don't want user
1492 * to put private certs inside the chroot.
1494 setup_tls();
1495 drop_priv();
1496 if (load_default_mime(&conf.mime) == -1)
1497 fatal("can't load default mime");
1498 sort_mime(&conf.mime);
1499 load_vhosts();
1500 loop(sock4, sock6, ibuf);
1501 return 0;
1504 int
1505 client_tree_cmp(struct client *a, struct client *b)
1507 if (a->id == b->id)
1508 return 0;
1509 else if (a->id < b->id)
1510 return -1;
1511 else
1512 return +1;
1515 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)