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_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
69 static void handle_dispatch_imsg(int, short, void *);
70 static void handle_siginfo(int, short, void*);
72 static imsg_handlerfn *handlers[] = {
73 [IMSG_QUIT] = handle_imsg_quit,
74 };
76 static uint32_t server_client_id;
78 struct client_tree_id clients;
80 static inline int
81 matches(const char *pattern, const char *path)
82 {
83 if (*path == '/')
84 path++;
85 return !fnmatch(pattern, path, 0);
86 }
88 const char *
89 vhost_lang(struct vhost *v, const char *path)
90 {
91 struct location *loc;
93 if (v == NULL || path == NULL)
94 return NULL;
96 loc = TAILQ_FIRST(&v->locations);
97 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
98 if (loc->lang != NULL) {
99 if (matches(loc->match, path))
100 return loc->lang;
104 return TAILQ_FIRST(&v->locations)->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 != NULL) {
119 if (matches(loc->match, path))
120 return loc->default_mime;
124 loc = TAILQ_FIRST(&v->locations);
125 if (loc->default_mime != NULL)
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 != NULL) {
142 if (matches(loc->match, path))
143 return loc->index;
147 loc = TAILQ_FIRST(&v->locations);
148 if (loc->index != NULL)
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): %s", strerror(errno));
373 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
374 fatal("fcntl(F_SETFL): %s", strerror(errno));
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: %s",
405 __func__, strerror(errno));
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(c, "handshake: missing SNI");
419 goto err;
422 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
423 log_info(c, "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(c, "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 fatal("%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) == NULL)
545 proto = "gemini";
546 if ((host = p->match_host) == NULL)
547 host = "*";
548 if ((port = p->match_port) == NULL)
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;
586 memset(&hints, 0, sizeof(hints));
587 hints.ai_family = AF_UNSPEC;
588 hints.ai_socktype = SOCK_STREAM;
590 /* XXX: asr_run? :> */
591 r = getaddrinfo(host, port, &hints, &res0);
592 if (r != 0) {
593 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
594 host, port, gai_strerror(r));
595 return -1;
598 for (res = res0; res; res = res->ai_next) {
599 sock = socket(res->ai_family, res->ai_socktype,
600 res->ai_protocol);
601 if (sock == -1)
602 continue;
604 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
605 close(sock);
606 sock = -1;
607 continue;
610 break;
613 freeaddrinfo(res0);
615 if (sock == -1)
616 log_warn(c, "can't connect to %s:%s", host, port);
618 return sock;
621 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
622 static int
623 apply_reverse_proxy(struct client *c)
625 struct proxy *p;
627 if ((p = matched_proxy(c)) == NULL)
628 return 0;
630 c->proxy = p;
632 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
633 return 1;
635 log_debug(c, "opening proxy connection for %s:%s",
636 p->host, p->port);
638 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
639 start_reply(c, PROXY_ERROR, "proxy error");
640 return 1;
643 mark_nonblock(c->pfd);
644 if (proxy_init(c) == -1)
645 start_reply(c, PROXY_ERROR, "proxy error");
647 return 1;
650 static int
651 fcgi_open_sock(struct fcgi *f)
653 struct sockaddr_un addr;
654 int fd;
656 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
657 log_err(NULL, "socket: %s", strerror(errno));
658 return -1;
661 memset(&addr, 0, sizeof(addr));
662 addr.sun_family = AF_UNIX;
663 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
665 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
666 log_warn(NULL, "failed to connect to %s: %s", f->path,
667 strerror(errno));
668 close(fd);
669 return -1;
672 return fd;
675 static int
676 fcgi_open_conn(struct fcgi *f)
678 struct addrinfo hints, *servinfo, *p;
679 int r, sock;
681 memset(&hints, 0, sizeof(hints));
682 hints.ai_family = AF_UNSPEC;
683 hints.ai_socktype = SOCK_STREAM;
684 hints.ai_flags = AI_ADDRCONFIG;
686 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
687 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
688 gai_strerror(r));
689 return -1;
692 for (p = servinfo; p != NULL; p = p->ai_next) {
693 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
694 if (sock == -1)
695 continue;
696 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
697 close(sock);
698 continue;
700 break;
703 if (p == NULL) {
704 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
705 sock = -1;
708 freeaddrinfo(servinfo);
709 return sock;
712 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
713 static int
714 apply_fastcgi(struct client *c)
716 int id;
717 struct fcgi *f;
719 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
720 return 0;
722 f = &fcgi[id];
724 log_debug(c, "opening fastcgi connection for (%s,%s)",
725 f->path, f->port);
727 if (f->port != NULL)
728 c->pfd = fcgi_open_sock(f);
729 else
730 c->pfd = fcgi_open_conn(f);
732 if (c->pfd == -1) {
733 start_reply(c, CGI_ERROR, "CGI error");
734 return 1;
737 mark_nonblock(c->pfd);
739 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
740 fcgi_error, c);
741 if (c->cgibev == NULL) {
742 start_reply(c, TEMP_FAILURE, "internal server error");
743 return 1;
746 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
747 fcgi_req(c);
749 return 1;
752 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
753 static int
754 apply_require_ca(struct client *c)
756 X509_STORE *store;
758 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
759 return 0;
760 return check_matching_certificate(store, c);
763 static void
764 open_dir(struct client *c)
766 size_t len;
767 int dirfd, root;
768 char *before_file;
770 log_debug(c, "in open_dir");
772 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
774 len = strlen(c->iri.path);
775 if (len > 0 && !ends_with(c->iri.path, "/")) {
776 redirect_canonical_dir(c);
777 return;
780 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
781 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
782 if (!ends_with(c->sbuf, "/"))
783 strlcat(c->sbuf, "/", sizeof(c->sbuf));
784 before_file = strchr(c->sbuf, '\0');
785 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
786 sizeof(c->sbuf));
787 if (len >= sizeof(c->sbuf)) {
788 start_reply(c, TEMP_FAILURE, "internal server error");
789 return;
792 c->iri.path = c->sbuf;
794 /* close later unless we have to generate the dir listing */
795 dirfd = c->pfd;
796 c->pfd = -1;
798 switch (check_path(c, c->iri.path, &c->pfd)) {
799 case FILE_EXISTS:
800 c->type = REQUEST_FILE;
801 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
802 break;
804 case FILE_DIRECTORY:
805 start_reply(c, TEMP_REDIRECT, c->sbuf);
806 break;
808 case FILE_MISSING:
809 *before_file = '\0';
811 if (!vhost_auto_index(c->host, c->iri.path)) {
812 start_reply(c, NOT_FOUND, "not found");
813 break;
816 c->type = REQUEST_DIR;
818 c->dirlen = scandir_fd(dirfd, &c->dir,
819 root ? select_non_dotdot : select_non_dot,
820 alphasort);
821 if (c->dirlen == -1) {
822 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
823 c->pfd, c->host->domain, c->iri.path, strerror(errno));
824 start_reply(c, TEMP_FAILURE, "internal server error");
825 return;
827 c->diroff = 0;
828 c->off = 0;
830 start_reply(c, SUCCESS, "text/gemini");
831 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
832 "# Index of %s\n\n", c->iri.path);
833 return;
835 default:
836 /* unreachable */
837 abort();
840 close(dirfd);
843 static void
844 redirect_canonical_dir(struct client *c)
846 size_t len;
848 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
849 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
850 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
852 if (len >= sizeof(c->sbuf)) {
853 start_reply(c, TEMP_FAILURE, "internal server error");
854 return;
857 start_reply(c, TEMP_REDIRECT, c->sbuf);
860 static void
861 client_tls_readcb(int fd, short event, void *d)
863 struct bufferevent *bufev = d;
864 struct client *client = bufev->cbarg;
865 ssize_t ret;
866 size_t len;
867 int what = EVBUFFER_READ;
868 int howmuch = IBUF_READ_SIZE;
869 char buf[IBUF_READ_SIZE];
871 if (event == EV_TIMEOUT) {
872 what |= EVBUFFER_TIMEOUT;
873 goto err;
876 if (bufev->wm_read.high != 0)
877 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
879 switch (ret = tls_read(client->ctx, buf, howmuch)) {
880 case TLS_WANT_POLLIN:
881 case TLS_WANT_POLLOUT:
882 goto retry;
883 case -1:
884 what |= EVBUFFER_ERROR;
885 goto err;
887 len = ret;
889 if (len == 0) {
890 what |= EVBUFFER_EOF;
891 goto err;
894 if (evbuffer_add(bufev->input, buf, len) == -1) {
895 what |= EVBUFFER_ERROR;
896 goto err;
899 event_add(&bufev->ev_read, NULL);
900 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
901 return;
902 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
903 /*
904 * here we could implement a read pressure policy.
905 */
908 if (bufev->readcb != NULL)
909 (*bufev->readcb)(bufev, bufev->cbarg);
911 return;
913 retry:
914 event_add(&bufev->ev_read, NULL);
915 return;
917 err:
918 (*bufev->errorcb)(bufev, what, bufev->cbarg);
921 static void
922 client_tls_writecb(int fd, short event, void *d)
924 struct bufferevent *bufev = d;
925 struct client *client = bufev->cbarg;
926 ssize_t ret;
927 size_t len;
928 short what = EVBUFFER_WRITE;
930 if (event == EV_TIMEOUT) {
931 what |= EVBUFFER_TIMEOUT;
932 goto err;
935 if (EVBUFFER_LENGTH(bufev->output) != 0) {
936 ret = tls_write(client->ctx,
937 EVBUFFER_DATA(bufev->output),
938 EVBUFFER_LENGTH(bufev->output));
939 switch (ret) {
940 case TLS_WANT_POLLIN:
941 case TLS_WANT_POLLOUT:
942 goto retry;
943 case -1:
944 what |= EVBUFFER_ERROR;
945 goto err;
947 len = ret;
948 evbuffer_drain(bufev->output, len);
951 if (EVBUFFER_LENGTH(bufev->output) != 0)
952 event_add(&bufev->ev_write, NULL);
954 if (bufev->writecb != NULL &&
955 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
956 (*bufev->writecb)(bufev, bufev->cbarg);
957 return;
959 retry:
960 event_add(&bufev->ev_write, NULL);
961 return;
962 err:
963 log_err(client, "tls error: %s", tls_error(client->ctx));
964 (*bufev->errorcb)(bufev, what, bufev->cbarg);
967 static void
968 client_read(struct bufferevent *bev, void *d)
970 struct client *c = d;
971 struct evbuffer *src = EVBUFFER_INPUT(bev);
972 const char *parse_err = "invalid request";
973 char decoded[DOMAIN_NAME_LEN];
974 size_t len;
976 bufferevent_disable(bev, EVBUFFER_READ);
978 /*
979 * libevent2 can still somehow call this function, even
980 * though I never enable EV_READ in the bufferevent. If
981 * that's the case, bail out.
982 */
983 if (c->type != REQUEST_UNDECIDED)
984 return;
986 /* max url len + \r\n */
987 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
988 log_err(c, "too much data received");
989 start_reply(c, BAD_REQUEST, "bad request");
990 return;
993 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
994 if (c->req == NULL) {
995 /* not enough data yet. */
996 bufferevent_enable(bev, EVBUFFER_READ);
997 return;
999 c->reqlen = strlen(c->req);
1000 if (c->reqlen > 1024+2) {
1001 log_err(c, "URL too long");
1002 start_reply(c, BAD_REQUEST, "bad request");
1003 return;
1006 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1007 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1008 log_err(c, "IRI parse error: %s", parse_err);
1009 start_reply(c, BAD_REQUEST, "bad request");
1010 return;
1013 if (apply_reverse_proxy(c))
1014 return;
1016 /* ignore the port number */
1017 if (strcmp(c->iri.schema, "gemini") ||
1018 strcmp(decoded, c->domain)) {
1019 start_reply(c, PROXY_REFUSED, "won't proxy request");
1020 return;
1023 if (apply_require_ca(c) ||
1024 apply_block_return(c)||
1025 apply_fastcgi(c))
1026 return;
1028 open_file(c);
1031 void
1032 client_write(struct bufferevent *bev, void *d)
1034 struct client *c = d;
1035 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1036 char nam[PATH_MAX];
1037 char buf[BUFSIZ];
1038 ssize_t r;
1040 switch (c->type) {
1041 case REQUEST_UNDECIDED:
1043 * Ignore spurious calls when we still don't have idea
1044 * what to do with the request.
1046 break;
1048 case REQUEST_FILE:
1049 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1050 log_warn(c, "read: %s", strerror(errno));
1051 client_error(bev, EVBUFFER_ERROR, c);
1052 return;
1053 } else if (r == 0) {
1054 client_close(c);
1055 return;
1056 } else if (r != sizeof(buf))
1057 c->type = REQUEST_DONE;
1058 bufferevent_write(bev, buf, r);
1059 break;
1061 case REQUEST_DIR:
1062 /* TODO: handle big big directories better */
1063 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1064 const char *sufx = "";
1066 encode_path(nam, sizeof(nam),
1067 c->dir[c->diroff]->d_name);
1068 if (c->dir[c->diroff]->d_type == DT_DIR)
1069 sufx = "/";
1070 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1071 free(c->dir[c->diroff]);
1073 free(c->dir);
1074 c->dir = NULL;
1076 c->type = REQUEST_DONE;
1078 event_add(&c->bev->ev_write, NULL);
1079 break;
1081 case REQUEST_FCGI:
1082 case REQUEST_PROXY:
1084 * Here we depend on fastcgi or proxy connection to
1085 * provide data.
1087 break;
1089 case REQUEST_DONE:
1090 if (EVBUFFER_LENGTH(out) == 0)
1091 client_close(c);
1092 break;
1096 static void
1097 client_error(struct bufferevent *bev, short error, void *d)
1099 struct client *c = d;
1101 c->type = REQUEST_DONE;
1103 if (error & EVBUFFER_TIMEOUT) {
1104 log_warn(c, "timeout reached, "
1105 "forcefully closing the connection");
1106 if (c->code == 0)
1107 start_reply(c, BAD_REQUEST, "timeout");
1108 else
1109 client_close(c);
1110 return;
1113 if (error & EVBUFFER_EOF) {
1114 client_close(c);
1115 return;
1118 log_err(c, "unknown bufferevent error %x", error);
1119 client_close(c);
1122 void
1123 start_reply(struct client *c, int code, const char *meta)
1125 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1126 const char *lang;
1127 int r, rr;
1129 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1131 c->code = code;
1132 c->meta = meta;
1134 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1135 if (r == -1)
1136 goto err;
1138 /* 2 digit status + space + 1024 max reply */
1139 if (r > 1027)
1140 goto overflow;
1142 if (c->type != REQUEST_FCGI &&
1143 c->type != REQUEST_PROXY &&
1144 !strcmp(meta, "text/gemini") &&
1145 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1146 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1147 if (rr == -1)
1148 goto err;
1149 if (r + rr > 1027)
1150 goto overflow;
1153 bufferevent_write(c->bev, "\r\n", 2);
1155 if (!vhost_disable_log(c->host, c->iri.path))
1156 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1158 if (code != 20)
1159 c->type = REQUEST_DONE;
1161 return;
1163 err:
1164 log_err(c, "evbuffer_add_printf error: no memory");
1165 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1166 client_close(c);
1167 return;
1169 overflow:
1170 log_warn(c, "reply header overflow");
1171 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1172 start_reply(c, TEMP_FAILURE, "internal error");
1175 static void
1176 client_close_ev(int fd, short event, void *d)
1178 struct client *c = d;
1180 switch (tls_close(c->ctx)) {
1181 case TLS_WANT_POLLIN:
1182 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1183 break;
1184 case TLS_WANT_POLLOUT:
1185 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1186 break;
1189 connected_clients--;
1191 free(c->req);
1193 tls_free(c->ctx);
1194 c->ctx = NULL;
1196 free(c->header);
1198 if (c->pfd != -1)
1199 close(c->pfd);
1201 if (c->dir != NULL)
1202 free(c->dir);
1204 close(c->fd);
1205 c->fd = -1;
1208 static void
1209 client_proxy_close(int fd, short event, void *d)
1211 struct tls *ctx = d;
1213 if (ctx == NULL) {
1214 close(fd);
1215 return;
1218 switch (tls_close(ctx)) {
1219 case TLS_WANT_POLLIN:
1220 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1221 break;
1222 case TLS_WANT_POLLOUT:
1223 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1224 break;
1227 tls_free(ctx);
1228 close(fd);
1231 void
1232 client_close(struct client *c)
1235 * We may end up calling client_close in various situations
1236 * and for the most unexpected reasons. Therefore, we need to
1237 * ensure that everything gets properly released once we reach
1238 * this point.
1241 SPLAY_REMOVE(client_tree_id, &clients, c);
1243 if (c->cgibev != NULL) {
1244 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1245 bufferevent_free(c->cgibev);
1246 c->cgibev = NULL;
1247 close(c->pfd);
1248 c->pfd = -1;
1251 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1252 bufferevent_free(c->bev);
1253 c->bev = NULL;
1255 if (c->proxyevset &&
1256 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1257 c->proxyevset = 0;
1258 event_del(&c->proxyev);
1261 if (c->pfd != -1 && c->proxyctx != NULL) {
1262 /* shut down the proxy TLS connection */
1263 client_proxy_close(c->pfd, 0, c->proxyctx);
1264 c->pfd = -1;
1267 if (c->proxybev != NULL)
1268 bufferevent_free(c->proxybev);
1270 client_close_ev(c->fd, 0, c);
1273 static void
1274 do_accept(int sock, short et, void *d)
1276 struct client *c;
1277 struct sockaddr_storage addr;
1278 struct sockaddr *saddr;
1279 socklen_t len;
1280 int fd;
1282 saddr = (struct sockaddr*)&addr;
1283 len = sizeof(addr);
1284 if ((fd = accept(sock, saddr, &len)) == -1) {
1285 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1286 errno == ECONNABORTED)
1287 return;
1288 fatal("accept: %s", strerror(errno));
1291 mark_nonblock(fd);
1293 c = xcalloc(1, sizeof(*c));
1294 c->id = ++server_client_id;
1295 c->fd = fd;
1296 c->pfd = -1;
1297 c->addr = addr;
1299 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1300 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1301 close(c->fd);
1302 free(c);
1303 return;
1306 SPLAY_INSERT(client_tree_id, &clients, c);
1307 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1308 connected_clients++;
1311 struct client *
1312 client_by_id(int id)
1314 struct client find;
1316 find.id = id;
1317 return SPLAY_FIND(client_tree_id, &clients, &find);
1320 static void
1321 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1324 * don't call event_loopbreak since we want to finish to
1325 * handle the ongoing connections.
1328 shutting_down = 1;
1330 event_del(&e4);
1331 if (has_ipv6)
1332 event_del(&e6);
1333 if (has_siginfo)
1334 signal_del(&siginfo);
1335 event_del(&imsgev);
1336 signal_del(&sigusr2);
1339 static void
1340 handle_dispatch_imsg(int fd, short ev, void *d)
1342 struct imsgbuf *ibuf = d;
1343 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1346 static void
1347 handle_siginfo(int fd, short ev, void *d)
1349 log_info(NULL, "%d connected clients", connected_clients);
1352 void
1353 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1355 ctx = ctx_;
1357 SPLAY_INIT(&clients);
1359 event_init();
1361 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1362 event_add(&e4, NULL);
1364 if (sock6 != -1) {
1365 has_ipv6 = 1;
1366 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1367 event_add(&e6, NULL);
1370 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1371 event_add(&imsgev, NULL);
1373 #ifdef SIGINFO
1374 has_siginfo = 1;
1375 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1376 signal_add(&siginfo, NULL);
1377 #endif
1378 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1379 signal_add(&sigusr2, NULL);
1381 sandbox_server_process(conf.can_open_sockets);
1382 event_dispatch();
1383 _exit(0);
1386 int
1387 client_tree_cmp(struct client *a, struct client *b)
1389 if (a->id == b->id)
1390 return 0;
1391 else if (a->id < b->id)
1392 return -1;
1393 else
1394 return +1;
1397 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)