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 apply_reverse_proxy(struct client *);
51 static int apply_fastcgi(struct client*);
52 static int apply_require_ca(struct client*);
53 static size_t host_nth(struct vhost*);
54 static void start_cgi(const char*, const char*, struct client*);
55 static void open_dir(struct client*);
56 static void redirect_canonical_dir(struct client*);
58 static void client_tls_readcb(int, short, void *);
59 static void client_tls_writecb(int, short, void *);
61 static void client_read(struct bufferevent *, void *);
62 void client_write(struct bufferevent *, void *);
63 static void client_error(struct bufferevent *, short, void *);
65 static void client_close_ev(int, short, void *);
67 static void cgi_read(struct bufferevent *, void *);
68 static void cgi_write(struct bufferevent *, void *);
69 static void cgi_error(struct bufferevent *, short, void *);
71 static void do_accept(int, short, void*);
72 static struct client *client_by_id(int);
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 return FILE_MISSING;
341 if (fstat(*fd, &sb) == -1) {
342 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
343 return FILE_MISSING;
346 if (S_ISDIR(sb.st_mode))
347 return FILE_DIRECTORY;
349 if (sb.st_mode & S_IXUSR)
350 return FILE_EXECUTABLE;
352 return FILE_EXISTS;
355 static void
356 open_file(struct client *c)
358 switch (check_path(c, c->iri.path, &c->pfd)) {
359 case FILE_EXECUTABLE:
360 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
361 start_cgi(c->iri.path, "", c);
362 return;
365 /* fallthrough */
367 case FILE_EXISTS:
368 c->type = REQUEST_FILE;
369 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
370 return;
372 case FILE_DIRECTORY:
373 open_dir(c);
374 return;
376 case FILE_MISSING:
377 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
378 check_for_cgi(c);
379 return;
381 start_reply(c, NOT_FOUND, "not found");
382 return;
384 default:
385 /* unreachable */
386 abort();
390 /*
391 * the inverse of this algorithm, i.e. starting from the start of the
392 * path + strlen(cgi), and checking if each component, should be
393 * faster. But it's tedious to write. This does the opposite: starts
394 * from the end and strip one component at a time, until either an
395 * executable is found or we emptied the path.
396 */
397 static void
398 check_for_cgi(struct client *c)
400 char path[PATH_MAX];
401 char *end;
403 strlcpy(path, c->iri.path, sizeof(path));
404 end = strchr(path, '\0');
406 while (end > path) {
407 /*
408 * go up one level. UNIX paths are simple and POSIX
409 * dirname, with its ambiguities on if the given
410 * pointer is changed or not, gives me headaches.
411 */
412 while (*end != '/' && end > path)
413 end--;
415 if (end == path)
416 break;
418 *end = '\0';
420 switch (check_path(c, path, &c->pfd)) {
421 case FILE_EXECUTABLE:
422 start_cgi(path, end+1, c);
423 return;
424 case FILE_MISSING:
425 break;
426 default:
427 goto err;
430 *end = '/';
431 end--;
434 err:
435 start_reply(c, NOT_FOUND, "not found");
436 return;
439 void
440 mark_nonblock(int fd)
442 int flags;
444 if ((flags = fcntl(fd, F_GETFL)) == -1)
445 fatal("fcntl(F_GETFL): %s", strerror(errno));
446 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
447 fatal("fcntl(F_SETFL): %s", strerror(errno));
450 static void
451 handle_handshake(int fd, short ev, void *d)
453 struct client *c = d;
454 struct vhost *h;
455 struct alist *a;
456 const char *servname;
457 const char *parse_err = "unknown error";
459 switch (tls_handshake(c->ctx)) {
460 case 0: /* success */
461 case -1: /* already handshaked */
462 break;
463 case TLS_WANT_POLLIN:
464 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
465 return;
466 case TLS_WANT_POLLOUT:
467 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
468 return;
469 default:
470 /* unreachable */
471 abort();
474 c->bev = bufferevent_new(fd, client_read, client_write,
475 client_error, c);
476 if (c->bev == NULL)
477 fatal("%s: failed to allocate client buffer: %s",
478 __func__, strerror(errno));
480 event_set(&c->bev->ev_read, c->fd, EV_READ,
481 client_tls_readcb, c->bev);
482 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
483 client_tls_writecb, c->bev);
485 #if HAVE_LIBEVENT2
486 evbuffer_unfreeze(c->bev->input, 0);
487 evbuffer_unfreeze(c->bev->output, 1);
488 #endif
490 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
491 log_debug(c, "handshake: missing SNI");
492 goto err;
495 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
496 log_info(c, "puny_decode: %s", parse_err);
497 goto err;
500 TAILQ_FOREACH(h, &hosts, vhosts) {
501 if (matches(h->domain, c->domain))
502 goto found;
503 TAILQ_FOREACH(a, &h->aliases, aliases) {
504 if (matches(a->alias, c->domain))
505 goto found;
509 found:
510 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
511 servname != NULL ? servname : "(null)",
512 c->domain,
513 h != NULL ? h->domain : "(null)");
515 if (h != NULL) {
516 c->host = h;
517 bufferevent_enable(c->bev, EV_READ);
518 return;
521 err:
522 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
525 static const char *
526 strip_path(const char *path, int strip)
528 char *t;
530 while (strip > 0) {
531 if ((t = strchr(path, '/')) == NULL) {
532 path = strchr(path, '\0');
533 break;
535 path = t;
536 strip--;
539 return path;
542 static void
543 fmt_sbuf(const char *fmt, struct client *c, const char *path)
545 size_t i;
546 char buf[32];
548 memset(buf, 0, sizeof(buf));
549 for (i = 0; *fmt; ++fmt) {
550 if (i == sizeof(buf)-1 || *fmt == '%') {
551 strlcat(c->sbuf, buf, sizeof(c->sbuf));
552 memset(buf, 0, sizeof(buf));
553 i = 0;
556 if (*fmt != '%') {
557 buf[i++] = *fmt;
558 continue;
561 switch (*++fmt) {
562 case '%':
563 strlcat(c->sbuf, "%", sizeof(c->sbuf));
564 break;
565 case 'p':
566 if (*path != '/')
567 strlcat(c->sbuf, "/", sizeof(c->sbuf));
568 strlcat(c->sbuf, path, sizeof(c->sbuf));
569 break;
570 case 'q':
571 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
572 break;
573 case 'P':
574 snprintf(buf, sizeof(buf), "%d", conf.port);
575 strlcat(c->sbuf, buf, sizeof(c->sbuf));
576 memset(buf, 0, sizeof(buf));
577 break;
578 case 'N':
579 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
580 break;
581 default:
582 fatal("%s: unknown fmt specifier %c",
583 __func__, *fmt);
587 if (i != 0)
588 strlcat(c->sbuf, buf, sizeof(c->sbuf));
591 /* 1 if a matching `block return' (and apply it), 0 otherwise */
592 static int
593 apply_block_return(struct client *c)
595 const char *fmt, *path;
596 int code;
598 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
599 return 0;
601 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
602 fmt_sbuf(fmt, c, path);
604 start_reply(c, code, c->sbuf);
605 return 1;
608 static struct proxy *
609 matched_proxy(struct client *c)
611 struct proxy *p;
612 const char *proto;
613 const char *host;
614 const char *port;
616 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
617 if ((proto = p->match_proto) == NULL)
618 proto = "gemini";
619 if ((host = p->match_host) == NULL)
620 host = "*";
621 if ((port = p->match_port) == NULL)
622 port = "*";
624 if (matches(proto, c->iri.schema) &&
625 matches(host, c->domain) &&
626 matches(port, c->iri.port))
627 return p;
630 return NULL;
633 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
634 static int
635 apply_reverse_proxy(struct client *c)
637 struct proxy *p;
638 struct connreq r;
640 if ((p = matched_proxy(c)) == NULL)
641 return 0;
643 c->proxy = p;
645 log_debug(c, "opening proxy connection for %s:%s",
646 p->host, p->port);
648 strlcpy(r.host, p->host, sizeof(r.host));
649 strlcpy(r.port, p->port, sizeof(r.port));
651 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
652 imsg_flush(&exibuf);
654 return 1;
657 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
658 static int
659 apply_fastcgi(struct client *c)
661 int id;
662 struct fcgi *f;
664 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
665 return 0;
667 f = &fcgi[id];
669 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
670 f->path, f->port, f->prog);
672 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
673 &id, sizeof(id));
674 imsg_flush(&exibuf);
675 return 1;
678 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
679 static int
680 apply_require_ca(struct client *c)
682 X509_STORE *store;
683 const uint8_t *cert;
684 size_t len;
686 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
687 return 0;
689 if (!tls_peer_cert_provided(c->ctx)) {
690 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
691 return 1;
694 cert = tls_peer_cert_chain_pem(c->ctx, &len);
695 if (!validate_against_ca(store, cert, len)) {
696 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
697 return 1;
700 return 0;
703 static size_t
704 host_nth(struct vhost *h)
706 struct vhost *v;
707 size_t i = 0;
709 TAILQ_FOREACH(v, &hosts, vhosts) {
710 if (v == h)
711 return i;
712 i++;
715 abort();
718 static void
719 start_cgi(const char *spath, const char *relpath, struct client *c)
721 char addr[NI_MAXHOST];
722 const char *t;
723 struct cgireq req;
724 int e;
726 c->type = REQUEST_CGI;
728 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
729 addr, sizeof(addr),
730 NULL, 0,
731 NI_NUMERICHOST);
732 if (e != 0)
733 fatal("getnameinfo failed");
735 memset(&req, 0, sizeof(req));
737 memcpy(req.buf, c->req, sizeof(req.buf));
739 req.iri_schema_off = c->iri.schema - c->req;
740 req.iri_host_off = c->iri.host - c->req;
741 req.iri_port_off = c->iri.port - c->req;
742 req.iri_path_off = c->iri.path - c->req;
743 req.iri_query_off = c->iri.query - c->req;
744 req.iri_fragment_off = c->iri.fragment - c->req;
746 req.iri_portno = c->iri.port_no;
748 strlcpy(req.spath, spath, sizeof(req.spath));
749 strlcpy(req.relpath, relpath, sizeof(req.relpath));
750 strlcpy(req.addr, addr, sizeof(req.addr));
752 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
753 strlcpy(req.subject, t, sizeof(req.subject));
754 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
755 strlcpy(req.issuer, t, sizeof(req.issuer));
756 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
757 strlcpy(req.hash, t, sizeof(req.hash));
758 if ((t = tls_conn_version(c->ctx)) != NULL)
759 strlcpy(req.version, t, sizeof(req.version));
760 if ((t = tls_conn_cipher(c->ctx)) != NULL)
761 strlcpy(req.cipher, t, sizeof(req.cipher));
763 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
764 req.notbefore = tls_peer_cert_notbefore(c->ctx);
765 req.notafter = tls_peer_cert_notafter(c->ctx);
767 req.host_off = host_nth(c->host);
768 req.loc_off = c->loc;
770 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
771 imsg_flush(&exibuf);
773 close(c->pfd);
776 static void
777 open_dir(struct client *c)
779 size_t len;
780 int dirfd, root;
781 char *before_file;
783 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
785 len = strlen(c->iri.path);
786 if (len > 0 && !ends_with(c->iri.path, "/")) {
787 redirect_canonical_dir(c);
788 return;
791 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
792 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
793 if (!ends_with(c->sbuf, "/"))
794 strlcat(c->sbuf, "/", sizeof(c->sbuf));
795 before_file = strchr(c->sbuf, '\0');
796 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
797 sizeof(c->sbuf));
798 if (len >= sizeof(c->sbuf)) {
799 start_reply(c, TEMP_FAILURE, "internal server error");
800 return;
803 c->iri.path = c->sbuf;
805 /* close later unless we have to generate the dir listing */
806 dirfd = c->pfd;
807 c->pfd = -1;
809 switch (check_path(c, c->iri.path, &c->pfd)) {
810 case FILE_EXECUTABLE:
811 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
812 start_cgi(c->iri.path, "", c);
813 break;
816 /* fallthrough */
818 case FILE_EXISTS:
819 c->type = REQUEST_FILE;
820 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
821 break;
823 case FILE_DIRECTORY:
824 start_reply(c, TEMP_REDIRECT, c->sbuf);
825 break;
827 case FILE_MISSING:
828 *before_file = '\0';
830 if (!vhost_auto_index(c->host, c->iri.path)) {
831 start_reply(c, NOT_FOUND, "not found");
832 break;
835 c->type = REQUEST_DIR;
837 c->dirlen = scandir_fd(dirfd, &c->dir,
838 root ? select_non_dotdot : select_non_dot,
839 alphasort);
840 if (c->dirlen == -1) {
841 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
842 c->pfd, c->host->domain, c->iri.path, strerror(errno));
843 start_reply(c, TEMP_FAILURE, "internal server error");
844 return;
846 c->diroff = 0;
847 c->off = 0;
849 start_reply(c, SUCCESS, "text/gemini");
850 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
851 "# Index of %s\n\n", c->iri.path);
852 return;
854 default:
855 /* unreachable */
856 abort();
859 close(dirfd);
862 static void
863 redirect_canonical_dir(struct client *c)
865 size_t len;
867 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
868 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
869 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
871 if (len >= sizeof(c->sbuf)) {
872 start_reply(c, TEMP_FAILURE, "internal server error");
873 return;
876 start_reply(c, TEMP_REDIRECT, c->sbuf);
879 static void
880 client_tls_readcb(int fd, short event, void *d)
882 struct bufferevent *bufev = d;
883 struct client *client = bufev->cbarg;
884 ssize_t ret;
885 size_t len;
886 int what = EVBUFFER_READ;
887 int howmuch = IBUF_READ_SIZE;
888 char buf[IBUF_READ_SIZE];
890 if (event == EV_TIMEOUT) {
891 what |= EVBUFFER_TIMEOUT;
892 goto err;
895 if (bufev->wm_read.high != 0)
896 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
898 switch (ret = tls_read(client->ctx, buf, howmuch)) {
899 case TLS_WANT_POLLIN:
900 case TLS_WANT_POLLOUT:
901 goto retry;
902 case -1:
903 what |= EVBUFFER_ERROR;
904 goto err;
906 len = ret;
908 if (len == 0) {
909 what |= EVBUFFER_EOF;
910 goto err;
913 if (evbuffer_add(bufev->input, buf, len) == -1) {
914 what |= EVBUFFER_ERROR;
915 goto err;
918 event_add(&bufev->ev_read, NULL);
919 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
920 return;
921 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
922 /*
923 * here we could implement a read pressure policy.
924 */
927 if (bufev->readcb != NULL)
928 (*bufev->readcb)(bufev, bufev->cbarg);
930 return;
932 retry:
933 event_add(&bufev->ev_read, NULL);
934 return;
936 err:
937 (*bufev->errorcb)(bufev, what, bufev->cbarg);
940 static void
941 client_tls_writecb(int fd, short event, void *d)
943 struct bufferevent *bufev = d;
944 struct client *client = bufev->cbarg;
945 ssize_t ret;
946 size_t len;
947 short what = EVBUFFER_WRITE;
949 if (event == EV_TIMEOUT) {
950 what |= EVBUFFER_TIMEOUT;
951 goto err;
954 if (EVBUFFER_LENGTH(bufev->output) != 0) {
955 ret = tls_write(client->ctx,
956 EVBUFFER_DATA(bufev->output),
957 EVBUFFER_LENGTH(bufev->output));
958 switch (ret) {
959 case TLS_WANT_POLLIN:
960 case TLS_WANT_POLLOUT:
961 goto retry;
962 case -1:
963 what |= EVBUFFER_ERROR;
964 goto err;
966 len = ret;
967 evbuffer_drain(bufev->output, len);
970 if (EVBUFFER_LENGTH(bufev->output) != 0)
971 event_add(&bufev->ev_write, NULL);
973 if (bufev->writecb != NULL &&
974 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
975 (*bufev->writecb)(bufev, bufev->cbarg);
976 return;
978 retry:
979 event_add(&bufev->ev_write, NULL);
980 return;
981 err:
982 log_err(client, "tls error: %s", tls_error(client->ctx));
983 (*bufev->errorcb)(bufev, what, bufev->cbarg);
986 static void
987 client_read(struct bufferevent *bev, void *d)
989 struct client *c = d;
990 struct evbuffer *src = EVBUFFER_INPUT(bev);
991 const char *parse_err = "invalid request";
992 char decoded[DOMAIN_NAME_LEN];
993 size_t len;
995 bufferevent_disable(bev, EVBUFFER_READ);
997 /* max url len + \r\n */
998 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
999 log_err(c, "too much data received");
1000 start_reply(c, BAD_REQUEST, "bad request");
1001 return;
1004 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1005 if (c->req == NULL) {
1006 /* not enough data yet. */
1007 bufferevent_enable(bev, EVBUFFER_READ);
1008 return;
1011 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1012 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1013 log_err(c, "IRI parse error: %s", parse_err);
1014 start_reply(c, BAD_REQUEST, "bad request");
1015 return;
1018 if (apply_reverse_proxy(c))
1019 return;
1021 /* ignore the port number */
1022 if (strcmp(c->iri.schema, "gemini") ||
1023 strcmp(decoded, c->domain)) {
1024 start_reply(c, PROXY_REFUSED, "won't proxy request");
1025 return;
1028 if (apply_require_ca(c) ||
1029 apply_block_return(c)||
1030 apply_fastcgi(c))
1031 return;
1033 if (c->host->entrypoint != NULL) {
1034 c->loc = 0;
1035 start_cgi(c->host->entrypoint, c->iri.path, c);
1036 return;
1039 open_file(c);
1042 void
1043 client_write(struct bufferevent *bev, void *d)
1045 struct client *c = d;
1046 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1047 char buf[BUFSIZ];
1048 ssize_t r;
1050 switch (c->type) {
1051 case REQUEST_UNDECIDED:
1053 * Ignore spurious calls when we still don't have idea
1054 * what to do with the request.
1056 break;
1058 case REQUEST_FILE:
1059 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1060 log_warn(c, "read: %s", strerror(errno));
1061 client_error(bev, EVBUFFER_ERROR, c);
1062 return;
1063 } else if (r == 0) {
1064 client_close(c);
1065 return;
1066 } else if (r != sizeof(buf))
1067 c->type = REQUEST_DONE;
1068 bufferevent_write(bev, buf, r);
1069 break;
1071 case REQUEST_DIR:
1072 /* TODO: handle big big directories better */
1073 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1074 evbuffer_add_printf(out, "=> %s\n",
1075 c->dir[c->diroff]->d_name);
1076 free(c->dir[c->diroff]);
1078 free(c->dir);
1079 c->dir = NULL;
1081 c->type = REQUEST_DONE;
1083 event_add(&c->bev->ev_write, NULL);
1084 break;
1086 case REQUEST_CGI:
1087 case REQUEST_FCGI:
1088 case REQUEST_PROXY:
1090 * Here we depend on on the cgi script or fastcgi
1091 * connection to provide data.
1093 break;
1095 case REQUEST_DONE:
1096 if (EVBUFFER_LENGTH(out) == 0)
1097 client_close(c);
1098 break;
1102 static void
1103 client_error(struct bufferevent *bev, short error, void *d)
1105 struct client *c = d;
1107 c->type = REQUEST_DONE;
1109 if (error & EVBUFFER_TIMEOUT) {
1110 log_warn(c, "timeout reached, "
1111 "forcefully closing the connection");
1112 if (c->code == 0)
1113 start_reply(c, BAD_REQUEST, "timeout");
1114 else
1115 client_close(c);
1116 return;
1119 if (error & EVBUFFER_EOF) {
1120 client_close(c);
1121 return;
1124 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1125 client_close(c);
1128 void
1129 start_reply(struct client *c, int code, const char *meta)
1131 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1132 const char *lang;
1133 int r, rr;
1135 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1137 c->code = code;
1138 c->meta = meta;
1140 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1141 if (r == -1)
1142 goto err;
1144 /* 2 digit status + space + 1024 max reply */
1145 if (r > 1027)
1146 goto overflow;
1148 if (c->type != REQUEST_CGI &&
1149 c->type != REQUEST_FCGI &&
1150 c->type != REQUEST_PROXY &&
1151 !strcmp(meta, "text/gemini") &&
1152 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1153 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1154 if (rr == -1)
1155 goto err;
1156 if (r + rr > 1027)
1157 goto overflow;
1160 bufferevent_write(c->bev, "\r\n", 2);
1162 if (!vhost_disable_log(c->host, c->iri.path))
1163 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1165 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1166 c->type = REQUEST_DONE;
1168 return;
1170 err:
1171 log_err(c, "evbuffer_add_printf error: no memory");
1172 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1173 client_close(c);
1174 return;
1176 overflow:
1177 log_warn(c, "reply header overflow");
1178 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1179 start_reply(c, TEMP_FAILURE, "internal error");
1182 static void
1183 client_close_ev(int fd, short event, void *d)
1185 struct client *c = d;
1187 switch (tls_close(c->ctx)) {
1188 case TLS_WANT_POLLIN:
1189 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1190 break;
1191 case TLS_WANT_POLLOUT:
1192 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1193 break;
1196 connected_clients--;
1198 free(c->req);
1200 tls_free(c->ctx);
1201 c->ctx = NULL;
1203 free(c->header);
1205 if (c->pfd != -1)
1206 close(c->pfd);
1208 if (c->dir != NULL)
1209 free(c->dir);
1211 close(c->fd);
1212 c->fd = -1;
1215 static void
1216 client_proxy_close(int fd, short event, void *d)
1218 struct tls *ctx = d;
1220 if (ctx == NULL) {
1221 close(fd);
1222 return;
1225 switch (tls_close(ctx)) {
1226 case TLS_WANT_POLLIN:
1227 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1228 break;
1229 case TLS_WANT_POLLOUT:
1230 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1231 break;
1234 tls_free(ctx);
1235 close(fd);
1238 void
1239 client_close(struct client *c)
1242 * We may end up calling client_close in various situations
1243 * and for the most unexpected reasons. Therefore, we need to
1244 * ensure that everything is properly released once we reach
1245 * this point.
1248 SPLAY_REMOVE(client_tree_id, &clients, c);
1250 if (c->cgibev != NULL) {
1251 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1252 bufferevent_free(c->cgibev);
1253 c->cgibev = NULL;
1254 close(c->pfd);
1255 c->pfd = -1;
1258 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1259 bufferevent_free(c->bev);
1260 c->bev = NULL;
1262 if (c->proxybev != NULL) {
1263 if (event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL))
1264 event_del(&c->proxyev);
1266 if (c->pfd != -1 && c->proxyctx != NULL) {
1267 /* shut down the proxy TLS connection */
1268 client_proxy_close(c->pfd, 0, c->proxyctx);
1269 c->pfd = -1;
1272 bufferevent_free(c->proxybev);
1275 client_close_ev(c->fd, 0, c);
1278 static void
1279 cgi_read(struct bufferevent *bev, void *d)
1281 struct client *client = d;
1282 struct evbuffer *src = EVBUFFER_INPUT(bev);
1283 char *header;
1284 size_t len;
1285 int code;
1287 /* intercept the header */
1288 if (client->code == 0) {
1289 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1290 if (header == NULL) {
1291 /* max reply + \r\n */
1292 if (EVBUFFER_LENGTH(src) > 1029) {
1293 log_warn(client, "CGI script is trying to "
1294 "send a header too long.");
1295 cgi_error(bev, EVBUFFER_READ, client);
1298 /* wait a bit */
1299 return;
1302 if (len < 3 || len > 1029 ||
1303 !isdigit(header[0]) ||
1304 !isdigit(header[1]) ||
1305 !isspace(header[2])) {
1306 free(header);
1307 log_warn(client, "CGI script is trying to send a "
1308 "malformed header");
1309 cgi_error(bev, EVBUFFER_READ, client);
1310 return;
1313 client->header = header;
1314 code = (header[0] - '0') * 10 + (header[1] - '0');
1316 if (code < 10 || code >= 70) {
1317 log_warn(client, "CGI script is trying to send an "
1318 "invalid reply code (%d)", code);
1319 cgi_error(bev, EVBUFFER_READ, client);
1320 return;
1323 start_reply(client, code, header + 3);
1325 if (client->code < 20 || client->code > 29) {
1326 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1327 return;
1331 bufferevent_write_buffer(client->bev, src);
1334 static void
1335 cgi_write(struct bufferevent *bev, void *d)
1338 * Never called. We don't send data to a CGI script.
1340 abort();
1343 static void
1344 cgi_error(struct bufferevent *bev, short error, void *d)
1346 struct client *client = d;
1348 if (error & EVBUFFER_ERROR)
1349 log_err(client, "%s: evbuffer error (%x): %s",
1350 __func__, error, strerror(errno));
1352 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1353 bufferevent_free(bev);
1354 client->cgibev = NULL;
1356 close(client->pfd);
1357 client->pfd = -1;
1359 client->type = REQUEST_DONE;
1360 if (client->code != 0)
1361 client_write(client->bev, client);
1362 else
1363 start_reply(client, CGI_ERROR, "CGI error");
1366 static void
1367 do_accept(int sock, short et, void *d)
1369 struct client *c;
1370 struct sockaddr_storage addr;
1371 struct sockaddr *saddr;
1372 socklen_t len;
1373 int fd;
1375 saddr = (struct sockaddr*)&addr;
1376 len = sizeof(addr);
1377 if ((fd = accept(sock, saddr, &len)) == -1) {
1378 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1379 errno == ECONNABORTED)
1380 return;
1381 fatal("accept: %s", strerror(errno));
1384 mark_nonblock(fd);
1386 c = xcalloc(1, sizeof(*c));
1387 c->id = ++server_client_id;
1388 c->fd = fd;
1389 c->pfd = -1;
1390 c->addr = addr;
1392 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1393 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1394 close(c->fd);
1395 free(c);
1396 return;
1399 SPLAY_INSERT(client_tree_id, &clients, c);
1400 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1401 connected_clients++;
1404 static struct client *
1405 client_by_id(int id)
1407 struct client *c;
1409 if ((c = try_client_by_id(id)) == NULL)
1410 fatal("in client_by_id: invalid id %d", id);
1411 return c;
1414 struct client *
1415 try_client_by_id(int id)
1417 struct client find;
1419 find.id = id;
1420 return SPLAY_FIND(client_tree_id, &clients, &find);
1423 static void
1424 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1426 struct client *c;
1428 c = client_by_id(imsg->hdr.peerid);
1430 if ((c->pfd = imsg->fd) == -1) {
1431 start_reply(c, TEMP_FAILURE, "internal server error");
1432 return;
1435 c->type = REQUEST_CGI;
1437 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1438 cgi_error, c);
1440 bufferevent_enable(c->cgibev, EV_READ);
1443 static void
1444 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1446 struct client *c;
1447 int id;
1449 id = imsg->hdr.peerid;
1451 if ((c = try_client_by_id(id)) == NULL) {
1452 if (imsg->fd != -1)
1453 close(imsg->fd);
1454 return;
1457 if ((c->pfd = imsg->fd) == -1) {
1458 start_reply(c, CGI_ERROR, "CGI error");
1459 return;
1462 mark_nonblock(c->pfd);
1464 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1465 fcgi_error, c);
1466 if (c->cgibev == NULL) {
1467 start_reply(c, TEMP_FAILURE, "internal server error");
1468 return;
1471 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1472 fcgi_req(c);
1475 static void
1476 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1478 struct client *c;
1479 int id;
1481 id = imsg->hdr.peerid;
1482 if ((c = try_client_by_id(id)) == NULL) {
1483 if (imsg->fd != -1)
1484 close(imsg->fd);
1485 return;
1488 if ((c->pfd = imsg->fd) == -1) {
1489 start_reply(c, PROXY_ERROR, "proxy error");
1490 return;
1493 mark_nonblock(c->pfd);
1495 if (proxy_init(c) == -1)
1496 start_reply(c, PROXY_ERROR, "proxy error");
1499 static void
1500 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1503 * don't call event_loopbreak since we want to finish to
1504 * handle the ongoing connections.
1507 shutting_down = 1;
1509 event_del(&e4);
1510 if (has_ipv6)
1511 event_del(&e6);
1512 if (has_siginfo)
1513 signal_del(&siginfo);
1514 event_del(&imsgev);
1515 signal_del(&sigusr2);
1518 static void
1519 handle_dispatch_imsg(int fd, short ev, void *d)
1521 struct imsgbuf *ibuf = d;
1522 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1525 static void
1526 handle_siginfo(int fd, short ev, void *d)
1528 log_info(NULL, "%d connected clients", connected_clients);
1531 void
1532 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1534 ctx = ctx_;
1536 SPLAY_INIT(&clients);
1538 event_init();
1540 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1541 event_add(&e4, NULL);
1543 if (sock6 != -1) {
1544 has_ipv6 = 1;
1545 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1546 event_add(&e6, NULL);
1549 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1550 event_add(&imsgev, NULL);
1552 #ifdef SIGINFO
1553 has_siginfo = 1;
1554 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1555 signal_add(&siginfo, NULL);
1556 #endif
1557 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1558 signal_add(&sigusr2, NULL);
1560 sandbox_server_process();
1561 event_dispatch();
1562 _exit(0);
1565 int
1566 client_tree_cmp(struct client *a, struct client *b)
1568 if (a->id == b->id)
1569 return 0;
1570 else if (a->id < b->id)
1571 return -1;
1572 else
1573 return +1;
1576 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)