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);
1007 /* max url len + \r\n */
1008 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1009 log_err(c, "too much data received");
1010 start_reply(c, BAD_REQUEST, "bad request");
1011 return;
1014 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1015 if (c->req == NULL) {
1016 /* not enough data yet. */
1017 bufferevent_enable(bev, EVBUFFER_READ);
1018 return;
1021 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1022 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1023 log_err(c, "IRI parse error: %s", parse_err);
1024 start_reply(c, BAD_REQUEST, "bad request");
1025 return;
1028 if (apply_reverse_proxy(c))
1029 return;
1031 /* ignore the port number */
1032 if (strcmp(c->iri.schema, "gemini") ||
1033 strcmp(decoded, c->domain)) {
1034 start_reply(c, PROXY_REFUSED, "won't proxy request");
1035 return;
1038 if (apply_require_ca(c) ||
1039 apply_block_return(c)||
1040 apply_fastcgi(c))
1041 return;
1043 if (c->host->entrypoint != NULL) {
1044 c->loc = 0;
1045 start_cgi(c->host->entrypoint, c->iri.path, c);
1046 return;
1049 open_file(c);
1052 void
1053 client_write(struct bufferevent *bev, void *d)
1055 struct client *c = d;
1056 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1057 char buf[BUFSIZ];
1058 ssize_t r;
1060 switch (c->type) {
1061 case REQUEST_UNDECIDED:
1063 * Ignore spurious calls when we still don't have idea
1064 * what to do with the request.
1066 break;
1068 case REQUEST_FILE:
1069 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1070 log_warn(c, "read: %s", strerror(errno));
1071 client_error(bev, EVBUFFER_ERROR, c);
1072 return;
1073 } else if (r == 0) {
1074 client_close(c);
1075 return;
1076 } else if (r != sizeof(buf))
1077 c->type = REQUEST_DONE;
1078 bufferevent_write(bev, buf, r);
1079 break;
1081 case REQUEST_DIR:
1082 /* TODO: handle big big directories better */
1083 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1084 evbuffer_add_printf(out, "=> %s\n",
1085 c->dir[c->diroff]->d_name);
1086 free(c->dir[c->diroff]);
1088 free(c->dir);
1089 c->dir = NULL;
1091 c->type = REQUEST_DONE;
1093 event_add(&c->bev->ev_write, NULL);
1094 break;
1096 case REQUEST_CGI:
1097 case REQUEST_FCGI:
1098 case REQUEST_PROXY:
1100 * Here we depend on on the cgi script or fastcgi
1101 * connection to provide data.
1103 break;
1105 case REQUEST_DONE:
1106 if (EVBUFFER_LENGTH(out) == 0)
1107 client_close(c);
1108 break;
1112 static void
1113 client_error(struct bufferevent *bev, short error, void *d)
1115 struct client *c = d;
1117 c->type = REQUEST_DONE;
1119 if (error & EVBUFFER_TIMEOUT) {
1120 log_warn(c, "timeout reached, "
1121 "forcefully closing the connection");
1122 if (c->code == 0)
1123 start_reply(c, BAD_REQUEST, "timeout");
1124 else
1125 client_close(c);
1126 return;
1129 if (error & EVBUFFER_EOF) {
1130 client_close(c);
1131 return;
1134 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1135 client_close(c);
1138 void
1139 start_reply(struct client *c, int code, const char *meta)
1141 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1142 const char *lang;
1143 int r, rr;
1145 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1147 c->code = code;
1148 c->meta = meta;
1150 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1151 if (r == -1)
1152 goto err;
1154 /* 2 digit status + space + 1024 max reply */
1155 if (r > 1027)
1156 goto overflow;
1158 if (c->type != REQUEST_CGI &&
1159 c->type != REQUEST_FCGI &&
1160 c->type != REQUEST_PROXY &&
1161 !strcmp(meta, "text/gemini") &&
1162 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1163 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1164 if (rr == -1)
1165 goto err;
1166 if (r + rr > 1027)
1167 goto overflow;
1170 bufferevent_write(c->bev, "\r\n", 2);
1172 if (!vhost_disable_log(c->host, c->iri.path))
1173 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1175 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1176 c->type = REQUEST_DONE;
1178 return;
1180 err:
1181 log_err(c, "evbuffer_add_printf error: no memory");
1182 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1183 client_close(c);
1184 return;
1186 overflow:
1187 log_warn(c, "reply header overflow");
1188 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1189 start_reply(c, TEMP_FAILURE, "internal error");
1192 static void
1193 client_close_ev(int fd, short event, void *d)
1195 struct client *c = d;
1197 switch (tls_close(c->ctx)) {
1198 case TLS_WANT_POLLIN:
1199 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1200 break;
1201 case TLS_WANT_POLLOUT:
1202 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1203 break;
1206 connected_clients--;
1208 free(c->req);
1210 tls_free(c->ctx);
1211 c->ctx = NULL;
1213 free(c->header);
1215 if (c->pfd != -1)
1216 close(c->pfd);
1218 if (c->dir != NULL)
1219 free(c->dir);
1221 close(c->fd);
1222 c->fd = -1;
1225 static void
1226 client_proxy_close(int fd, short event, void *d)
1228 struct tls *ctx = d;
1230 if (ctx == NULL) {
1231 close(fd);
1232 return;
1235 switch (tls_close(ctx)) {
1236 case TLS_WANT_POLLIN:
1237 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1238 break;
1239 case TLS_WANT_POLLOUT:
1240 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1241 break;
1244 tls_free(ctx);
1245 close(fd);
1248 void
1249 client_close(struct client *c)
1252 * We may end up calling client_close in various situations
1253 * and for the most unexpected reasons. Therefore, we need to
1254 * ensure that everything is properly released once we reach
1255 * this point.
1258 SPLAY_REMOVE(client_tree_id, &clients, c);
1260 if (c->cgibev != NULL) {
1261 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1262 bufferevent_free(c->cgibev);
1263 c->cgibev = NULL;
1264 close(c->pfd);
1265 c->pfd = -1;
1268 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1269 bufferevent_free(c->bev);
1270 c->bev = NULL;
1272 if (c->proxybev != NULL) {
1273 if (event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL))
1274 event_del(&c->proxyev);
1276 if (c->pfd != -1 && c->proxyctx != NULL) {
1277 /* shut down the proxy TLS connection */
1278 client_proxy_close(c->pfd, 0, c->proxyctx);
1279 c->pfd = -1;
1282 bufferevent_free(c->proxybev);
1285 client_close_ev(c->fd, 0, c);
1288 static void
1289 cgi_read(struct bufferevent *bev, void *d)
1291 struct client *client = d;
1292 struct evbuffer *src = EVBUFFER_INPUT(bev);
1293 char *header;
1294 size_t len;
1295 int code;
1297 /* intercept the header */
1298 if (client->code == 0) {
1299 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1300 if (header == NULL) {
1301 /* max reply + \r\n */
1302 if (EVBUFFER_LENGTH(src) > 1029) {
1303 log_warn(client, "CGI script is trying to "
1304 "send a header too long.");
1305 cgi_error(bev, EVBUFFER_READ, client);
1308 /* wait a bit */
1309 return;
1312 if (len < 3 || len > 1029 ||
1313 !isdigit(header[0]) ||
1314 !isdigit(header[1]) ||
1315 !isspace(header[2])) {
1316 free(header);
1317 log_warn(client, "CGI script is trying to send a "
1318 "malformed header");
1319 cgi_error(bev, EVBUFFER_READ, client);
1320 return;
1323 client->header = header;
1324 code = (header[0] - '0') * 10 + (header[1] - '0');
1326 if (code < 10 || code >= 70) {
1327 log_warn(client, "CGI script is trying to send an "
1328 "invalid reply code (%d)", code);
1329 cgi_error(bev, EVBUFFER_READ, client);
1330 return;
1333 start_reply(client, code, header + 3);
1335 if (client->code < 20 || client->code > 29) {
1336 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1337 return;
1341 bufferevent_write_buffer(client->bev, src);
1344 static void
1345 cgi_write(struct bufferevent *bev, void *d)
1348 * Never called. We don't send data to a CGI script.
1350 abort();
1353 static void
1354 cgi_error(struct bufferevent *bev, short error, void *d)
1356 struct client *client = d;
1358 if (error & EVBUFFER_ERROR)
1359 log_err(client, "%s: evbuffer error (%x): %s",
1360 __func__, error, strerror(errno));
1362 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1363 bufferevent_free(bev);
1364 client->cgibev = NULL;
1366 close(client->pfd);
1367 client->pfd = -1;
1369 client->type = REQUEST_DONE;
1370 if (client->code != 0)
1371 client_write(client->bev, client);
1372 else
1373 start_reply(client, CGI_ERROR, "CGI error");
1376 static void
1377 do_accept(int sock, short et, void *d)
1379 struct client *c;
1380 struct sockaddr_storage addr;
1381 struct sockaddr *saddr;
1382 socklen_t len;
1383 int fd;
1385 saddr = (struct sockaddr*)&addr;
1386 len = sizeof(addr);
1387 if ((fd = accept(sock, saddr, &len)) == -1) {
1388 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1389 errno == ECONNABORTED)
1390 return;
1391 fatal("accept: %s", strerror(errno));
1394 mark_nonblock(fd);
1396 c = xcalloc(1, sizeof(*c));
1397 c->id = ++server_client_id;
1398 c->fd = fd;
1399 c->pfd = -1;
1400 c->addr = addr;
1402 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1403 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1404 close(c->fd);
1405 free(c);
1406 return;
1409 SPLAY_INSERT(client_tree_id, &clients, c);
1410 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1411 connected_clients++;
1414 static struct client *
1415 client_by_id(int id)
1417 struct client *c;
1419 if ((c = try_client_by_id(id)) == NULL)
1420 fatal("in client_by_id: invalid id %d", id);
1421 return c;
1424 struct client *
1425 try_client_by_id(int id)
1427 struct client find;
1429 find.id = id;
1430 return SPLAY_FIND(client_tree_id, &clients, &find);
1433 static void
1434 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1436 struct client *c;
1438 c = client_by_id(imsg->hdr.peerid);
1440 if ((c->pfd = imsg->fd) == -1) {
1441 start_reply(c, TEMP_FAILURE, "internal server error");
1442 return;
1445 c->type = REQUEST_CGI;
1447 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1448 cgi_error, c);
1450 bufferevent_enable(c->cgibev, EV_READ);
1453 static void
1454 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1456 struct client *c;
1457 int id;
1459 id = imsg->hdr.peerid;
1461 if ((c = try_client_by_id(id)) == NULL) {
1462 if (imsg->fd != -1)
1463 close(imsg->fd);
1464 return;
1467 if ((c->pfd = imsg->fd) == -1) {
1468 start_reply(c, CGI_ERROR, "CGI error");
1469 return;
1472 mark_nonblock(c->pfd);
1474 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1475 fcgi_error, c);
1476 if (c->cgibev == NULL) {
1477 start_reply(c, TEMP_FAILURE, "internal server error");
1478 return;
1481 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1482 fcgi_req(c);
1485 static void
1486 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1488 struct client *c;
1489 int id;
1491 id = imsg->hdr.peerid;
1492 if ((c = try_client_by_id(id)) == NULL) {
1493 if (imsg->fd != -1)
1494 close(imsg->fd);
1495 return;
1498 if ((c->pfd = imsg->fd) == -1) {
1499 start_reply(c, PROXY_ERROR, "proxy error");
1500 return;
1503 mark_nonblock(c->pfd);
1505 if (proxy_init(c) == -1)
1506 start_reply(c, PROXY_ERROR, "proxy error");
1509 static void
1510 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1513 * don't call event_loopbreak since we want to finish to
1514 * handle the ongoing connections.
1517 shutting_down = 1;
1519 event_del(&e4);
1520 if (has_ipv6)
1521 event_del(&e6);
1522 if (has_siginfo)
1523 signal_del(&siginfo);
1524 event_del(&imsgev);
1525 signal_del(&sigusr2);
1528 static void
1529 handle_dispatch_imsg(int fd, short ev, void *d)
1531 struct imsgbuf *ibuf = d;
1532 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1535 static void
1536 handle_siginfo(int fd, short ev, void *d)
1538 log_info(NULL, "%d connected clients", connected_clients);
1541 void
1542 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1544 ctx = ctx_;
1546 SPLAY_INIT(&clients);
1548 event_init();
1550 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1551 event_add(&e4, NULL);
1553 if (sock6 != -1) {
1554 has_ipv6 = 1;
1555 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1556 event_add(&e6, NULL);
1559 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1560 event_add(&imsgev, NULL);
1562 #ifdef SIGINFO
1563 has_siginfo = 1;
1564 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1565 signal_add(&siginfo, NULL);
1566 #endif
1567 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1568 signal_add(&sigusr2, NULL);
1570 sandbox_server_process();
1571 event_dispatch();
1572 _exit(0);
1575 int
1576 client_tree_cmp(struct client *a, struct client *b)
1578 if (a->id == b->id)
1579 return 0;
1580 else if (a->id < b->id)
1581 return -1;
1582 else
1583 return +1;
1586 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)