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 #define MIN(a, b) ((a) < (b) ? (a) : (b))
33 int shutting_down;
35 static struct tls *ctx;
37 static struct event e4, e6, imsgev, siginfo, sigusr2;
38 static int has_ipv6, has_siginfo;
40 int connected_clients;
42 static inline int matches(const char*, const char*);
44 static int check_path(struct client*, const char*, int*);
45 static void open_file(struct client*);
46 static void handle_handshake(int, short, void*);
47 static const char *strip_path(const char*, int);
48 static void fmt_sbuf(const char*, struct client*, const char*);
49 static int apply_block_return(struct client*);
50 static int check_matching_certificate(X509_STORE *, struct client *);
51 static int apply_reverse_proxy(struct client *);
52 static int apply_fastcgi(struct client*);
53 static int apply_require_ca(struct client*);
54 static void open_dir(struct client*);
55 static void redirect_canonical_dir(struct client*);
57 static void client_tls_readcb(int, short, void *);
58 static void client_tls_writecb(int, short, void *);
60 static void client_read(struct bufferevent *, void *);
61 void client_write(struct bufferevent *, void *);
62 static void client_error(struct bufferevent *, short, void *);
64 static void client_close_ev(int, short, void *);
66 static void do_accept(int, short, void*);
68 static void handle_dispatch_imsg(int, short, void *);
69 static void handle_siginfo(int, short, void*);
71 static uint32_t server_client_id;
73 struct client_tree_id clients;
75 static inline int
76 matches(const char *pattern, const char *path)
77 {
78 if (*path == '/')
79 path++;
80 return !fnmatch(pattern, path, 0);
81 }
83 const char *
84 vhost_lang(struct vhost *v, const char *path)
85 {
86 struct location *loc;
88 if (v == NULL || path == NULL)
89 return NULL;
91 loc = TAILQ_FIRST(&v->locations);
92 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
93 if (*loc->lang != '\0') {
94 if (matches(loc->match, path))
95 return loc->lang;
96 }
97 }
99 loc = TAILQ_FIRST(&v->locations);
100 if (*loc->lang == '\0')
101 return NULL;
102 return loc->lang;
105 const char *
106 vhost_default_mime(struct vhost *v, const char *path)
108 struct location *loc;
109 const char *default_mime = "application/octet-stream";
111 if (v == NULL || path == NULL)
112 return default_mime;
114 loc = TAILQ_FIRST(&v->locations);
115 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
116 if (*loc->default_mime != '\0') {
117 if (matches(loc->match, path))
118 return loc->default_mime;
122 loc = TAILQ_FIRST(&v->locations);
123 if (*loc->default_mime != '\0')
124 return loc->default_mime;
125 return default_mime;
128 const char *
129 vhost_index(struct vhost *v, const char *path)
131 struct location *loc;
132 const char *index = "index.gmi";
134 if (v == NULL || path == NULL)
135 return index;
137 loc = TAILQ_FIRST(&v->locations);
138 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
139 if (*loc->index != '\0') {
140 if (matches(loc->match, path))
141 return loc->index;
145 loc = TAILQ_FIRST(&v->locations);
146 if (*loc->index != '\0')
147 return loc->index;
148 return index;
151 int
152 vhost_auto_index(struct vhost *v, const char *path)
154 struct location *loc;
156 if (v == NULL || path == NULL)
157 return 0;
159 loc = TAILQ_FIRST(&v->locations);
160 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
161 if (loc->auto_index != 0) {
162 if (matches(loc->match, path))
163 return loc->auto_index == 1;
167 loc = TAILQ_FIRST(&v->locations);
168 return loc->auto_index == 1;
171 int
172 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
174 struct location *loc;
176 if (v == NULL || path == NULL)
177 return 0;
179 loc = TAILQ_FIRST(&v->locations);
180 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
181 if (loc->block_code != 0) {
182 if (matches(loc->match, path)) {
183 *code = loc->block_code;
184 *fmt = loc->block_fmt;
185 return 1;
190 loc = TAILQ_FIRST(&v->locations);
191 *code = loc->block_code;
192 *fmt = loc->block_fmt;
193 return loc->block_code != 0;
196 int
197 vhost_fastcgi(struct vhost *v, const char *path)
199 struct location *loc;
201 if (v == NULL || path == NULL)
202 return -1;
204 loc = TAILQ_FIRST(&v->locations);
205 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
206 if (loc->fcgi != -1)
207 if (matches(loc->match, path))
208 return loc->fcgi;
211 loc = TAILQ_FIRST(&v->locations);
212 return loc->fcgi;
215 int
216 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
218 struct location *loc;
219 size_t l = 0;
221 if (v == NULL || path == NULL)
222 return -1;
224 loc = TAILQ_FIRST(&v->locations);
225 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
226 l++;
227 if (loc->dirfd != -1)
228 if (matches(loc->match, path)) {
229 *retloc = l;
230 return loc->dirfd;
234 *retloc = 0;
235 loc = TAILQ_FIRST(&v->locations);
236 return loc->dirfd;
239 int
240 vhost_strip(struct vhost *v, const char *path)
242 struct location *loc;
244 if (v == NULL || path == NULL)
245 return 0;
247 loc = TAILQ_FIRST(&v->locations);
248 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
249 if (loc->strip != 0) {
250 if (matches(loc->match, path))
251 return loc->strip;
255 loc = TAILQ_FIRST(&v->locations);
256 return loc->strip;
259 X509_STORE *
260 vhost_require_ca(struct vhost *v, const char *path)
262 struct location *loc;
264 if (v == NULL || path == NULL)
265 return NULL;
267 loc = TAILQ_FIRST(&v->locations);
268 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
269 if (loc->reqca != NULL) {
270 if (matches(loc->match, path))
271 return loc->reqca;
275 loc = TAILQ_FIRST(&v->locations);
276 return loc->reqca;
279 int
280 vhost_disable_log(struct vhost *v, const char *path)
282 struct location *loc;
284 if (v == NULL || path == NULL)
285 return 0;
287 loc = TAILQ_FIRST(&v->locations);
288 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
289 if (loc->disable_log && matches(loc->match, path))
290 return 1;
293 loc = TAILQ_FIRST(&v->locations);
294 return loc->disable_log;
297 static int
298 check_path(struct client *c, const char *path, int *fd)
300 struct stat sb;
301 const char *p;
302 int dirfd, strip;
304 assert(path != NULL);
306 /*
307 * in send_dir we add an initial / (to be redirect-friendly),
308 * but here we want to skip it
309 */
310 if (*path == '/')
311 path++;
313 strip = vhost_strip(c->host, path);
314 p = strip_path(path, strip);
316 if (*p == '/')
317 p = p+1;
318 if (*p == '\0')
319 p = ".";
321 dirfd = vhost_dirfd(c->host, path, &c->loc);
322 log_debug(c, "check_path: strip=%d path=%s original=%s",
323 strip, p, path);
324 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
325 if (errno == EACCES)
326 log_info(c, "can't open %s: %s", p, strerror(errno));
327 return FILE_MISSING;
330 if (fstat(*fd, &sb) == -1) {
331 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
332 return FILE_MISSING;
335 if (S_ISDIR(sb.st_mode))
336 return FILE_DIRECTORY;
338 return FILE_EXISTS;
341 static void
342 open_file(struct client *c)
344 switch (check_path(c, c->iri.path, &c->pfd)) {
345 case FILE_EXISTS:
346 c->type = REQUEST_FILE;
347 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
348 return;
350 case FILE_DIRECTORY:
351 open_dir(c);
352 return;
354 case FILE_MISSING:
355 start_reply(c, NOT_FOUND, "not found");
356 return;
358 default:
359 /* unreachable */
360 abort();
364 void
365 mark_nonblock(int fd)
367 int flags;
369 if ((flags = fcntl(fd, F_GETFL)) == -1)
370 fatal("fcntl(F_GETFL): %s", strerror(errno));
371 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
372 fatal("fcntl(F_SETFL): %s", strerror(errno));
375 static void
376 handle_handshake(int fd, short ev, void *d)
378 struct client *c = d;
379 struct vhost *h;
380 struct alist *a;
381 const char *servname;
382 const char *parse_err = "unknown error";
384 switch (tls_handshake(c->ctx)) {
385 case 0: /* success */
386 case -1: /* already handshaked */
387 break;
388 case TLS_WANT_POLLIN:
389 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
390 return;
391 case TLS_WANT_POLLOUT:
392 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
393 return;
394 default:
395 /* unreachable */
396 abort();
399 c->bev = bufferevent_new(fd, client_read, client_write,
400 client_error, c);
401 if (c->bev == NULL)
402 fatal("%s: failed to allocate client buffer: %s",
403 __func__, strerror(errno));
405 event_set(&c->bev->ev_read, c->fd, EV_READ,
406 client_tls_readcb, c->bev);
407 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
408 client_tls_writecb, c->bev);
410 #if HAVE_LIBEVENT2
411 evbuffer_unfreeze(c->bev->input, 0);
412 evbuffer_unfreeze(c->bev->output, 1);
413 #endif
415 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
416 log_debug(c, "handshake: missing SNI");
417 goto err;
420 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
421 log_info(c, "puny_decode: %s", parse_err);
422 goto err;
425 TAILQ_FOREACH(h, &hosts, vhosts) {
426 if (matches(h->domain, c->domain))
427 goto found;
428 TAILQ_FOREACH(a, &h->aliases, aliases) {
429 if (matches(a->alias, c->domain))
430 goto found;
434 found:
435 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
436 servname != NULL ? servname : "(null)",
437 c->domain,
438 h != NULL ? h->domain : "(null)");
440 if (h != NULL) {
441 c->host = h;
442 bufferevent_enable(c->bev, EV_READ);
443 return;
446 err:
447 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
450 static const char *
451 strip_path(const char *path, int strip)
453 char *t;
455 while (strip > 0) {
456 if ((t = strchr(path, '/')) == NULL) {
457 path = strchr(path, '\0');
458 break;
460 path = t;
461 strip--;
464 return path;
467 static void
468 fmt_sbuf(const char *fmt, struct client *c, const char *path)
470 size_t i;
471 char buf[32];
473 memset(buf, 0, sizeof(buf));
474 for (i = 0; *fmt; ++fmt) {
475 if (i == sizeof(buf)-1 || *fmt == '%') {
476 strlcat(c->sbuf, buf, sizeof(c->sbuf));
477 memset(buf, 0, sizeof(buf));
478 i = 0;
481 if (*fmt != '%') {
482 buf[i++] = *fmt;
483 continue;
486 switch (*++fmt) {
487 case '%':
488 strlcat(c->sbuf, "%", sizeof(c->sbuf));
489 break;
490 case 'p':
491 if (*path != '/')
492 strlcat(c->sbuf, "/", sizeof(c->sbuf));
493 strlcat(c->sbuf, path, sizeof(c->sbuf));
494 break;
495 case 'q':
496 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
497 break;
498 case 'P':
499 snprintf(buf, sizeof(buf), "%d", conf.port);
500 strlcat(c->sbuf, buf, sizeof(c->sbuf));
501 memset(buf, 0, sizeof(buf));
502 break;
503 case 'N':
504 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
505 break;
506 default:
507 fatal("%s: unknown fmt specifier %c",
508 __func__, *fmt);
512 if (i != 0)
513 strlcat(c->sbuf, buf, sizeof(c->sbuf));
516 /* 1 if a matching `block return' (and apply it), 0 otherwise */
517 static int
518 apply_block_return(struct client *c)
520 const char *fmt, *path;
521 int code;
523 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
524 return 0;
526 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
527 fmt_sbuf(fmt, c, path);
529 start_reply(c, code, c->sbuf);
530 return 1;
533 static struct proxy *
534 matched_proxy(struct client *c)
536 struct proxy *p;
537 const char *proto;
538 const char *host;
539 const char *port;
541 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
542 if (*(proto = p->match_proto) == '\0')
543 proto = "gemini";
544 if (*(host = p->match_host) == '\0')
545 host = "*";
546 if (*(port = p->match_port) == '\0')
547 port = "*";
549 if (matches(proto, c->iri.schema) &&
550 matches(host, c->domain) &&
551 matches(port, c->iri.port))
552 return p;
555 return NULL;
558 static int
559 check_matching_certificate(X509_STORE *store, struct client *c)
561 const uint8_t *cert;
562 size_t len;
564 if (!tls_peer_cert_provided(c->ctx)) {
565 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
566 return 1;
569 cert = tls_peer_cert_chain_pem(c->ctx, &len);
570 if (!validate_against_ca(store, cert, len)) {
571 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
572 return 1;
575 return 0;
578 static int
579 proxy_socket(struct client *c, const char *host, const char *port)
581 struct addrinfo hints, *res, *res0;
582 int r, sock;
584 memset(&hints, 0, sizeof(hints));
585 hints.ai_family = AF_UNSPEC;
586 hints.ai_socktype = SOCK_STREAM;
588 /* XXX: asr_run? :> */
589 r = getaddrinfo(host, port, &hints, &res0);
590 if (r != 0) {
591 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
592 host, port, gai_strerror(r));
593 return -1;
596 for (res = res0; res; res = res->ai_next) {
597 sock = socket(res->ai_family, res->ai_socktype,
598 res->ai_protocol);
599 if (sock == -1)
600 continue;
602 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
603 close(sock);
604 sock = -1;
605 continue;
608 break;
611 freeaddrinfo(res0);
613 if (sock == -1)
614 log_warn(c, "can't connect to %s:%s", host, port);
616 return sock;
619 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
620 static int
621 apply_reverse_proxy(struct client *c)
623 struct proxy *p;
625 if ((p = matched_proxy(c)) == NULL)
626 return 0;
628 c->proxy = p;
630 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
631 return 1;
633 log_debug(c, "opening proxy connection for %s:%s",
634 p->host, p->port);
636 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
637 start_reply(c, PROXY_ERROR, "proxy error");
638 return 1;
641 mark_nonblock(c->pfd);
642 if (proxy_init(c) == -1)
643 start_reply(c, PROXY_ERROR, "proxy error");
645 return 1;
648 static int
649 fcgi_open_sock(struct fcgi *f)
651 struct sockaddr_un addr;
652 int fd;
654 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
655 log_err(NULL, "socket: %s", strerror(errno));
656 return -1;
659 memset(&addr, 0, sizeof(addr));
660 addr.sun_family = AF_UNIX;
661 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
663 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
664 log_warn(NULL, "failed to connect to %s: %s", f->path,
665 strerror(errno));
666 close(fd);
667 return -1;
670 return fd;
673 static int
674 fcgi_open_conn(struct fcgi *f)
676 struct addrinfo hints, *servinfo, *p;
677 int r, sock;
679 memset(&hints, 0, sizeof(hints));
680 hints.ai_family = AF_UNSPEC;
681 hints.ai_socktype = SOCK_STREAM;
682 hints.ai_flags = AI_ADDRCONFIG;
684 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
685 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
686 gai_strerror(r));
687 return -1;
690 for (p = servinfo; p != NULL; p = p->ai_next) {
691 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
692 if (sock == -1)
693 continue;
694 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
695 close(sock);
696 continue;
698 break;
701 if (p == NULL) {
702 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
703 sock = -1;
706 freeaddrinfo(servinfo);
707 return sock;
710 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
711 static int
712 apply_fastcgi(struct client *c)
714 int id;
715 struct fcgi *f;
717 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
718 return 0;
720 f = &fcgi[id];
722 log_debug(c, "opening fastcgi connection for (%s,%s)",
723 f->path, f->port);
725 if (*f->port != '\0')
726 c->pfd = fcgi_open_sock(f);
727 else
728 c->pfd = fcgi_open_conn(f);
730 if (c->pfd == -1) {
731 start_reply(c, CGI_ERROR, "CGI error");
732 return 1;
735 mark_nonblock(c->pfd);
737 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
738 fcgi_error, c);
739 if (c->cgibev == NULL) {
740 start_reply(c, TEMP_FAILURE, "internal server error");
741 return 1;
744 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
745 fcgi_req(c);
747 return 1;
750 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
751 static int
752 apply_require_ca(struct client *c)
754 X509_STORE *store;
756 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
757 return 0;
758 return check_matching_certificate(store, c);
761 static void
762 open_dir(struct client *c)
764 size_t len;
765 int dirfd, root;
766 char *before_file;
768 log_debug(c, "in open_dir");
770 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
772 len = strlen(c->iri.path);
773 if (len > 0 && !ends_with(c->iri.path, "/")) {
774 redirect_canonical_dir(c);
775 return;
778 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
779 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
780 if (!ends_with(c->sbuf, "/"))
781 strlcat(c->sbuf, "/", sizeof(c->sbuf));
782 before_file = strchr(c->sbuf, '\0');
783 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
784 sizeof(c->sbuf));
785 if (len >= sizeof(c->sbuf)) {
786 start_reply(c, TEMP_FAILURE, "internal server error");
787 return;
790 c->iri.path = c->sbuf;
792 /* close later unless we have to generate the dir listing */
793 dirfd = c->pfd;
794 c->pfd = -1;
796 switch (check_path(c, c->iri.path, &c->pfd)) {
797 case FILE_EXISTS:
798 c->type = REQUEST_FILE;
799 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
800 break;
802 case FILE_DIRECTORY:
803 start_reply(c, TEMP_REDIRECT, c->sbuf);
804 break;
806 case FILE_MISSING:
807 *before_file = '\0';
809 if (!vhost_auto_index(c->host, c->iri.path)) {
810 start_reply(c, NOT_FOUND, "not found");
811 break;
814 c->type = REQUEST_DIR;
816 c->dirlen = scandir_fd(dirfd, &c->dir,
817 root ? select_non_dotdot : select_non_dot,
818 alphasort);
819 if (c->dirlen == -1) {
820 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
821 c->pfd, c->host->domain, c->iri.path, strerror(errno));
822 start_reply(c, TEMP_FAILURE, "internal server error");
823 return;
825 c->diroff = 0;
826 c->off = 0;
828 start_reply(c, SUCCESS, "text/gemini");
829 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
830 "# Index of %s\n\n", c->iri.path);
831 return;
833 default:
834 /* unreachable */
835 abort();
838 close(dirfd);
841 static void
842 redirect_canonical_dir(struct client *c)
844 size_t len;
846 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
847 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
848 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
850 if (len >= sizeof(c->sbuf)) {
851 start_reply(c, TEMP_FAILURE, "internal server error");
852 return;
855 start_reply(c, TEMP_REDIRECT, c->sbuf);
858 static void
859 client_tls_readcb(int fd, short event, void *d)
861 struct bufferevent *bufev = d;
862 struct client *client = bufev->cbarg;
863 ssize_t ret;
864 size_t len;
865 int what = EVBUFFER_READ;
866 int howmuch = IBUF_READ_SIZE;
867 char buf[IBUF_READ_SIZE];
869 if (event == EV_TIMEOUT) {
870 what |= EVBUFFER_TIMEOUT;
871 goto err;
874 if (bufev->wm_read.high != 0)
875 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
877 switch (ret = tls_read(client->ctx, buf, howmuch)) {
878 case TLS_WANT_POLLIN:
879 case TLS_WANT_POLLOUT:
880 goto retry;
881 case -1:
882 what |= EVBUFFER_ERROR;
883 goto err;
885 len = ret;
887 if (len == 0) {
888 what |= EVBUFFER_EOF;
889 goto err;
892 if (evbuffer_add(bufev->input, buf, len) == -1) {
893 what |= EVBUFFER_ERROR;
894 goto err;
897 event_add(&bufev->ev_read, NULL);
898 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
899 return;
900 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
901 /*
902 * here we could implement a read pressure policy.
903 */
906 if (bufev->readcb != NULL)
907 (*bufev->readcb)(bufev, bufev->cbarg);
909 return;
911 retry:
912 event_add(&bufev->ev_read, NULL);
913 return;
915 err:
916 (*bufev->errorcb)(bufev, what, bufev->cbarg);
919 static void
920 client_tls_writecb(int fd, short event, void *d)
922 struct bufferevent *bufev = d;
923 struct client *client = bufev->cbarg;
924 ssize_t ret;
925 size_t len;
926 short what = EVBUFFER_WRITE;
928 if (event == EV_TIMEOUT) {
929 what |= EVBUFFER_TIMEOUT;
930 goto err;
933 if (EVBUFFER_LENGTH(bufev->output) != 0) {
934 ret = tls_write(client->ctx,
935 EVBUFFER_DATA(bufev->output),
936 EVBUFFER_LENGTH(bufev->output));
937 switch (ret) {
938 case TLS_WANT_POLLIN:
939 case TLS_WANT_POLLOUT:
940 goto retry;
941 case -1:
942 what |= EVBUFFER_ERROR;
943 goto err;
945 len = ret;
946 evbuffer_drain(bufev->output, len);
949 if (EVBUFFER_LENGTH(bufev->output) != 0)
950 event_add(&bufev->ev_write, NULL);
952 if (bufev->writecb != NULL &&
953 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
954 (*bufev->writecb)(bufev, bufev->cbarg);
955 return;
957 retry:
958 event_add(&bufev->ev_write, NULL);
959 return;
960 err:
961 log_err(client, "tls error: %s", tls_error(client->ctx));
962 (*bufev->errorcb)(bufev, what, bufev->cbarg);
965 static void
966 client_read(struct bufferevent *bev, void *d)
968 struct client *c = d;
969 struct evbuffer *src = EVBUFFER_INPUT(bev);
970 const char *parse_err = "invalid request";
971 char decoded[DOMAIN_NAME_LEN];
972 size_t len;
974 bufferevent_disable(bev, EVBUFFER_READ);
976 /*
977 * libevent2 can still somehow call this function, even
978 * though I never enable EV_READ in the bufferevent. If
979 * that's the case, bail out.
980 */
981 if (c->type != REQUEST_UNDECIDED)
982 return;
984 /* max url len + \r\n */
985 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
986 log_err(c, "too much data received");
987 start_reply(c, BAD_REQUEST, "bad request");
988 return;
991 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
992 if (c->req == NULL) {
993 /* not enough data yet. */
994 bufferevent_enable(bev, EVBUFFER_READ);
995 return;
997 c->reqlen = strlen(c->req);
998 if (c->reqlen > 1024+2) {
999 log_err(c, "URL too long");
1000 start_reply(c, BAD_REQUEST, "bad request");
1001 return;
1004 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1005 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1006 log_err(c, "IRI parse error: %s", parse_err);
1007 start_reply(c, BAD_REQUEST, "bad request");
1008 return;
1011 if (apply_reverse_proxy(c))
1012 return;
1014 /* ignore the port number */
1015 if (strcmp(c->iri.schema, "gemini") ||
1016 strcmp(decoded, c->domain)) {
1017 start_reply(c, PROXY_REFUSED, "won't proxy request");
1018 return;
1021 if (apply_require_ca(c) ||
1022 apply_block_return(c)||
1023 apply_fastcgi(c))
1024 return;
1026 open_file(c);
1029 void
1030 client_write(struct bufferevent *bev, void *d)
1032 struct client *c = d;
1033 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1034 char nam[PATH_MAX];
1035 char buf[BUFSIZ];
1036 ssize_t r;
1038 switch (c->type) {
1039 case REQUEST_UNDECIDED:
1041 * Ignore spurious calls when we still don't have idea
1042 * what to do with the request.
1044 break;
1046 case REQUEST_FILE:
1047 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1048 log_warn(c, "read: %s", strerror(errno));
1049 client_error(bev, EVBUFFER_ERROR, c);
1050 return;
1051 } else if (r == 0) {
1052 client_close(c);
1053 return;
1054 } else if (r != sizeof(buf))
1055 c->type = REQUEST_DONE;
1056 bufferevent_write(bev, buf, r);
1057 break;
1059 case REQUEST_DIR:
1060 /* TODO: handle big big directories better */
1061 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1062 const char *sufx = "";
1064 encode_path(nam, sizeof(nam),
1065 c->dir[c->diroff]->d_name);
1066 if (c->dir[c->diroff]->d_type == DT_DIR)
1067 sufx = "/";
1068 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1069 free(c->dir[c->diroff]);
1071 free(c->dir);
1072 c->dir = NULL;
1074 c->type = REQUEST_DONE;
1076 event_add(&c->bev->ev_write, NULL);
1077 break;
1079 case REQUEST_FCGI:
1080 case REQUEST_PROXY:
1082 * Here we depend on fastcgi or proxy connection to
1083 * provide data.
1085 break;
1087 case REQUEST_DONE:
1088 if (EVBUFFER_LENGTH(out) == 0)
1089 client_close(c);
1090 break;
1094 static void
1095 client_error(struct bufferevent *bev, short error, void *d)
1097 struct client *c = d;
1099 c->type = REQUEST_DONE;
1101 if (error & EVBUFFER_TIMEOUT) {
1102 log_warn(c, "timeout reached, "
1103 "forcefully closing the connection");
1104 if (c->code == 0)
1105 start_reply(c, BAD_REQUEST, "timeout");
1106 else
1107 client_close(c);
1108 return;
1111 if (error & EVBUFFER_EOF) {
1112 client_close(c);
1113 return;
1116 log_err(c, "unknown bufferevent error %x", error);
1117 client_close(c);
1120 void
1121 start_reply(struct client *c, int code, const char *meta)
1123 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1124 const char *lang;
1125 int r, rr;
1127 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1129 c->code = code;
1130 c->meta = meta;
1132 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1133 if (r == -1)
1134 goto err;
1136 /* 2 digit status + space + 1024 max reply */
1137 if (r > 1027)
1138 goto overflow;
1140 if (c->type != REQUEST_FCGI &&
1141 c->type != REQUEST_PROXY &&
1142 !strcmp(meta, "text/gemini") &&
1143 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1144 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1145 if (rr == -1)
1146 goto err;
1147 if (r + rr > 1027)
1148 goto overflow;
1151 bufferevent_write(c->bev, "\r\n", 2);
1153 if (!vhost_disable_log(c->host, c->iri.path))
1154 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1156 if (code != 20)
1157 c->type = REQUEST_DONE;
1159 return;
1161 err:
1162 log_err(c, "evbuffer_add_printf error: no memory");
1163 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1164 client_close(c);
1165 return;
1167 overflow:
1168 log_warn(c, "reply header overflow");
1169 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1170 start_reply(c, TEMP_FAILURE, "internal error");
1173 static void
1174 client_close_ev(int fd, short event, void *d)
1176 struct client *c = d;
1178 switch (tls_close(c->ctx)) {
1179 case TLS_WANT_POLLIN:
1180 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1181 break;
1182 case TLS_WANT_POLLOUT:
1183 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1184 break;
1187 connected_clients--;
1189 free(c->req);
1191 tls_free(c->ctx);
1192 c->ctx = NULL;
1194 free(c->header);
1196 if (c->pfd != -1)
1197 close(c->pfd);
1199 if (c->dir != NULL)
1200 free(c->dir);
1202 close(c->fd);
1203 c->fd = -1;
1206 static void
1207 client_proxy_close(int fd, short event, void *d)
1209 struct tls *ctx = d;
1211 if (ctx == NULL) {
1212 close(fd);
1213 return;
1216 switch (tls_close(ctx)) {
1217 case TLS_WANT_POLLIN:
1218 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1219 break;
1220 case TLS_WANT_POLLOUT:
1221 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1222 break;
1225 tls_free(ctx);
1226 close(fd);
1229 void
1230 client_close(struct client *c)
1233 * We may end up calling client_close in various situations
1234 * and for the most unexpected reasons. Therefore, we need to
1235 * ensure that everything gets properly released once we reach
1236 * this point.
1239 SPLAY_REMOVE(client_tree_id, &clients, c);
1241 if (c->cgibev != NULL) {
1242 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1243 bufferevent_free(c->cgibev);
1244 c->cgibev = NULL;
1245 close(c->pfd);
1246 c->pfd = -1;
1249 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1250 bufferevent_free(c->bev);
1251 c->bev = NULL;
1253 if (c->proxyevset &&
1254 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1255 c->proxyevset = 0;
1256 event_del(&c->proxyev);
1259 if (c->pfd != -1 && c->proxyctx != NULL) {
1260 /* shut down the proxy TLS connection */
1261 client_proxy_close(c->pfd, 0, c->proxyctx);
1262 c->pfd = -1;
1265 if (c->proxybev != NULL)
1266 bufferevent_free(c->proxybev);
1268 client_close_ev(c->fd, 0, c);
1271 static void
1272 do_accept(int sock, short et, void *d)
1274 struct client *c;
1275 struct sockaddr_storage addr;
1276 struct sockaddr *saddr;
1277 socklen_t len;
1278 int fd;
1280 saddr = (struct sockaddr*)&addr;
1281 len = sizeof(addr);
1282 if ((fd = accept(sock, saddr, &len)) == -1) {
1283 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1284 errno == ECONNABORTED)
1285 return;
1286 fatal("accept: %s", strerror(errno));
1289 mark_nonblock(fd);
1291 c = xcalloc(1, sizeof(*c));
1292 c->id = ++server_client_id;
1293 c->fd = fd;
1294 c->pfd = -1;
1295 c->addr = addr;
1297 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1298 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1299 close(c->fd);
1300 free(c);
1301 return;
1304 SPLAY_INSERT(client_tree_id, &clients, c);
1305 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1306 connected_clients++;
1309 struct client *
1310 client_by_id(int id)
1312 struct client find;
1314 find.id = id;
1315 return SPLAY_FIND(client_tree_id, &clients, &find);
1318 static void
1319 handle_dispatch_imsg(int fd, short ev, void *d)
1321 struct imsgbuf *ibuf = d;
1322 struct imsg imsg;
1323 ssize_t n;
1325 if ((n = imsg_read(ibuf)) == -1) {
1326 if (errno == EAGAIN || errno == EWOULDBLOCK)
1327 return;
1328 fatal("imsg_read");
1331 if (n == 0)
1332 fatal("connection closed."); /* XXX: fatalx */
1334 for (;;) {
1335 if ((n = imsg_get(ibuf, &imsg)) == -1)
1336 fatal("imsg_get");
1337 if (n == 0)
1338 return;
1340 switch (imsg.hdr.type) {
1341 case IMSG_QUIT:
1343 * Don't call event_loopbreak since we want to
1344 * finish handling the ongoing connections.
1346 shutting_down = 1;
1348 event_del(&e4);
1349 if (has_ipv6)
1350 event_del(&e6);
1351 if (has_siginfo)
1352 signal_del(&siginfo);
1353 event_del(&imsgev);
1354 signal_del(&sigusr2);
1355 break;
1356 default:
1357 /* XXX: fatalx */
1358 fatal("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 void
1371 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1373 ctx = ctx_;
1375 SPLAY_INIT(&clients);
1377 event_init();
1379 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1380 event_add(&e4, NULL);
1382 if (sock6 != -1) {
1383 has_ipv6 = 1;
1384 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1385 event_add(&e6, NULL);
1388 if (ibuf) {
1389 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1390 handle_dispatch_imsg, ibuf);
1391 event_add(&imsgev, NULL);
1394 #ifdef SIGINFO
1395 has_siginfo = 1;
1396 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1397 signal_add(&siginfo, NULL);
1398 #endif
1399 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1400 signal_add(&sigusr2, NULL);
1402 sandbox_server_process(conf.can_open_sockets);
1403 event_dispatch();
1404 _exit(0);
1407 int
1408 client_tree_cmp(struct client *a, struct client *b)
1410 if (a->id == b->id)
1411 return 0;
1412 else if (a->id < b->id)
1413 return -1;
1414 else
1415 return +1;
1418 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)