Blob


1 /*
2 * Copyright (c) 2021 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>
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <fnmatch.h>
27 #include <limits.h>
28 #include <string.h>
30 #define MIN(a, b) ((a) < (b) ? (a) : (b))
32 int shutting_down;
34 static struct tls *ctx;
36 static struct event e4, e6, imsgev, siginfo, sigusr2;
37 static int has_ipv6, has_siginfo;
39 int connected_clients;
41 static inline int matches(const char*, const char*);
43 static int check_path(struct client*, const char*, int*);
44 static void open_file(struct client*);
45 static void check_for_cgi(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 size_t host_nth(struct vhost*);
55 static void start_cgi(const char*, const char*, 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 cgi_read(struct bufferevent *, void *);
69 static void cgi_write(struct bufferevent *, void *);
70 static void cgi_error(struct bufferevent *, short, void *);
72 static void do_accept(int, short, void*);
73 static struct client *client_by_id(int);
75 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
76 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
77 static void handle_imsg_conn_fd(struct imsgbuf*, struct imsg*, size_t);
78 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
79 static void handle_dispatch_imsg(int, short, void *);
80 static void handle_siginfo(int, short, void*);
82 static imsg_handlerfn *handlers[] = {
83 [IMSG_QUIT] = handle_imsg_quit,
84 [IMSG_CGI_RES] = handle_imsg_cgi_res,
85 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
86 [IMSG_CONN_FD] = handle_imsg_conn_fd,
87 };
89 static uint32_t server_client_id;
91 struct client_tree_id clients;
93 static inline int
94 matches(const char *pattern, const char *path)
95 {
96 if (*path == '/')
97 path++;
98 return !fnmatch(pattern, path, 0);
99 }
101 const char *
102 vhost_lang(struct vhost *v, const char *path)
104 struct location *loc;
106 if (v == NULL || path == NULL)
107 return NULL;
109 loc = TAILQ_FIRST(&v->locations);
110 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
111 if (loc->lang != NULL) {
112 if (matches(loc->match, path))
113 return loc->lang;
117 return TAILQ_FIRST(&v->locations)->lang;
120 const char *
121 vhost_default_mime(struct vhost *v, const char *path)
123 struct location *loc;
124 const char *default_mime = "application/octet-stream";
126 if (v == NULL || path == NULL)
127 return default_mime;
129 loc = TAILQ_FIRST(&v->locations);
130 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
131 if (loc->default_mime != NULL) {
132 if (matches(loc->match, path))
133 return loc->default_mime;
137 loc = TAILQ_FIRST(&v->locations);
138 if (loc->default_mime != NULL)
139 return loc->default_mime;
140 return default_mime;
143 const char *
144 vhost_index(struct vhost *v, const char *path)
146 struct location *loc;
147 const char *index = "index.gmi";
149 if (v == NULL || path == NULL)
150 return index;
152 loc = TAILQ_FIRST(&v->locations);
153 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
154 if (loc->index != NULL) {
155 if (matches(loc->match, path))
156 return loc->index;
160 loc = TAILQ_FIRST(&v->locations);
161 if (loc->index != NULL)
162 return loc->index;
163 return index;
166 int
167 vhost_auto_index(struct vhost *v, const char *path)
169 struct location *loc;
171 if (v == NULL || path == NULL)
172 return 0;
174 loc = TAILQ_FIRST(&v->locations);
175 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
176 if (loc->auto_index != 0) {
177 if (matches(loc->match, path))
178 return loc->auto_index == 1;
182 loc = TAILQ_FIRST(&v->locations);
183 return loc->auto_index == 1;
186 int
187 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
189 struct location *loc;
191 if (v == NULL || path == NULL)
192 return 0;
194 loc = TAILQ_FIRST(&v->locations);
195 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
196 if (loc->block_code != 0) {
197 if (matches(loc->match, path)) {
198 *code = loc->block_code;
199 *fmt = loc->block_fmt;
200 return 1;
205 loc = TAILQ_FIRST(&v->locations);
206 *code = loc->block_code;
207 *fmt = loc->block_fmt;
208 return loc->block_code != 0;
211 int
212 vhost_fastcgi(struct vhost *v, const char *path)
214 struct location *loc;
216 if (v == NULL || path == NULL)
217 return -1;
219 loc = TAILQ_FIRST(&v->locations);
220 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
221 if (loc->fcgi != -1)
222 if (matches(loc->match, path))
223 return loc->fcgi;
226 loc = TAILQ_FIRST(&v->locations);
227 return loc->fcgi;
230 int
231 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
233 struct location *loc;
234 size_t l = 0;
236 if (v == NULL || path == NULL)
237 return -1;
239 loc = TAILQ_FIRST(&v->locations);
240 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
241 l++;
242 if (loc->dirfd != -1)
243 if (matches(loc->match, path)) {
244 *retloc = l;
245 return loc->dirfd;
249 *retloc = 0;
250 loc = TAILQ_FIRST(&v->locations);
251 return loc->dirfd;
254 int
255 vhost_strip(struct vhost *v, const char *path)
257 struct location *loc;
259 if (v == NULL || path == NULL)
260 return 0;
262 loc = TAILQ_FIRST(&v->locations);
263 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
264 if (loc->strip != 0) {
265 if (matches(loc->match, path))
266 return loc->strip;
270 loc = TAILQ_FIRST(&v->locations);
271 return loc->strip;
274 X509_STORE *
275 vhost_require_ca(struct vhost *v, const char *path)
277 struct location *loc;
279 if (v == NULL || path == NULL)
280 return NULL;
282 loc = TAILQ_FIRST(&v->locations);
283 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
284 if (loc->reqca != NULL) {
285 if (matches(loc->match, path))
286 return loc->reqca;
290 loc = TAILQ_FIRST(&v->locations);
291 return loc->reqca;
294 int
295 vhost_disable_log(struct vhost *v, const char *path)
297 struct location *loc;
299 if (v == NULL || path == NULL)
300 return 0;
302 loc = TAILQ_FIRST(&v->locations);
303 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
304 if (loc->disable_log && matches(loc->match, path))
305 return 1;
308 loc = TAILQ_FIRST(&v->locations);
309 return loc->disable_log;
312 static int
313 check_path(struct client *c, const char *path, int *fd)
315 struct stat sb;
316 const char *p;
317 int dirfd, strip;
319 assert(path != NULL);
321 /*
322 * in send_dir we add an initial / (to be redirect-friendly),
323 * but here we want to skip it
324 */
325 if (*path == '/')
326 path++;
328 strip = vhost_strip(c->host, path);
329 p = strip_path(path, strip);
331 if (*p == '/')
332 p = p+1;
333 if (*p == '\0')
334 p = ".";
336 dirfd = vhost_dirfd(c->host, path, &c->loc);
337 log_debug(c, "check_path: strip=%d path=%s original=%s",
338 strip, p, path);
339 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
340 return FILE_MISSING;
342 if (fstat(*fd, &sb) == -1) {
343 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
344 return FILE_MISSING;
347 if (S_ISDIR(sb.st_mode))
348 return FILE_DIRECTORY;
350 if (sb.st_mode & S_IXUSR)
351 return FILE_EXECUTABLE;
353 return FILE_EXISTS;
356 static void
357 open_file(struct client *c)
359 switch (check_path(c, c->iri.path, &c->pfd)) {
360 case FILE_EXECUTABLE:
361 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
362 start_cgi(c->iri.path, "", c);
363 return;
366 /* fallthrough */
368 case FILE_EXISTS:
369 c->type = REQUEST_FILE;
370 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
371 return;
373 case FILE_DIRECTORY:
374 open_dir(c);
375 return;
377 case FILE_MISSING:
378 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
379 check_for_cgi(c);
380 return;
382 start_reply(c, NOT_FOUND, "not found");
383 return;
385 default:
386 /* unreachable */
387 abort();
391 /*
392 * the inverse of this algorithm, i.e. starting from the start of the
393 * path + strlen(cgi), and checking if each component, should be
394 * faster. But it's tedious to write. This does the opposite: starts
395 * from the end and strip one component at a time, until either an
396 * executable is found or we emptied the path.
397 */
398 static void
399 check_for_cgi(struct client *c)
401 char path[PATH_MAX];
402 char *end;
404 strlcpy(path, c->iri.path, sizeof(path));
405 end = strchr(path, '\0');
407 while (end > path) {
408 /*
409 * go up one level. UNIX paths are simple and POSIX
410 * dirname, with its ambiguities on if the given
411 * pointer is changed or not, gives me headaches.
412 */
413 while (*end != '/' && end > path)
414 end--;
416 if (end == path)
417 break;
419 *end = '\0';
421 switch (check_path(c, path, &c->pfd)) {
422 case FILE_EXECUTABLE:
423 start_cgi(path, end+1, c);
424 return;
425 case FILE_MISSING:
426 break;
427 default:
428 goto err;
431 *end = '/';
432 end--;
435 err:
436 start_reply(c, NOT_FOUND, "not found");
437 return;
440 void
441 mark_nonblock(int fd)
443 int flags;
445 if ((flags = fcntl(fd, F_GETFL)) == -1)
446 fatal("fcntl(F_GETFL): %s", strerror(errno));
447 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
448 fatal("fcntl(F_SETFL): %s", strerror(errno));
451 static void
452 handle_handshake(int fd, short ev, void *d)
454 struct client *c = d;
455 struct vhost *h;
456 struct alist *a;
457 const char *servname;
458 const char *parse_err = "unknown error";
460 switch (tls_handshake(c->ctx)) {
461 case 0: /* success */
462 case -1: /* already handshaked */
463 break;
464 case TLS_WANT_POLLIN:
465 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
466 return;
467 case TLS_WANT_POLLOUT:
468 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
469 return;
470 default:
471 /* unreachable */
472 abort();
475 c->bev = bufferevent_new(fd, client_read, client_write,
476 client_error, c);
477 if (c->bev == NULL)
478 fatal("%s: failed to allocate client buffer: %s",
479 __func__, strerror(errno));
481 event_set(&c->bev->ev_read, c->fd, EV_READ,
482 client_tls_readcb, c->bev);
483 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
484 client_tls_writecb, c->bev);
486 #if HAVE_LIBEVENT2
487 evbuffer_unfreeze(c->bev->input, 0);
488 evbuffer_unfreeze(c->bev->output, 1);
489 #endif
491 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
492 log_debug(c, "handshake: missing SNI");
493 goto err;
496 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
497 log_info(c, "puny_decode: %s", parse_err);
498 goto err;
501 TAILQ_FOREACH(h, &hosts, vhosts) {
502 if (matches(h->domain, c->domain))
503 goto found;
504 TAILQ_FOREACH(a, &h->aliases, aliases) {
505 if (matches(a->alias, c->domain))
506 goto found;
510 found:
511 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
512 servname != NULL ? servname : "(null)",
513 c->domain,
514 h != NULL ? h->domain : "(null)");
516 if (h != NULL) {
517 c->host = h;
518 bufferevent_enable(c->bev, EV_READ);
519 return;
522 err:
523 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
526 static const char *
527 strip_path(const char *path, int strip)
529 char *t;
531 while (strip > 0) {
532 if ((t = strchr(path, '/')) == NULL) {
533 path = strchr(path, '\0');
534 break;
536 path = t;
537 strip--;
540 return path;
543 static void
544 fmt_sbuf(const char *fmt, struct client *c, const char *path)
546 size_t i;
547 char buf[32];
549 memset(buf, 0, sizeof(buf));
550 for (i = 0; *fmt; ++fmt) {
551 if (i == sizeof(buf)-1 || *fmt == '%') {
552 strlcat(c->sbuf, buf, sizeof(c->sbuf));
553 memset(buf, 0, sizeof(buf));
554 i = 0;
557 if (*fmt != '%') {
558 buf[i++] = *fmt;
559 continue;
562 switch (*++fmt) {
563 case '%':
564 strlcat(c->sbuf, "%", sizeof(c->sbuf));
565 break;
566 case 'p':
567 if (*path != '/')
568 strlcat(c->sbuf, "/", sizeof(c->sbuf));
569 strlcat(c->sbuf, path, sizeof(c->sbuf));
570 break;
571 case 'q':
572 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
573 break;
574 case 'P':
575 snprintf(buf, sizeof(buf), "%d", conf.port);
576 strlcat(c->sbuf, buf, sizeof(c->sbuf));
577 memset(buf, 0, sizeof(buf));
578 break;
579 case 'N':
580 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
581 break;
582 default:
583 fatal("%s: unknown fmt specifier %c",
584 __func__, *fmt);
588 if (i != 0)
589 strlcat(c->sbuf, buf, sizeof(c->sbuf));
592 /* 1 if a matching `block return' (and apply it), 0 otherwise */
593 static int
594 apply_block_return(struct client *c)
596 const char *fmt, *path;
597 int code;
599 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
600 return 0;
602 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
603 fmt_sbuf(fmt, c, path);
605 start_reply(c, code, c->sbuf);
606 return 1;
609 static struct proxy *
610 matched_proxy(struct client *c)
612 struct proxy *p;
613 const char *proto;
614 const char *host;
615 const char *port;
617 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
618 if ((proto = p->match_proto) == NULL)
619 proto = "gemini";
620 if ((host = p->match_host) == NULL)
621 host = "*";
622 if ((port = p->match_port) == NULL)
623 port = "*";
625 if (matches(proto, c->iri.schema) &&
626 matches(host, c->domain) &&
627 matches(port, c->iri.port))
628 return p;
631 return NULL;
634 static int
635 check_matching_certificate(X509_STORE *store, struct client *c)
637 const uint8_t *cert;
638 size_t len;
640 if (!tls_peer_cert_provided(c->ctx)) {
641 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
642 return 1;
645 cert = tls_peer_cert_chain_pem(c->ctx, &len);
646 if (!validate_against_ca(store, cert, len)) {
647 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
648 return 1;
651 return 0;
654 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
655 static int
656 apply_reverse_proxy(struct client *c)
658 struct proxy *p;
659 struct connreq r;
661 if ((p = matched_proxy(c)) == NULL)
662 return 0;
664 c->proxy = p;
666 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
667 return 1;
669 log_debug(c, "opening proxy connection for %s:%s",
670 p->host, p->port);
672 strlcpy(r.host, p->host, sizeof(r.host));
673 strlcpy(r.port, p->port, sizeof(r.port));
675 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
676 imsg_flush(&exibuf);
678 return 1;
681 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
682 static int
683 apply_fastcgi(struct client *c)
685 int id;
686 struct fcgi *f;
688 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
689 return 0;
691 f = &fcgi[id];
693 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
694 f->path, f->port, f->prog);
696 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
697 &id, sizeof(id));
698 imsg_flush(&exibuf);
699 return 1;
702 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
703 static int
704 apply_require_ca(struct client *c)
706 X509_STORE *store;
708 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
709 return 0;
710 return check_matching_certificate(store, c);
713 static size_t
714 host_nth(struct vhost *h)
716 struct vhost *v;
717 size_t i = 0;
719 TAILQ_FOREACH(v, &hosts, vhosts) {
720 if (v == h)
721 return i;
722 i++;
725 abort();
728 static void
729 start_cgi(const char *spath, const char *relpath, struct client *c)
731 char addr[NI_MAXHOST];
732 const char *t;
733 struct cgireq req;
734 int e;
736 c->type = REQUEST_CGI;
738 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
739 addr, sizeof(addr),
740 NULL, 0,
741 NI_NUMERICHOST);
742 if (e != 0)
743 fatal("getnameinfo failed");
745 memset(&req, 0, sizeof(req));
747 memcpy(req.buf, c->req, sizeof(req.buf));
749 req.iri_schema_off = c->iri.schema - c->req;
750 req.iri_host_off = c->iri.host - c->req;
751 req.iri_port_off = c->iri.port - c->req;
752 req.iri_path_off = c->iri.path - c->req;
753 req.iri_query_off = c->iri.query - c->req;
754 req.iri_fragment_off = c->iri.fragment - c->req;
756 req.iri_portno = c->iri.port_no;
758 strlcpy(req.spath, spath, sizeof(req.spath));
759 strlcpy(req.relpath, relpath, sizeof(req.relpath));
760 strlcpy(req.addr, addr, sizeof(req.addr));
762 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
763 strlcpy(req.subject, t, sizeof(req.subject));
764 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
765 strlcpy(req.issuer, t, sizeof(req.issuer));
766 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
767 strlcpy(req.hash, t, sizeof(req.hash));
768 if ((t = tls_conn_version(c->ctx)) != NULL)
769 strlcpy(req.version, t, sizeof(req.version));
770 if ((t = tls_conn_cipher(c->ctx)) != NULL)
771 strlcpy(req.cipher, t, sizeof(req.cipher));
773 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
774 req.notbefore = tls_peer_cert_notbefore(c->ctx);
775 req.notafter = tls_peer_cert_notafter(c->ctx);
777 req.host_off = host_nth(c->host);
778 req.loc_off = c->loc;
780 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
781 imsg_flush(&exibuf);
783 close(c->pfd);
786 static void
787 open_dir(struct client *c)
789 size_t len;
790 int dirfd, root;
791 char *before_file;
793 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
795 len = strlen(c->iri.path);
796 if (len > 0 && !ends_with(c->iri.path, "/")) {
797 redirect_canonical_dir(c);
798 return;
801 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
802 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
803 if (!ends_with(c->sbuf, "/"))
804 strlcat(c->sbuf, "/", sizeof(c->sbuf));
805 before_file = strchr(c->sbuf, '\0');
806 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
807 sizeof(c->sbuf));
808 if (len >= sizeof(c->sbuf)) {
809 start_reply(c, TEMP_FAILURE, "internal server error");
810 return;
813 c->iri.path = c->sbuf;
815 /* close later unless we have to generate the dir listing */
816 dirfd = c->pfd;
817 c->pfd = -1;
819 switch (check_path(c, c->iri.path, &c->pfd)) {
820 case FILE_EXECUTABLE:
821 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
822 start_cgi(c->iri.path, "", c);
823 break;
826 /* fallthrough */
828 case FILE_EXISTS:
829 c->type = REQUEST_FILE;
830 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
831 break;
833 case FILE_DIRECTORY:
834 start_reply(c, TEMP_REDIRECT, c->sbuf);
835 break;
837 case FILE_MISSING:
838 *before_file = '\0';
840 if (!vhost_auto_index(c->host, c->iri.path)) {
841 start_reply(c, NOT_FOUND, "not found");
842 break;
845 c->type = REQUEST_DIR;
847 c->dirlen = scandir_fd(dirfd, &c->dir,
848 root ? select_non_dotdot : select_non_dot,
849 alphasort);
850 if (c->dirlen == -1) {
851 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
852 c->pfd, c->host->domain, c->iri.path, strerror(errno));
853 start_reply(c, TEMP_FAILURE, "internal server error");
854 return;
856 c->diroff = 0;
857 c->off = 0;
859 start_reply(c, SUCCESS, "text/gemini");
860 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
861 "# Index of %s\n\n", c->iri.path);
862 return;
864 default:
865 /* unreachable */
866 abort();
869 close(dirfd);
872 static void
873 redirect_canonical_dir(struct client *c)
875 size_t len;
877 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
878 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
879 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
881 if (len >= sizeof(c->sbuf)) {
882 start_reply(c, TEMP_FAILURE, "internal server error");
883 return;
886 start_reply(c, TEMP_REDIRECT, c->sbuf);
889 static void
890 client_tls_readcb(int fd, short event, void *d)
892 struct bufferevent *bufev = d;
893 struct client *client = bufev->cbarg;
894 ssize_t ret;
895 size_t len;
896 int what = EVBUFFER_READ;
897 int howmuch = IBUF_READ_SIZE;
898 char buf[IBUF_READ_SIZE];
900 if (event == EV_TIMEOUT) {
901 what |= EVBUFFER_TIMEOUT;
902 goto err;
905 if (bufev->wm_read.high != 0)
906 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
908 switch (ret = tls_read(client->ctx, buf, howmuch)) {
909 case TLS_WANT_POLLIN:
910 case TLS_WANT_POLLOUT:
911 goto retry;
912 case -1:
913 what |= EVBUFFER_ERROR;
914 goto err;
916 len = ret;
918 if (len == 0) {
919 what |= EVBUFFER_EOF;
920 goto err;
923 if (evbuffer_add(bufev->input, buf, len) == -1) {
924 what |= EVBUFFER_ERROR;
925 goto err;
928 event_add(&bufev->ev_read, NULL);
929 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
930 return;
931 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
932 /*
933 * here we could implement a read pressure policy.
934 */
937 if (bufev->readcb != NULL)
938 (*bufev->readcb)(bufev, bufev->cbarg);
940 return;
942 retry:
943 event_add(&bufev->ev_read, NULL);
944 return;
946 err:
947 (*bufev->errorcb)(bufev, what, bufev->cbarg);
950 static void
951 client_tls_writecb(int fd, short event, void *d)
953 struct bufferevent *bufev = d;
954 struct client *client = bufev->cbarg;
955 ssize_t ret;
956 size_t len;
957 short what = EVBUFFER_WRITE;
959 if (event == EV_TIMEOUT) {
960 what |= EVBUFFER_TIMEOUT;
961 goto err;
964 if (EVBUFFER_LENGTH(bufev->output) != 0) {
965 ret = tls_write(client->ctx,
966 EVBUFFER_DATA(bufev->output),
967 EVBUFFER_LENGTH(bufev->output));
968 switch (ret) {
969 case TLS_WANT_POLLIN:
970 case TLS_WANT_POLLOUT:
971 goto retry;
972 case -1:
973 what |= EVBUFFER_ERROR;
974 goto err;
976 len = ret;
977 evbuffer_drain(bufev->output, len);
980 if (EVBUFFER_LENGTH(bufev->output) != 0)
981 event_add(&bufev->ev_write, NULL);
983 if (bufev->writecb != NULL &&
984 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
985 (*bufev->writecb)(bufev, bufev->cbarg);
986 return;
988 retry:
989 event_add(&bufev->ev_write, NULL);
990 return;
991 err:
992 log_err(client, "tls error: %s", tls_error(client->ctx));
993 (*bufev->errorcb)(bufev, what, bufev->cbarg);
996 static void
997 client_read(struct bufferevent *bev, void *d)
999 struct client *c = d;
1000 struct evbuffer *src = EVBUFFER_INPUT(bev);
1001 const char *parse_err = "invalid request";
1002 char decoded[DOMAIN_NAME_LEN];
1003 size_t len;
1005 bufferevent_disable(bev, EVBUFFER_READ);
1008 * libevent2 can still somehow call this function, even
1009 * though I never enable EV_READ in the bufferevent. If
1010 * that's the case, bail out.
1012 if (c->type != REQUEST_UNDECIDED)
1013 return;
1015 /* max url len + \r\n */
1016 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1017 log_err(c, "too much data received");
1018 start_reply(c, BAD_REQUEST, "bad request");
1019 return;
1022 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1023 if (c->req == NULL) {
1024 /* not enough data yet. */
1025 bufferevent_enable(bev, EVBUFFER_READ);
1026 return;
1029 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1030 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1031 log_err(c, "IRI parse error: %s", parse_err);
1032 start_reply(c, BAD_REQUEST, "bad request");
1033 return;
1036 if (apply_reverse_proxy(c))
1037 return;
1039 /* ignore the port number */
1040 if (strcmp(c->iri.schema, "gemini") ||
1041 strcmp(decoded, c->domain)) {
1042 start_reply(c, PROXY_REFUSED, "won't proxy request");
1043 return;
1046 if (apply_require_ca(c) ||
1047 apply_block_return(c)||
1048 apply_fastcgi(c))
1049 return;
1051 if (c->host->entrypoint != NULL) {
1052 c->loc = 0;
1053 start_cgi(c->host->entrypoint, c->iri.path, c);
1054 return;
1057 open_file(c);
1060 void
1061 client_write(struct bufferevent *bev, void *d)
1063 struct client *c = d;
1064 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1065 char buf[BUFSIZ];
1066 ssize_t r;
1068 switch (c->type) {
1069 case REQUEST_UNDECIDED:
1071 * Ignore spurious calls when we still don't have idea
1072 * what to do with the request.
1074 break;
1076 case REQUEST_FILE:
1077 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1078 log_warn(c, "read: %s", strerror(errno));
1079 client_error(bev, EVBUFFER_ERROR, c);
1080 return;
1081 } else if (r == 0) {
1082 client_close(c);
1083 return;
1084 } else if (r != sizeof(buf))
1085 c->type = REQUEST_DONE;
1086 bufferevent_write(bev, buf, r);
1087 break;
1089 case REQUEST_DIR:
1090 /* TODO: handle big big directories better */
1091 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1092 evbuffer_add_printf(out, "=> %s\n",
1093 c->dir[c->diroff]->d_name);
1094 free(c->dir[c->diroff]);
1096 free(c->dir);
1097 c->dir = NULL;
1099 c->type = REQUEST_DONE;
1101 event_add(&c->bev->ev_write, NULL);
1102 break;
1104 case REQUEST_CGI:
1105 case REQUEST_FCGI:
1106 case REQUEST_PROXY:
1108 * Here we depend on the cgi/fastcgi or proxy
1109 * connection to provide data.
1111 break;
1113 case REQUEST_DONE:
1114 if (EVBUFFER_LENGTH(out) == 0)
1115 client_close(c);
1116 break;
1120 static void
1121 client_error(struct bufferevent *bev, short error, void *d)
1123 struct client *c = d;
1125 c->type = REQUEST_DONE;
1127 if (error & EVBUFFER_TIMEOUT) {
1128 log_warn(c, "timeout reached, "
1129 "forcefully closing the connection");
1130 if (c->code == 0)
1131 start_reply(c, BAD_REQUEST, "timeout");
1132 else
1133 client_close(c);
1134 return;
1137 if (error & EVBUFFER_EOF) {
1138 client_close(c);
1139 return;
1142 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1143 client_close(c);
1146 void
1147 start_reply(struct client *c, int code, const char *meta)
1149 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1150 const char *lang;
1151 int r, rr;
1153 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1155 c->code = code;
1156 c->meta = meta;
1158 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1159 if (r == -1)
1160 goto err;
1162 /* 2 digit status + space + 1024 max reply */
1163 if (r > 1027)
1164 goto overflow;
1166 if (c->type != REQUEST_CGI &&
1167 c->type != REQUEST_FCGI &&
1168 c->type != REQUEST_PROXY &&
1169 !strcmp(meta, "text/gemini") &&
1170 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1171 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1172 if (rr == -1)
1173 goto err;
1174 if (r + rr > 1027)
1175 goto overflow;
1178 bufferevent_write(c->bev, "\r\n", 2);
1180 if (!vhost_disable_log(c->host, c->iri.path))
1181 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1183 if (code != 20)
1184 c->type = REQUEST_DONE;
1186 return;
1188 err:
1189 log_err(c, "evbuffer_add_printf error: no memory");
1190 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1191 client_close(c);
1192 return;
1194 overflow:
1195 log_warn(c, "reply header overflow");
1196 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1197 start_reply(c, TEMP_FAILURE, "internal error");
1200 static void
1201 client_close_ev(int fd, short event, void *d)
1203 struct client *c = d;
1205 switch (tls_close(c->ctx)) {
1206 case TLS_WANT_POLLIN:
1207 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1208 break;
1209 case TLS_WANT_POLLOUT:
1210 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1211 break;
1214 connected_clients--;
1216 free(c->req);
1218 tls_free(c->ctx);
1219 c->ctx = NULL;
1221 free(c->header);
1223 if (c->pfd != -1)
1224 close(c->pfd);
1226 if (c->dir != NULL)
1227 free(c->dir);
1229 close(c->fd);
1230 c->fd = -1;
1233 static void
1234 client_proxy_close(int fd, short event, void *d)
1236 struct tls *ctx = d;
1238 if (ctx == NULL) {
1239 close(fd);
1240 return;
1243 switch (tls_close(ctx)) {
1244 case TLS_WANT_POLLIN:
1245 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1246 break;
1247 case TLS_WANT_POLLOUT:
1248 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1249 break;
1252 tls_free(ctx);
1253 close(fd);
1256 void
1257 client_close(struct client *c)
1260 * We may end up calling client_close in various situations
1261 * and for the most unexpected reasons. Therefore, we need to
1262 * ensure that everything gets properly released once we reach
1263 * this point.
1266 SPLAY_REMOVE(client_tree_id, &clients, c);
1268 if (c->cgibev != NULL) {
1269 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1270 bufferevent_free(c->cgibev);
1271 c->cgibev = NULL;
1272 close(c->pfd);
1273 c->pfd = -1;
1276 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1277 bufferevent_free(c->bev);
1278 c->bev = NULL;
1280 if (c->proxyevset &&
1281 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1282 c->proxyevset = 0;
1283 event_del(&c->proxyev);
1286 if (c->pfd != -1 && c->proxyctx != NULL) {
1287 /* shut down the proxy TLS connection */
1288 client_proxy_close(c->pfd, 0, c->proxyctx);
1289 c->pfd = -1;
1292 if (c->proxybev != NULL)
1293 bufferevent_free(c->proxybev);
1295 client_close_ev(c->fd, 0, c);
1298 static void
1299 cgi_read(struct bufferevent *bev, void *d)
1301 struct client *client = d;
1302 struct evbuffer *src = EVBUFFER_INPUT(bev);
1303 char *header;
1304 size_t len;
1305 int code;
1307 /* intercept the header */
1308 if (client->code == 0) {
1309 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1310 if (header == NULL) {
1311 /* max reply + \r\n */
1312 if (EVBUFFER_LENGTH(src) > 1029) {
1313 log_warn(client, "CGI script is trying to "
1314 "send a header too long.");
1315 cgi_error(bev, EVBUFFER_READ, client);
1318 /* wait a bit */
1319 return;
1322 if (len < 3 || len > 1029 ||
1323 !isdigit(header[0]) ||
1324 !isdigit(header[1]) ||
1325 !isspace(header[2])) {
1326 free(header);
1327 log_warn(client, "CGI script is trying to send a "
1328 "malformed header");
1329 cgi_error(bev, EVBUFFER_READ, client);
1330 return;
1333 client->header = header;
1334 code = (header[0] - '0') * 10 + (header[1] - '0');
1336 if (code < 10 || code >= 70) {
1337 log_warn(client, "CGI script is trying to send an "
1338 "invalid reply code (%d)", code);
1339 cgi_error(bev, EVBUFFER_READ, client);
1340 return;
1343 start_reply(client, code, header + 3);
1345 if (client->code < 20 || client->code > 29) {
1346 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1347 return;
1351 bufferevent_write_buffer(client->bev, src);
1354 static void
1355 cgi_write(struct bufferevent *bev, void *d)
1358 * Never called. We don't send data to a CGI script.
1360 abort();
1363 static void
1364 cgi_error(struct bufferevent *bev, short error, void *d)
1366 struct client *client = d;
1368 if (error & EVBUFFER_ERROR)
1369 log_err(client, "%s: evbuffer error (%x): %s",
1370 __func__, error, strerror(errno));
1372 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1373 bufferevent_free(bev);
1374 client->cgibev = NULL;
1376 close(client->pfd);
1377 client->pfd = -1;
1379 client->type = REQUEST_DONE;
1380 if (client->code != 0)
1381 client_write(client->bev, client);
1382 else
1383 start_reply(client, CGI_ERROR, "CGI error");
1386 static void
1387 do_accept(int sock, short et, void *d)
1389 struct client *c;
1390 struct sockaddr_storage addr;
1391 struct sockaddr *saddr;
1392 socklen_t len;
1393 int fd;
1395 saddr = (struct sockaddr*)&addr;
1396 len = sizeof(addr);
1397 if ((fd = accept(sock, saddr, &len)) == -1) {
1398 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1399 errno == ECONNABORTED)
1400 return;
1401 fatal("accept: %s", strerror(errno));
1404 mark_nonblock(fd);
1406 c = xcalloc(1, sizeof(*c));
1407 c->id = ++server_client_id;
1408 c->fd = fd;
1409 c->pfd = -1;
1410 c->addr = addr;
1412 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1413 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1414 close(c->fd);
1415 free(c);
1416 return;
1419 SPLAY_INSERT(client_tree_id, &clients, c);
1420 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1421 connected_clients++;
1424 static struct client *
1425 client_by_id(int id)
1427 struct client *c;
1429 if ((c = try_client_by_id(id)) == NULL)
1430 fatal("in client_by_id: invalid id %d", id);
1431 return c;
1434 struct client *
1435 try_client_by_id(int id)
1437 struct client find;
1439 find.id = id;
1440 return SPLAY_FIND(client_tree_id, &clients, &find);
1443 static void
1444 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1446 struct client *c;
1448 c = client_by_id(imsg->hdr.peerid);
1450 if ((c->pfd = imsg->fd) == -1) {
1451 start_reply(c, TEMP_FAILURE, "internal server error");
1452 return;
1455 c->type = REQUEST_CGI;
1457 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1458 cgi_error, c);
1460 bufferevent_enable(c->cgibev, EV_READ);
1463 static void
1464 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1466 struct client *c;
1467 int id;
1469 id = imsg->hdr.peerid;
1471 if ((c = try_client_by_id(id)) == NULL) {
1472 if (imsg->fd != -1)
1473 close(imsg->fd);
1474 return;
1477 if ((c->pfd = imsg->fd) == -1) {
1478 start_reply(c, CGI_ERROR, "CGI error");
1479 return;
1482 mark_nonblock(c->pfd);
1484 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1485 fcgi_error, c);
1486 if (c->cgibev == NULL) {
1487 start_reply(c, TEMP_FAILURE, "internal server error");
1488 return;
1491 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1492 fcgi_req(c);
1495 static void
1496 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1498 struct client *c;
1499 int id;
1501 id = imsg->hdr.peerid;
1502 if ((c = try_client_by_id(id)) == NULL) {
1503 if (imsg->fd != -1)
1504 close(imsg->fd);
1505 return;
1508 if ((c->pfd = imsg->fd) == -1) {
1509 start_reply(c, PROXY_ERROR, "proxy error");
1510 return;
1513 mark_nonblock(c->pfd);
1515 if (proxy_init(c) == -1)
1516 start_reply(c, PROXY_ERROR, "proxy error");
1519 static void
1520 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1523 * don't call event_loopbreak since we want to finish to
1524 * handle the ongoing connections.
1527 shutting_down = 1;
1529 event_del(&e4);
1530 if (has_ipv6)
1531 event_del(&e6);
1532 if (has_siginfo)
1533 signal_del(&siginfo);
1534 event_del(&imsgev);
1535 signal_del(&sigusr2);
1538 static void
1539 handle_dispatch_imsg(int fd, short ev, void *d)
1541 struct imsgbuf *ibuf = d;
1542 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1545 static void
1546 handle_siginfo(int fd, short ev, void *d)
1548 log_info(NULL, "%d connected clients", connected_clients);
1551 void
1552 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1554 ctx = ctx_;
1556 SPLAY_INIT(&clients);
1558 event_init();
1560 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1561 event_add(&e4, NULL);
1563 if (sock6 != -1) {
1564 has_ipv6 = 1;
1565 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1566 event_add(&e6, NULL);
1569 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1570 event_add(&imsgev, NULL);
1572 #ifdef SIGINFO
1573 has_siginfo = 1;
1574 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1575 signal_add(&siginfo, NULL);
1576 #endif
1577 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1578 signal_add(&sigusr2, NULL);
1580 sandbox_server_process();
1581 event_dispatch();
1582 _exit(0);
1585 int
1586 client_tree_cmp(struct client *a, struct client *b)
1588 if (a->id == b->id)
1589 return 0;
1590 else if (a->id < b->id)
1591 return -1;
1592 else
1593 return +1;
1596 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)