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>
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*);
74 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
75 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
76 static void handle_imsg_conn_fd(struct imsgbuf*, struct imsg*, size_t);
77 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
78 static void handle_dispatch_imsg(int, short, void *);
79 static void handle_siginfo(int, short, void*);
81 static imsg_handlerfn *handlers[] = {
82 [IMSG_QUIT] = handle_imsg_quit,
83 [IMSG_CGI_RES] = handle_imsg_cgi_res,
84 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
85 [IMSG_CONN_FD] = handle_imsg_conn_fd,
86 };
88 static uint32_t server_client_id;
90 struct client_tree_id clients;
92 static inline int
93 matches(const char *pattern, const char *path)
94 {
95 if (*path == '/')
96 path++;
97 return !fnmatch(pattern, path, 0);
98 }
100 const char *
101 vhost_lang(struct vhost *v, const char *path)
103 struct location *loc;
105 if (v == NULL || path == NULL)
106 return NULL;
108 loc = TAILQ_FIRST(&v->locations);
109 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
110 if (loc->lang != NULL) {
111 if (matches(loc->match, path))
112 return loc->lang;
116 return TAILQ_FIRST(&v->locations)->lang;
119 const char *
120 vhost_default_mime(struct vhost *v, const char *path)
122 struct location *loc;
123 const char *default_mime = "application/octet-stream";
125 if (v == NULL || path == NULL)
126 return default_mime;
128 loc = TAILQ_FIRST(&v->locations);
129 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
130 if (loc->default_mime != NULL) {
131 if (matches(loc->match, path))
132 return loc->default_mime;
136 loc = TAILQ_FIRST(&v->locations);
137 if (loc->default_mime != NULL)
138 return loc->default_mime;
139 return default_mime;
142 const char *
143 vhost_index(struct vhost *v, const char *path)
145 struct location *loc;
146 const char *index = "index.gmi";
148 if (v == NULL || path == NULL)
149 return index;
151 loc = TAILQ_FIRST(&v->locations);
152 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
153 if (loc->index != NULL) {
154 if (matches(loc->match, path))
155 return loc->index;
159 loc = TAILQ_FIRST(&v->locations);
160 if (loc->index != NULL)
161 return loc->index;
162 return index;
165 int
166 vhost_auto_index(struct vhost *v, const char *path)
168 struct location *loc;
170 if (v == NULL || path == NULL)
171 return 0;
173 loc = TAILQ_FIRST(&v->locations);
174 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
175 if (loc->auto_index != 0) {
176 if (matches(loc->match, path))
177 return loc->auto_index == 1;
181 loc = TAILQ_FIRST(&v->locations);
182 return loc->auto_index == 1;
185 int
186 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
188 struct location *loc;
190 if (v == NULL || path == NULL)
191 return 0;
193 loc = TAILQ_FIRST(&v->locations);
194 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
195 if (loc->block_code != 0) {
196 if (matches(loc->match, path)) {
197 *code = loc->block_code;
198 *fmt = loc->block_fmt;
199 return 1;
204 loc = TAILQ_FIRST(&v->locations);
205 *code = loc->block_code;
206 *fmt = loc->block_fmt;
207 return loc->block_code != 0;
210 int
211 vhost_fastcgi(struct vhost *v, const char *path)
213 struct location *loc;
215 if (v == NULL || path == NULL)
216 return -1;
218 loc = TAILQ_FIRST(&v->locations);
219 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
220 if (loc->fcgi != -1)
221 if (matches(loc->match, path))
222 return loc->fcgi;
225 loc = TAILQ_FIRST(&v->locations);
226 return loc->fcgi;
229 int
230 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
232 struct location *loc;
233 size_t l = 0;
235 if (v == NULL || path == NULL)
236 return -1;
238 loc = TAILQ_FIRST(&v->locations);
239 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
240 l++;
241 if (loc->dirfd != -1)
242 if (matches(loc->match, path)) {
243 *retloc = l;
244 return loc->dirfd;
248 *retloc = 0;
249 loc = TAILQ_FIRST(&v->locations);
250 return loc->dirfd;
253 int
254 vhost_strip(struct vhost *v, const char *path)
256 struct location *loc;
258 if (v == NULL || path == NULL)
259 return 0;
261 loc = TAILQ_FIRST(&v->locations);
262 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
263 if (loc->strip != 0) {
264 if (matches(loc->match, path))
265 return loc->strip;
269 loc = TAILQ_FIRST(&v->locations);
270 return loc->strip;
273 X509_STORE *
274 vhost_require_ca(struct vhost *v, const char *path)
276 struct location *loc;
278 if (v == NULL || path == NULL)
279 return NULL;
281 loc = TAILQ_FIRST(&v->locations);
282 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
283 if (loc->reqca != NULL) {
284 if (matches(loc->match, path))
285 return loc->reqca;
289 loc = TAILQ_FIRST(&v->locations);
290 return loc->reqca;
293 int
294 vhost_disable_log(struct vhost *v, const char *path)
296 struct location *loc;
298 if (v == NULL || path == NULL)
299 return 0;
301 loc = TAILQ_FIRST(&v->locations);
302 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
303 if (loc->disable_log && matches(loc->match, path))
304 return 1;
307 loc = TAILQ_FIRST(&v->locations);
308 return loc->disable_log;
311 static int
312 check_path(struct client *c, const char *path, int *fd)
314 struct stat sb;
315 const char *p;
316 int dirfd, strip;
318 assert(path != NULL);
320 /*
321 * in send_dir we add an initial / (to be redirect-friendly),
322 * but here we want to skip it
323 */
324 if (*path == '/')
325 path++;
327 strip = vhost_strip(c->host, path);
328 p = strip_path(path, strip);
330 if (*p == '/')
331 p = p+1;
332 if (*p == '\0')
333 p = ".";
335 dirfd = vhost_dirfd(c->host, path, &c->loc);
336 log_debug(c, "check_path: strip=%d path=%s original=%s",
337 strip, p, path);
338 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
339 if (errno == EACCES)
340 log_info(c, "can't open %s: %s", p, strerror(errno));
341 return FILE_MISSING;
344 if (fstat(*fd, &sb) == -1) {
345 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
346 return FILE_MISSING;
349 if (S_ISDIR(sb.st_mode))
350 return FILE_DIRECTORY;
352 if (sb.st_mode & S_IXUSR)
353 return FILE_EXECUTABLE;
355 return FILE_EXISTS;
358 static void
359 open_file(struct client *c)
361 switch (check_path(c, c->iri.path, &c->pfd)) {
362 case FILE_EXECUTABLE:
363 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
364 start_cgi(c->iri.path, "", c);
365 return;
368 /* fallthrough */
370 case FILE_EXISTS:
371 c->type = REQUEST_FILE;
372 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
373 return;
375 case FILE_DIRECTORY:
376 open_dir(c);
377 return;
379 case FILE_MISSING:
380 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
381 check_for_cgi(c);
382 return;
384 start_reply(c, NOT_FOUND, "not found");
385 return;
387 default:
388 /* unreachable */
389 abort();
393 /*
394 * the inverse of this algorithm, i.e. starting from the start of the
395 * path + strlen(cgi), and checking if each component, should be
396 * faster. But it's tedious to write. This does the opposite: starts
397 * from the end and strip one component at a time, until either an
398 * executable is found or we emptied the path.
399 */
400 static void
401 check_for_cgi(struct client *c)
403 char path[PATH_MAX];
404 char *end;
406 strlcpy(path, c->iri.path, sizeof(path));
407 end = strchr(path, '\0');
409 while (end > path) {
410 /*
411 * go up one level. UNIX paths are simple and POSIX
412 * dirname, with its ambiguities on if the given
413 * pointer is changed or not, gives me headaches.
414 */
415 while (*end != '/' && end > path)
416 end--;
418 if (end == path)
419 break;
421 *end = '\0';
423 switch (check_path(c, path, &c->pfd)) {
424 case FILE_EXECUTABLE:
425 start_cgi(path, end+1, c);
426 return;
427 case FILE_MISSING:
428 break;
429 default:
430 goto err;
433 *end = '/';
434 end--;
437 err:
438 start_reply(c, NOT_FOUND, "not found");
439 return;
442 void
443 mark_nonblock(int fd)
445 int flags;
447 if ((flags = fcntl(fd, F_GETFL)) == -1)
448 fatal("fcntl(F_GETFL): %s", strerror(errno));
449 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
450 fatal("fcntl(F_SETFL): %s", strerror(errno));
453 static void
454 handle_handshake(int fd, short ev, void *d)
456 struct client *c = d;
457 struct vhost *h;
458 struct alist *a;
459 const char *servname;
460 const char *parse_err = "unknown error";
462 switch (tls_handshake(c->ctx)) {
463 case 0: /* success */
464 case -1: /* already handshaked */
465 break;
466 case TLS_WANT_POLLIN:
467 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
468 return;
469 case TLS_WANT_POLLOUT:
470 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
471 return;
472 default:
473 /* unreachable */
474 abort();
477 c->bev = bufferevent_new(fd, client_read, client_write,
478 client_error, c);
479 if (c->bev == NULL)
480 fatal("%s: failed to allocate client buffer: %s",
481 __func__, strerror(errno));
483 event_set(&c->bev->ev_read, c->fd, EV_READ,
484 client_tls_readcb, c->bev);
485 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
486 client_tls_writecb, c->bev);
488 #if HAVE_LIBEVENT2
489 evbuffer_unfreeze(c->bev->input, 0);
490 evbuffer_unfreeze(c->bev->output, 1);
491 #endif
493 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
494 log_debug(c, "handshake: missing SNI");
495 goto err;
498 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
499 log_info(c, "puny_decode: %s", parse_err);
500 goto err;
503 TAILQ_FOREACH(h, &hosts, vhosts) {
504 if (matches(h->domain, c->domain))
505 goto found;
506 TAILQ_FOREACH(a, &h->aliases, aliases) {
507 if (matches(a->alias, c->domain))
508 goto found;
512 found:
513 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
514 servname != NULL ? servname : "(null)",
515 c->domain,
516 h != NULL ? h->domain : "(null)");
518 if (h != NULL) {
519 c->host = h;
520 bufferevent_enable(c->bev, EV_READ);
521 return;
524 err:
525 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
528 static const char *
529 strip_path(const char *path, int strip)
531 char *t;
533 while (strip > 0) {
534 if ((t = strchr(path, '/')) == NULL) {
535 path = strchr(path, '\0');
536 break;
538 path = t;
539 strip--;
542 return path;
545 static void
546 fmt_sbuf(const char *fmt, struct client *c, const char *path)
548 size_t i;
549 char buf[32];
551 memset(buf, 0, sizeof(buf));
552 for (i = 0; *fmt; ++fmt) {
553 if (i == sizeof(buf)-1 || *fmt == '%') {
554 strlcat(c->sbuf, buf, sizeof(c->sbuf));
555 memset(buf, 0, sizeof(buf));
556 i = 0;
559 if (*fmt != '%') {
560 buf[i++] = *fmt;
561 continue;
564 switch (*++fmt) {
565 case '%':
566 strlcat(c->sbuf, "%", sizeof(c->sbuf));
567 break;
568 case 'p':
569 if (*path != '/')
570 strlcat(c->sbuf, "/", sizeof(c->sbuf));
571 strlcat(c->sbuf, path, sizeof(c->sbuf));
572 break;
573 case 'q':
574 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
575 break;
576 case 'P':
577 snprintf(buf, sizeof(buf), "%d", conf.port);
578 strlcat(c->sbuf, buf, sizeof(c->sbuf));
579 memset(buf, 0, sizeof(buf));
580 break;
581 case 'N':
582 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
583 break;
584 default:
585 fatal("%s: unknown fmt specifier %c",
586 __func__, *fmt);
590 if (i != 0)
591 strlcat(c->sbuf, buf, sizeof(c->sbuf));
594 /* 1 if a matching `block return' (and apply it), 0 otherwise */
595 static int
596 apply_block_return(struct client *c)
598 const char *fmt, *path;
599 int code;
601 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
602 return 0;
604 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
605 fmt_sbuf(fmt, c, path);
607 start_reply(c, code, c->sbuf);
608 return 1;
611 static struct proxy *
612 matched_proxy(struct client *c)
614 struct proxy *p;
615 const char *proto;
616 const char *host;
617 const char *port;
619 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
620 if ((proto = p->match_proto) == NULL)
621 proto = "gemini";
622 if ((host = p->match_host) == NULL)
623 host = "*";
624 if ((port = p->match_port) == NULL)
625 port = "*";
627 if (matches(proto, c->iri.schema) &&
628 matches(host, c->domain) &&
629 matches(port, c->iri.port))
630 return p;
633 return NULL;
636 static int
637 check_matching_certificate(X509_STORE *store, struct client *c)
639 const uint8_t *cert;
640 size_t len;
642 if (!tls_peer_cert_provided(c->ctx)) {
643 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
644 return 1;
647 cert = tls_peer_cert_chain_pem(c->ctx, &len);
648 if (!validate_against_ca(store, cert, len)) {
649 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
650 return 1;
653 return 0;
656 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
657 static int
658 apply_reverse_proxy(struct client *c)
660 struct proxy *p;
661 struct connreq r;
663 if ((p = matched_proxy(c)) == NULL)
664 return 0;
666 c->proxy = p;
668 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
669 return 1;
671 log_debug(c, "opening proxy connection for %s:%s",
672 p->host, p->port);
674 strlcpy(r.host, p->host, sizeof(r.host));
675 strlcpy(r.port, p->port, sizeof(r.port));
677 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
678 imsg_flush(&exibuf);
680 return 1;
683 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
684 static int
685 apply_fastcgi(struct client *c)
687 int id;
688 struct fcgi *f;
690 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
691 return 0;
693 f = &fcgi[id];
695 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
696 f->path, f->port, f->prog);
698 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
699 &id, sizeof(id));
700 imsg_flush(&exibuf);
701 return 1;
704 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
705 static int
706 apply_require_ca(struct client *c)
708 X509_STORE *store;
710 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
711 return 0;
712 return check_matching_certificate(store, c);
715 static size_t
716 host_nth(struct vhost *h)
718 struct vhost *v;
719 size_t i = 0;
721 TAILQ_FOREACH(v, &hosts, vhosts) {
722 if (v == h)
723 return i;
724 i++;
727 abort();
730 static void
731 start_cgi(const char *spath, const char *relpath, struct client *c)
733 char addr[NI_MAXHOST];
734 const char *t;
735 struct cgireq req;
736 int e;
738 c->type = REQUEST_CGI;
740 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
741 addr, sizeof(addr),
742 NULL, 0,
743 NI_NUMERICHOST);
744 if (e != 0)
745 fatal("getnameinfo failed");
747 memset(&req, 0, sizeof(req));
749 memcpy(req.buf, c->req, c->reqlen);
751 req.iri_schema_off = c->iri.schema - c->req;
752 req.iri_host_off = c->iri.host - c->req;
753 req.iri_port_off = c->iri.port - c->req;
754 req.iri_path_off = c->iri.path - c->req;
755 req.iri_query_off = c->iri.query - c->req;
756 req.iri_fragment_off = c->iri.fragment - c->req;
758 req.iri_portno = c->iri.port_no;
760 strlcpy(req.spath, spath, sizeof(req.spath));
761 strlcpy(req.relpath, relpath, sizeof(req.relpath));
762 strlcpy(req.addr, addr, sizeof(req.addr));
764 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
765 strlcpy(req.subject, t, sizeof(req.subject));
766 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
767 strlcpy(req.issuer, t, sizeof(req.issuer));
768 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
769 strlcpy(req.hash, t, sizeof(req.hash));
770 if ((t = tls_conn_version(c->ctx)) != NULL)
771 strlcpy(req.version, t, sizeof(req.version));
772 if ((t = tls_conn_cipher(c->ctx)) != NULL)
773 strlcpy(req.cipher, t, sizeof(req.cipher));
775 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
776 req.notbefore = tls_peer_cert_notbefore(c->ctx);
777 req.notafter = tls_peer_cert_notafter(c->ctx);
779 req.host_off = host_nth(c->host);
780 req.loc_off = c->loc;
782 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
783 imsg_flush(&exibuf);
785 close(c->pfd);
788 static void
789 open_dir(struct client *c)
791 size_t len;
792 int dirfd, root;
793 char *before_file;
795 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
797 len = strlen(c->iri.path);
798 if (len > 0 && !ends_with(c->iri.path, "/")) {
799 redirect_canonical_dir(c);
800 return;
803 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
804 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
805 if (!ends_with(c->sbuf, "/"))
806 strlcat(c->sbuf, "/", sizeof(c->sbuf));
807 before_file = strchr(c->sbuf, '\0');
808 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
809 sizeof(c->sbuf));
810 if (len >= sizeof(c->sbuf)) {
811 start_reply(c, TEMP_FAILURE, "internal server error");
812 return;
815 c->iri.path = c->sbuf;
817 /* close later unless we have to generate the dir listing */
818 dirfd = c->pfd;
819 c->pfd = -1;
821 switch (check_path(c, c->iri.path, &c->pfd)) {
822 case FILE_EXECUTABLE:
823 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
824 start_cgi(c->iri.path, "", c);
825 break;
828 /* fallthrough */
830 case FILE_EXISTS:
831 c->type = REQUEST_FILE;
832 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
833 break;
835 case FILE_DIRECTORY:
836 start_reply(c, TEMP_REDIRECT, c->sbuf);
837 break;
839 case FILE_MISSING:
840 *before_file = '\0';
842 if (!vhost_auto_index(c->host, c->iri.path)) {
843 start_reply(c, NOT_FOUND, "not found");
844 break;
847 c->type = REQUEST_DIR;
849 c->dirlen = scandir_fd(dirfd, &c->dir,
850 root ? select_non_dotdot : select_non_dot,
851 alphasort);
852 if (c->dirlen == -1) {
853 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
854 c->pfd, c->host->domain, c->iri.path, strerror(errno));
855 start_reply(c, TEMP_FAILURE, "internal server error");
856 return;
858 c->diroff = 0;
859 c->off = 0;
861 start_reply(c, SUCCESS, "text/gemini");
862 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
863 "# Index of %s\n\n", c->iri.path);
864 return;
866 default:
867 /* unreachable */
868 abort();
871 close(dirfd);
874 static void
875 redirect_canonical_dir(struct client *c)
877 size_t len;
879 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
880 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
881 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
883 if (len >= sizeof(c->sbuf)) {
884 start_reply(c, TEMP_FAILURE, "internal server error");
885 return;
888 start_reply(c, TEMP_REDIRECT, c->sbuf);
891 static void
892 client_tls_readcb(int fd, short event, void *d)
894 struct bufferevent *bufev = d;
895 struct client *client = bufev->cbarg;
896 ssize_t ret;
897 size_t len;
898 int what = EVBUFFER_READ;
899 int howmuch = IBUF_READ_SIZE;
900 char buf[IBUF_READ_SIZE];
902 if (event == EV_TIMEOUT) {
903 what |= EVBUFFER_TIMEOUT;
904 goto err;
907 if (bufev->wm_read.high != 0)
908 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
910 switch (ret = tls_read(client->ctx, buf, howmuch)) {
911 case TLS_WANT_POLLIN:
912 case TLS_WANT_POLLOUT:
913 goto retry;
914 case -1:
915 what |= EVBUFFER_ERROR;
916 goto err;
918 len = ret;
920 if (len == 0) {
921 what |= EVBUFFER_EOF;
922 goto err;
925 if (evbuffer_add(bufev->input, buf, len) == -1) {
926 what |= EVBUFFER_ERROR;
927 goto err;
930 event_add(&bufev->ev_read, NULL);
931 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
932 return;
933 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
934 /*
935 * here we could implement a read pressure policy.
936 */
939 if (bufev->readcb != NULL)
940 (*bufev->readcb)(bufev, bufev->cbarg);
942 return;
944 retry:
945 event_add(&bufev->ev_read, NULL);
946 return;
948 err:
949 (*bufev->errorcb)(bufev, what, bufev->cbarg);
952 static void
953 client_tls_writecb(int fd, short event, void *d)
955 struct bufferevent *bufev = d;
956 struct client *client = bufev->cbarg;
957 ssize_t ret;
958 size_t len;
959 short what = EVBUFFER_WRITE;
961 if (event == EV_TIMEOUT) {
962 what |= EVBUFFER_TIMEOUT;
963 goto err;
966 if (EVBUFFER_LENGTH(bufev->output) != 0) {
967 ret = tls_write(client->ctx,
968 EVBUFFER_DATA(bufev->output),
969 EVBUFFER_LENGTH(bufev->output));
970 switch (ret) {
971 case TLS_WANT_POLLIN:
972 case TLS_WANT_POLLOUT:
973 goto retry;
974 case -1:
975 what |= EVBUFFER_ERROR;
976 goto err;
978 len = ret;
979 evbuffer_drain(bufev->output, len);
982 if (EVBUFFER_LENGTH(bufev->output) != 0)
983 event_add(&bufev->ev_write, NULL);
985 if (bufev->writecb != NULL &&
986 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
987 (*bufev->writecb)(bufev, bufev->cbarg);
988 return;
990 retry:
991 event_add(&bufev->ev_write, NULL);
992 return;
993 err:
994 log_err(client, "tls error: %s", tls_error(client->ctx));
995 (*bufev->errorcb)(bufev, what, bufev->cbarg);
998 static void
999 client_read(struct bufferevent *bev, void *d)
1001 struct client *c = d;
1002 struct evbuffer *src = EVBUFFER_INPUT(bev);
1003 const char *parse_err = "invalid request";
1004 char decoded[DOMAIN_NAME_LEN];
1005 size_t len;
1007 bufferevent_disable(bev, EVBUFFER_READ);
1010 * libevent2 can still somehow call this function, even
1011 * though I never enable EV_READ in the bufferevent. If
1012 * that's the case, bail out.
1014 if (c->type != REQUEST_UNDECIDED)
1015 return;
1017 /* max url len + \r\n */
1018 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1019 log_err(c, "too much data received");
1020 start_reply(c, BAD_REQUEST, "bad request");
1021 return;
1024 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1025 if (c->req == NULL) {
1026 /* not enough data yet. */
1027 bufferevent_enable(bev, EVBUFFER_READ);
1028 return;
1030 c->reqlen = strlen(c->req);
1031 if (c->reqlen > 1024+2) {
1032 log_err(c, "URL too long");
1033 start_reply(c, BAD_REQUEST, "bad request");
1034 return;
1037 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1038 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1039 log_err(c, "IRI parse error: %s", parse_err);
1040 start_reply(c, BAD_REQUEST, "bad request");
1041 return;
1044 if (apply_reverse_proxy(c))
1045 return;
1047 /* ignore the port number */
1048 if (strcmp(c->iri.schema, "gemini") ||
1049 strcmp(decoded, c->domain)) {
1050 start_reply(c, PROXY_REFUSED, "won't proxy request");
1051 return;
1054 if (apply_require_ca(c) ||
1055 apply_block_return(c)||
1056 apply_fastcgi(c))
1057 return;
1059 if (c->host->entrypoint != NULL) {
1060 c->loc = 0;
1061 start_cgi(c->host->entrypoint, c->iri.path, c);
1062 return;
1065 open_file(c);
1068 void
1069 client_write(struct bufferevent *bev, void *d)
1071 struct client *c = d;
1072 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1073 char nam[PATH_MAX];
1074 char buf[BUFSIZ];
1075 ssize_t r;
1077 switch (c->type) {
1078 case REQUEST_UNDECIDED:
1080 * Ignore spurious calls when we still don't have idea
1081 * what to do with the request.
1083 break;
1085 case REQUEST_FILE:
1086 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1087 log_warn(c, "read: %s", strerror(errno));
1088 client_error(bev, EVBUFFER_ERROR, c);
1089 return;
1090 } else if (r == 0) {
1091 client_close(c);
1092 return;
1093 } else if (r != sizeof(buf))
1094 c->type = REQUEST_DONE;
1095 bufferevent_write(bev, buf, r);
1096 break;
1098 case REQUEST_DIR:
1099 /* TODO: handle big big directories better */
1100 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1101 const char *sufx = "";
1103 encode_path(nam, sizeof(nam),
1104 c->dir[c->diroff]->d_name);
1105 if (c->dir[c->diroff]->d_type == DT_DIR)
1106 sufx = "/";
1107 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1108 free(c->dir[c->diroff]);
1110 free(c->dir);
1111 c->dir = NULL;
1113 c->type = REQUEST_DONE;
1115 event_add(&c->bev->ev_write, NULL);
1116 break;
1118 case REQUEST_CGI:
1119 case REQUEST_FCGI:
1120 case REQUEST_PROXY:
1122 * Here we depend on the cgi/fastcgi or proxy
1123 * connection to provide data.
1125 break;
1127 case REQUEST_DONE:
1128 if (EVBUFFER_LENGTH(out) == 0)
1129 client_close(c);
1130 break;
1134 static void
1135 client_error(struct bufferevent *bev, short error, void *d)
1137 struct client *c = d;
1139 c->type = REQUEST_DONE;
1141 if (error & EVBUFFER_TIMEOUT) {
1142 log_warn(c, "timeout reached, "
1143 "forcefully closing the connection");
1144 if (c->code == 0)
1145 start_reply(c, BAD_REQUEST, "timeout");
1146 else
1147 client_close(c);
1148 return;
1151 if (error & EVBUFFER_EOF) {
1152 client_close(c);
1153 return;
1156 log_err(c, "unknown bufferevent error %x", error);
1157 client_close(c);
1160 void
1161 start_reply(struct client *c, int code, const char *meta)
1163 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1164 const char *lang;
1165 int r, rr;
1167 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1169 c->code = code;
1170 c->meta = meta;
1172 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1173 if (r == -1)
1174 goto err;
1176 /* 2 digit status + space + 1024 max reply */
1177 if (r > 1027)
1178 goto overflow;
1180 if (c->type != REQUEST_CGI &&
1181 c->type != REQUEST_FCGI &&
1182 c->type != REQUEST_PROXY &&
1183 !strcmp(meta, "text/gemini") &&
1184 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1185 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1186 if (rr == -1)
1187 goto err;
1188 if (r + rr > 1027)
1189 goto overflow;
1192 bufferevent_write(c->bev, "\r\n", 2);
1194 if (!vhost_disable_log(c->host, c->iri.path))
1195 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1197 if (code != 20)
1198 c->type = REQUEST_DONE;
1200 return;
1202 err:
1203 log_err(c, "evbuffer_add_printf error: no memory");
1204 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1205 client_close(c);
1206 return;
1208 overflow:
1209 log_warn(c, "reply header overflow");
1210 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1211 start_reply(c, TEMP_FAILURE, "internal error");
1214 static void
1215 client_close_ev(int fd, short event, void *d)
1217 struct client *c = d;
1219 switch (tls_close(c->ctx)) {
1220 case TLS_WANT_POLLIN:
1221 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1222 break;
1223 case TLS_WANT_POLLOUT:
1224 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1225 break;
1228 connected_clients--;
1230 free(c->req);
1232 tls_free(c->ctx);
1233 c->ctx = NULL;
1235 free(c->header);
1237 if (c->pfd != -1)
1238 close(c->pfd);
1240 if (c->dir != NULL)
1241 free(c->dir);
1243 close(c->fd);
1244 c->fd = -1;
1247 static void
1248 client_proxy_close(int fd, short event, void *d)
1250 struct tls *ctx = d;
1252 if (ctx == NULL) {
1253 close(fd);
1254 return;
1257 switch (tls_close(ctx)) {
1258 case TLS_WANT_POLLIN:
1259 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1260 break;
1261 case TLS_WANT_POLLOUT:
1262 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1263 break;
1266 tls_free(ctx);
1267 close(fd);
1270 void
1271 client_close(struct client *c)
1274 * We may end up calling client_close in various situations
1275 * and for the most unexpected reasons. Therefore, we need to
1276 * ensure that everything gets properly released once we reach
1277 * this point.
1280 SPLAY_REMOVE(client_tree_id, &clients, c);
1282 if (c->cgibev != NULL) {
1283 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1284 bufferevent_free(c->cgibev);
1285 c->cgibev = NULL;
1286 close(c->pfd);
1287 c->pfd = -1;
1290 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1291 bufferevent_free(c->bev);
1292 c->bev = NULL;
1294 if (c->proxyevset &&
1295 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1296 c->proxyevset = 0;
1297 event_del(&c->proxyev);
1300 if (c->pfd != -1 && c->proxyctx != NULL) {
1301 /* shut down the proxy TLS connection */
1302 client_proxy_close(c->pfd, 0, c->proxyctx);
1303 c->pfd = -1;
1306 if (c->proxybev != NULL)
1307 bufferevent_free(c->proxybev);
1309 client_close_ev(c->fd, 0, c);
1312 static void
1313 cgi_read(struct bufferevent *bev, void *d)
1315 struct client *client = d;
1316 struct evbuffer *src = EVBUFFER_INPUT(bev);
1317 char *header;
1318 size_t len;
1319 int code;
1321 /* intercept the header */
1322 if (client->code == 0) {
1323 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1324 if (header == NULL) {
1325 /* max reply + \r\n */
1326 if (EVBUFFER_LENGTH(src) > 1029) {
1327 log_warn(client, "CGI script is trying to "
1328 "send a header too long.");
1329 cgi_error(bev, EVBUFFER_READ, client);
1332 /* wait a bit */
1333 return;
1336 if (len < 3 || len > 1029 ||
1337 !isdigit(header[0]) ||
1338 !isdigit(header[1]) ||
1339 !isspace(header[2])) {
1340 free(header);
1341 log_warn(client, "CGI script is trying to send a "
1342 "malformed header");
1343 cgi_error(bev, EVBUFFER_READ, client);
1344 return;
1347 client->header = header;
1348 code = (header[0] - '0') * 10 + (header[1] - '0');
1350 if (code < 10 || code >= 70) {
1351 log_warn(client, "CGI script is trying to send an "
1352 "invalid reply code (%d)", code);
1353 cgi_error(bev, EVBUFFER_READ, client);
1354 return;
1357 start_reply(client, code, header + 3);
1359 if (client->code < 20 || client->code > 29) {
1360 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1361 return;
1365 bufferevent_write_buffer(client->bev, src);
1368 static void
1369 cgi_write(struct bufferevent *bev, void *d)
1372 * Never called. We don't send data to a CGI script.
1374 abort();
1377 static void
1378 cgi_error(struct bufferevent *bev, short error, void *d)
1380 struct client *client = d;
1382 if (error & EVBUFFER_ERROR)
1383 log_err(client, "%s: evbuffer error (%x): %s",
1384 __func__, error, strerror(errno));
1386 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1387 bufferevent_free(bev);
1388 client->cgibev = NULL;
1390 close(client->pfd);
1391 client->pfd = -1;
1393 client->type = REQUEST_DONE;
1394 if (client->code != 0)
1395 client_write(client->bev, client);
1396 else
1397 start_reply(client, CGI_ERROR, "CGI error");
1400 static void
1401 do_accept(int sock, short et, void *d)
1403 struct client *c;
1404 struct sockaddr_storage addr;
1405 struct sockaddr *saddr;
1406 socklen_t len;
1407 int fd;
1409 saddr = (struct sockaddr*)&addr;
1410 len = sizeof(addr);
1411 if ((fd = accept(sock, saddr, &len)) == -1) {
1412 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1413 errno == ECONNABORTED)
1414 return;
1415 fatal("accept: %s", strerror(errno));
1418 mark_nonblock(fd);
1420 c = xcalloc(1, sizeof(*c));
1421 c->id = ++server_client_id;
1422 c->fd = fd;
1423 c->pfd = -1;
1424 c->addr = addr;
1426 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1427 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1428 close(c->fd);
1429 free(c);
1430 return;
1433 SPLAY_INSERT(client_tree_id, &clients, c);
1434 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1435 connected_clients++;
1438 struct client *
1439 client_by_id(int id)
1441 struct client find;
1443 find.id = id;
1444 return SPLAY_FIND(client_tree_id, &clients, &find);
1447 static void
1448 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1450 struct client *c;
1452 if ((c = client_by_id(imsg->hdr.peerid)) == NULL) {
1453 if (imsg->fd != -1)
1454 close(imsg->fd);
1455 return;
1458 if ((c->pfd = imsg->fd) == -1) {
1459 start_reply(c, TEMP_FAILURE, "internal server error");
1460 return;
1463 c->type = REQUEST_CGI;
1465 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1466 cgi_error, c);
1468 bufferevent_enable(c->cgibev, EV_READ);
1471 static void
1472 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1474 struct client *c;
1475 int id;
1477 id = imsg->hdr.peerid;
1479 if ((c = client_by_id(id)) == NULL) {
1480 if (imsg->fd != -1)
1481 close(imsg->fd);
1482 return;
1485 if ((c->pfd = imsg->fd) == -1) {
1486 start_reply(c, CGI_ERROR, "CGI error");
1487 return;
1490 mark_nonblock(c->pfd);
1492 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1493 fcgi_error, c);
1494 if (c->cgibev == NULL) {
1495 start_reply(c, TEMP_FAILURE, "internal server error");
1496 return;
1499 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1500 fcgi_req(c);
1503 static void
1504 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1506 struct client *c;
1507 int id;
1509 id = imsg->hdr.peerid;
1510 if ((c = client_by_id(id)) == NULL) {
1511 if (imsg->fd != -1)
1512 close(imsg->fd);
1513 return;
1516 if ((c->pfd = imsg->fd) == -1) {
1517 start_reply(c, PROXY_ERROR, "proxy error");
1518 return;
1521 mark_nonblock(c->pfd);
1523 if (proxy_init(c) == -1)
1524 start_reply(c, PROXY_ERROR, "proxy error");
1527 static void
1528 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1531 * don't call event_loopbreak since we want to finish to
1532 * handle the ongoing connections.
1535 shutting_down = 1;
1537 event_del(&e4);
1538 if (has_ipv6)
1539 event_del(&e6);
1540 if (has_siginfo)
1541 signal_del(&siginfo);
1542 event_del(&imsgev);
1543 signal_del(&sigusr2);
1546 static void
1547 handle_dispatch_imsg(int fd, short ev, void *d)
1549 struct imsgbuf *ibuf = d;
1550 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1553 static void
1554 handle_siginfo(int fd, short ev, void *d)
1556 log_info(NULL, "%d connected clients", connected_clients);
1559 void
1560 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1562 ctx = ctx_;
1564 SPLAY_INIT(&clients);
1566 event_init();
1568 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1569 event_add(&e4, NULL);
1571 if (sock6 != -1) {
1572 has_ipv6 = 1;
1573 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1574 event_add(&e6, NULL);
1577 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1578 event_add(&imsgev, NULL);
1580 #ifdef SIGINFO
1581 has_siginfo = 1;
1582 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1583 signal_add(&siginfo, NULL);
1584 #endif
1585 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1586 signal_add(&sigusr2, NULL);
1588 sandbox_server_process();
1589 event_dispatch();
1590 _exit(0);
1593 int
1594 client_tree_cmp(struct client *a, struct client *b)
1596 if (a->id == b->id)
1597 return 0;
1598 else if (a->id < b->id)
1599 return -1;
1600 else
1601 return +1;
1604 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)