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*);
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 static int
634 check_matching_certificate(X509_STORE *store, struct client *c)
636 const uint8_t *cert;
637 size_t len;
639 if (!tls_peer_cert_provided(c->ctx)) {
640 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
641 return 1;
644 cert = tls_peer_cert_chain_pem(c->ctx, &len);
645 if (!validate_against_ca(store, cert, len)) {
646 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
647 return 1;
650 return 0;
653 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
654 static int
655 apply_reverse_proxy(struct client *c)
657 struct proxy *p;
658 struct connreq r;
660 if ((p = matched_proxy(c)) == NULL)
661 return 0;
663 c->proxy = p;
665 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
666 return 1;
668 log_debug(c, "opening proxy connection for %s:%s",
669 p->host, p->port);
671 strlcpy(r.host, p->host, sizeof(r.host));
672 strlcpy(r.port, p->port, sizeof(r.port));
674 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
675 imsg_flush(&exibuf);
677 return 1;
680 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
681 static int
682 apply_fastcgi(struct client *c)
684 int id;
685 struct fcgi *f;
687 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
688 return 0;
690 f = &fcgi[id];
692 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
693 f->path, f->port, f->prog);
695 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
696 &id, sizeof(id));
697 imsg_flush(&exibuf);
698 return 1;
701 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
702 static int
703 apply_require_ca(struct client *c)
705 X509_STORE *store;
707 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
708 return 0;
709 return check_matching_certificate(store, c);
712 static size_t
713 host_nth(struct vhost *h)
715 struct vhost *v;
716 size_t i = 0;
718 TAILQ_FOREACH(v, &hosts, vhosts) {
719 if (v == h)
720 return i;
721 i++;
724 abort();
727 static void
728 start_cgi(const char *spath, const char *relpath, struct client *c)
730 char addr[NI_MAXHOST];
731 const char *t;
732 struct cgireq req;
733 int e;
735 c->type = REQUEST_CGI;
737 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
738 addr, sizeof(addr),
739 NULL, 0,
740 NI_NUMERICHOST);
741 if (e != 0)
742 fatal("getnameinfo failed");
744 memset(&req, 0, sizeof(req));
746 memcpy(req.buf, c->req, c->reqlen);
748 req.iri_schema_off = c->iri.schema - c->req;
749 req.iri_host_off = c->iri.host - c->req;
750 req.iri_port_off = c->iri.port - c->req;
751 req.iri_path_off = c->iri.path - c->req;
752 req.iri_query_off = c->iri.query - c->req;
753 req.iri_fragment_off = c->iri.fragment - c->req;
755 req.iri_portno = c->iri.port_no;
757 strlcpy(req.spath, spath, sizeof(req.spath));
758 strlcpy(req.relpath, relpath, sizeof(req.relpath));
759 strlcpy(req.addr, addr, sizeof(req.addr));
761 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
762 strlcpy(req.subject, t, sizeof(req.subject));
763 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
764 strlcpy(req.issuer, t, sizeof(req.issuer));
765 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
766 strlcpy(req.hash, t, sizeof(req.hash));
767 if ((t = tls_conn_version(c->ctx)) != NULL)
768 strlcpy(req.version, t, sizeof(req.version));
769 if ((t = tls_conn_cipher(c->ctx)) != NULL)
770 strlcpy(req.cipher, t, sizeof(req.cipher));
772 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
773 req.notbefore = tls_peer_cert_notbefore(c->ctx);
774 req.notafter = tls_peer_cert_notafter(c->ctx);
776 req.host_off = host_nth(c->host);
777 req.loc_off = c->loc;
779 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
780 imsg_flush(&exibuf);
782 close(c->pfd);
785 static void
786 open_dir(struct client *c)
788 size_t len;
789 int dirfd, root;
790 char *before_file;
792 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
794 len = strlen(c->iri.path);
795 if (len > 0 && !ends_with(c->iri.path, "/")) {
796 redirect_canonical_dir(c);
797 return;
800 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
801 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
802 if (!ends_with(c->sbuf, "/"))
803 strlcat(c->sbuf, "/", sizeof(c->sbuf));
804 before_file = strchr(c->sbuf, '\0');
805 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
806 sizeof(c->sbuf));
807 if (len >= sizeof(c->sbuf)) {
808 start_reply(c, TEMP_FAILURE, "internal server error");
809 return;
812 c->iri.path = c->sbuf;
814 /* close later unless we have to generate the dir listing */
815 dirfd = c->pfd;
816 c->pfd = -1;
818 switch (check_path(c, c->iri.path, &c->pfd)) {
819 case FILE_EXECUTABLE:
820 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
821 start_cgi(c->iri.path, "", c);
822 break;
825 /* fallthrough */
827 case FILE_EXISTS:
828 c->type = REQUEST_FILE;
829 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
830 break;
832 case FILE_DIRECTORY:
833 start_reply(c, TEMP_REDIRECT, c->sbuf);
834 break;
836 case FILE_MISSING:
837 *before_file = '\0';
839 if (!vhost_auto_index(c->host, c->iri.path)) {
840 start_reply(c, NOT_FOUND, "not found");
841 break;
844 c->type = REQUEST_DIR;
846 c->dirlen = scandir_fd(dirfd, &c->dir,
847 root ? select_non_dotdot : select_non_dot,
848 alphasort);
849 if (c->dirlen == -1) {
850 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
851 c->pfd, c->host->domain, c->iri.path, strerror(errno));
852 start_reply(c, TEMP_FAILURE, "internal server error");
853 return;
855 c->diroff = 0;
856 c->off = 0;
858 start_reply(c, SUCCESS, "text/gemini");
859 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
860 "# Index of %s\n\n", c->iri.path);
861 return;
863 default:
864 /* unreachable */
865 abort();
868 close(dirfd);
871 static void
872 redirect_canonical_dir(struct client *c)
874 size_t len;
876 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
877 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
878 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
880 if (len >= sizeof(c->sbuf)) {
881 start_reply(c, TEMP_FAILURE, "internal server error");
882 return;
885 start_reply(c, TEMP_REDIRECT, c->sbuf);
888 static void
889 client_tls_readcb(int fd, short event, void *d)
891 struct bufferevent *bufev = d;
892 struct client *client = bufev->cbarg;
893 ssize_t ret;
894 size_t len;
895 int what = EVBUFFER_READ;
896 int howmuch = IBUF_READ_SIZE;
897 char buf[IBUF_READ_SIZE];
899 if (event == EV_TIMEOUT) {
900 what |= EVBUFFER_TIMEOUT;
901 goto err;
904 if (bufev->wm_read.high != 0)
905 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
907 switch (ret = tls_read(client->ctx, buf, howmuch)) {
908 case TLS_WANT_POLLIN:
909 case TLS_WANT_POLLOUT:
910 goto retry;
911 case -1:
912 what |= EVBUFFER_ERROR;
913 goto err;
915 len = ret;
917 if (len == 0) {
918 what |= EVBUFFER_EOF;
919 goto err;
922 if (evbuffer_add(bufev->input, buf, len) == -1) {
923 what |= EVBUFFER_ERROR;
924 goto err;
927 event_add(&bufev->ev_read, NULL);
928 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
929 return;
930 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
931 /*
932 * here we could implement a read pressure policy.
933 */
936 if (bufev->readcb != NULL)
937 (*bufev->readcb)(bufev, bufev->cbarg);
939 return;
941 retry:
942 event_add(&bufev->ev_read, NULL);
943 return;
945 err:
946 (*bufev->errorcb)(bufev, what, bufev->cbarg);
949 static void
950 client_tls_writecb(int fd, short event, void *d)
952 struct bufferevent *bufev = d;
953 struct client *client = bufev->cbarg;
954 ssize_t ret;
955 size_t len;
956 short what = EVBUFFER_WRITE;
958 if (event == EV_TIMEOUT) {
959 what |= EVBUFFER_TIMEOUT;
960 goto err;
963 if (EVBUFFER_LENGTH(bufev->output) != 0) {
964 ret = tls_write(client->ctx,
965 EVBUFFER_DATA(bufev->output),
966 EVBUFFER_LENGTH(bufev->output));
967 switch (ret) {
968 case TLS_WANT_POLLIN:
969 case TLS_WANT_POLLOUT:
970 goto retry;
971 case -1:
972 what |= EVBUFFER_ERROR;
973 goto err;
975 len = ret;
976 evbuffer_drain(bufev->output, len);
979 if (EVBUFFER_LENGTH(bufev->output) != 0)
980 event_add(&bufev->ev_write, NULL);
982 if (bufev->writecb != NULL &&
983 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
984 (*bufev->writecb)(bufev, bufev->cbarg);
985 return;
987 retry:
988 event_add(&bufev->ev_write, NULL);
989 return;
990 err:
991 log_err(client, "tls error: %s", tls_error(client->ctx));
992 (*bufev->errorcb)(bufev, what, bufev->cbarg);
995 static void
996 client_read(struct bufferevent *bev, void *d)
998 struct client *c = d;
999 struct evbuffer *src = EVBUFFER_INPUT(bev);
1000 const char *parse_err = "invalid request";
1001 char decoded[DOMAIN_NAME_LEN];
1002 size_t len;
1004 bufferevent_disable(bev, EVBUFFER_READ);
1007 * libevent2 can still somehow call this function, even
1008 * though I never enable EV_READ in the bufferevent. If
1009 * that's the case, bail out.
1011 if (c->type != REQUEST_UNDECIDED)
1012 return;
1014 /* max url len + \r\n */
1015 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1016 log_err(c, "too much data received");
1017 start_reply(c, BAD_REQUEST, "bad request");
1018 return;
1021 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1022 if (c->req == NULL) {
1023 /* not enough data yet. */
1024 bufferevent_enable(bev, EVBUFFER_READ);
1025 return;
1027 c->reqlen = strlen(c->req);
1028 if (c->reqlen > 1024+2) {
1029 log_err(c, "URL too long");
1030 start_reply(c, BAD_REQUEST, "bad request");
1031 return;
1034 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1035 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1036 log_err(c, "IRI parse error: %s", parse_err);
1037 start_reply(c, BAD_REQUEST, "bad request");
1038 return;
1041 if (apply_reverse_proxy(c))
1042 return;
1044 /* ignore the port number */
1045 if (strcmp(c->iri.schema, "gemini") ||
1046 strcmp(decoded, c->domain)) {
1047 start_reply(c, PROXY_REFUSED, "won't proxy request");
1048 return;
1051 if (apply_require_ca(c) ||
1052 apply_block_return(c)||
1053 apply_fastcgi(c))
1054 return;
1056 if (c->host->entrypoint != NULL) {
1057 c->loc = 0;
1058 start_cgi(c->host->entrypoint, c->iri.path, c);
1059 return;
1062 open_file(c);
1065 void
1066 client_write(struct bufferevent *bev, void *d)
1068 struct client *c = d;
1069 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1070 char buf[BUFSIZ];
1071 ssize_t r;
1073 switch (c->type) {
1074 case REQUEST_UNDECIDED:
1076 * Ignore spurious calls when we still don't have idea
1077 * what to do with the request.
1079 break;
1081 case REQUEST_FILE:
1082 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1083 log_warn(c, "read: %s", strerror(errno));
1084 client_error(bev, EVBUFFER_ERROR, c);
1085 return;
1086 } else if (r == 0) {
1087 client_close(c);
1088 return;
1089 } else if (r != sizeof(buf))
1090 c->type = REQUEST_DONE;
1091 bufferevent_write(bev, buf, r);
1092 break;
1094 case REQUEST_DIR:
1095 /* TODO: handle big big directories better */
1096 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1097 evbuffer_add_printf(out, "=> %s\n",
1098 c->dir[c->diroff]->d_name);
1099 free(c->dir[c->diroff]);
1101 free(c->dir);
1102 c->dir = NULL;
1104 c->type = REQUEST_DONE;
1106 event_add(&c->bev->ev_write, NULL);
1107 break;
1109 case REQUEST_CGI:
1110 case REQUEST_FCGI:
1111 case REQUEST_PROXY:
1113 * Here we depend on the cgi/fastcgi or proxy
1114 * connection to provide data.
1116 break;
1118 case REQUEST_DONE:
1119 if (EVBUFFER_LENGTH(out) == 0)
1120 client_close(c);
1121 break;
1125 static void
1126 client_error(struct bufferevent *bev, short error, void *d)
1128 struct client *c = d;
1130 c->type = REQUEST_DONE;
1132 if (error & EVBUFFER_TIMEOUT) {
1133 log_warn(c, "timeout reached, "
1134 "forcefully closing the connection");
1135 if (c->code == 0)
1136 start_reply(c, BAD_REQUEST, "timeout");
1137 else
1138 client_close(c);
1139 return;
1142 if (error & EVBUFFER_EOF) {
1143 client_close(c);
1144 return;
1147 log_err(c, "unknown bufferevent error %x", error);
1148 client_close(c);
1151 void
1152 start_reply(struct client *c, int code, const char *meta)
1154 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1155 const char *lang;
1156 int r, rr;
1158 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1160 c->code = code;
1161 c->meta = meta;
1163 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1164 if (r == -1)
1165 goto err;
1167 /* 2 digit status + space + 1024 max reply */
1168 if (r > 1027)
1169 goto overflow;
1171 if (c->type != REQUEST_CGI &&
1172 c->type != REQUEST_FCGI &&
1173 c->type != REQUEST_PROXY &&
1174 !strcmp(meta, "text/gemini") &&
1175 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1176 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1177 if (rr == -1)
1178 goto err;
1179 if (r + rr > 1027)
1180 goto overflow;
1183 bufferevent_write(c->bev, "\r\n", 2);
1185 if (!vhost_disable_log(c->host, c->iri.path))
1186 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1188 if (code != 20)
1189 c->type = REQUEST_DONE;
1191 return;
1193 err:
1194 log_err(c, "evbuffer_add_printf error: no memory");
1195 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1196 client_close(c);
1197 return;
1199 overflow:
1200 log_warn(c, "reply header overflow");
1201 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1202 start_reply(c, TEMP_FAILURE, "internal error");
1205 static void
1206 client_close_ev(int fd, short event, void *d)
1208 struct client *c = d;
1210 switch (tls_close(c->ctx)) {
1211 case TLS_WANT_POLLIN:
1212 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1213 break;
1214 case TLS_WANT_POLLOUT:
1215 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1216 break;
1219 connected_clients--;
1221 free(c->req);
1223 tls_free(c->ctx);
1224 c->ctx = NULL;
1226 free(c->header);
1228 if (c->pfd != -1)
1229 close(c->pfd);
1231 if (c->dir != NULL)
1232 free(c->dir);
1234 close(c->fd);
1235 c->fd = -1;
1238 static void
1239 client_proxy_close(int fd, short event, void *d)
1241 struct tls *ctx = d;
1243 if (ctx == NULL) {
1244 close(fd);
1245 return;
1248 switch (tls_close(ctx)) {
1249 case TLS_WANT_POLLIN:
1250 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1251 break;
1252 case TLS_WANT_POLLOUT:
1253 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1254 break;
1257 tls_free(ctx);
1258 close(fd);
1261 void
1262 client_close(struct client *c)
1265 * We may end up calling client_close in various situations
1266 * and for the most unexpected reasons. Therefore, we need to
1267 * ensure that everything gets properly released once we reach
1268 * this point.
1271 SPLAY_REMOVE(client_tree_id, &clients, c);
1273 if (c->cgibev != NULL) {
1274 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1275 bufferevent_free(c->cgibev);
1276 c->cgibev = NULL;
1277 close(c->pfd);
1278 c->pfd = -1;
1281 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1282 bufferevent_free(c->bev);
1283 c->bev = NULL;
1285 if (c->proxyevset &&
1286 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1287 c->proxyevset = 0;
1288 event_del(&c->proxyev);
1291 if (c->pfd != -1 && c->proxyctx != NULL) {
1292 /* shut down the proxy TLS connection */
1293 client_proxy_close(c->pfd, 0, c->proxyctx);
1294 c->pfd = -1;
1297 if (c->proxybev != NULL)
1298 bufferevent_free(c->proxybev);
1300 client_close_ev(c->fd, 0, c);
1303 static void
1304 cgi_read(struct bufferevent *bev, void *d)
1306 struct client *client = d;
1307 struct evbuffer *src = EVBUFFER_INPUT(bev);
1308 char *header;
1309 size_t len;
1310 int code;
1312 /* intercept the header */
1313 if (client->code == 0) {
1314 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1315 if (header == NULL) {
1316 /* max reply + \r\n */
1317 if (EVBUFFER_LENGTH(src) > 1029) {
1318 log_warn(client, "CGI script is trying to "
1319 "send a header too long.");
1320 cgi_error(bev, EVBUFFER_READ, client);
1323 /* wait a bit */
1324 return;
1327 if (len < 3 || len > 1029 ||
1328 !isdigit(header[0]) ||
1329 !isdigit(header[1]) ||
1330 !isspace(header[2])) {
1331 free(header);
1332 log_warn(client, "CGI script is trying to send a "
1333 "malformed header");
1334 cgi_error(bev, EVBUFFER_READ, client);
1335 return;
1338 client->header = header;
1339 code = (header[0] - '0') * 10 + (header[1] - '0');
1341 if (code < 10 || code >= 70) {
1342 log_warn(client, "CGI script is trying to send an "
1343 "invalid reply code (%d)", code);
1344 cgi_error(bev, EVBUFFER_READ, client);
1345 return;
1348 start_reply(client, code, header + 3);
1350 if (client->code < 20 || client->code > 29) {
1351 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1352 return;
1356 bufferevent_write_buffer(client->bev, src);
1359 static void
1360 cgi_write(struct bufferevent *bev, void *d)
1363 * Never called. We don't send data to a CGI script.
1365 abort();
1368 static void
1369 cgi_error(struct bufferevent *bev, short error, void *d)
1371 struct client *client = d;
1373 if (error & EVBUFFER_ERROR)
1374 log_err(client, "%s: evbuffer error (%x): %s",
1375 __func__, error, strerror(errno));
1377 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1378 bufferevent_free(bev);
1379 client->cgibev = NULL;
1381 close(client->pfd);
1382 client->pfd = -1;
1384 client->type = REQUEST_DONE;
1385 if (client->code != 0)
1386 client_write(client->bev, client);
1387 else
1388 start_reply(client, CGI_ERROR, "CGI error");
1391 static void
1392 do_accept(int sock, short et, void *d)
1394 struct client *c;
1395 struct sockaddr_storage addr;
1396 struct sockaddr *saddr;
1397 socklen_t len;
1398 int fd;
1400 saddr = (struct sockaddr*)&addr;
1401 len = sizeof(addr);
1402 if ((fd = accept(sock, saddr, &len)) == -1) {
1403 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1404 errno == ECONNABORTED)
1405 return;
1406 fatal("accept: %s", strerror(errno));
1409 mark_nonblock(fd);
1411 c = xcalloc(1, sizeof(*c));
1412 c->id = ++server_client_id;
1413 c->fd = fd;
1414 c->pfd = -1;
1415 c->addr = addr;
1417 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1418 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1419 close(c->fd);
1420 free(c);
1421 return;
1424 SPLAY_INSERT(client_tree_id, &clients, c);
1425 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1426 connected_clients++;
1429 struct client *
1430 client_by_id(int id)
1432 struct client find;
1434 find.id = id;
1435 return SPLAY_FIND(client_tree_id, &clients, &find);
1438 static void
1439 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1441 struct client *c;
1443 if ((c = client_by_id(imsg->hdr.peerid)) == NULL) {
1444 if (imsg->fd != -1)
1445 close(imsg->fd);
1446 return;
1449 if ((c->pfd = imsg->fd) == -1) {
1450 start_reply(c, TEMP_FAILURE, "internal server error");
1451 return;
1454 c->type = REQUEST_CGI;
1456 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1457 cgi_error, c);
1459 bufferevent_enable(c->cgibev, EV_READ);
1462 static void
1463 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1465 struct client *c;
1466 int id;
1468 id = imsg->hdr.peerid;
1470 if ((c = client_by_id(id)) == NULL) {
1471 if (imsg->fd != -1)
1472 close(imsg->fd);
1473 return;
1476 if ((c->pfd = imsg->fd) == -1) {
1477 start_reply(c, CGI_ERROR, "CGI error");
1478 return;
1481 mark_nonblock(c->pfd);
1483 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1484 fcgi_error, c);
1485 if (c->cgibev == NULL) {
1486 start_reply(c, TEMP_FAILURE, "internal server error");
1487 return;
1490 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1491 fcgi_req(c);
1494 static void
1495 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1497 struct client *c;
1498 int id;
1500 id = imsg->hdr.peerid;
1501 if ((c = client_by_id(id)) == NULL) {
1502 if (imsg->fd != -1)
1503 close(imsg->fd);
1504 return;
1507 if ((c->pfd = imsg->fd) == -1) {
1508 start_reply(c, PROXY_ERROR, "proxy error");
1509 return;
1512 mark_nonblock(c->pfd);
1514 if (proxy_init(c) == -1)
1515 start_reply(c, PROXY_ERROR, "proxy error");
1518 static void
1519 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1522 * don't call event_loopbreak since we want to finish to
1523 * handle the ongoing connections.
1526 shutting_down = 1;
1528 event_del(&e4);
1529 if (has_ipv6)
1530 event_del(&e6);
1531 if (has_siginfo)
1532 signal_del(&siginfo);
1533 event_del(&imsgev);
1534 signal_del(&sigusr2);
1537 static void
1538 handle_dispatch_imsg(int fd, short ev, void *d)
1540 struct imsgbuf *ibuf = d;
1541 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1544 static void
1545 handle_siginfo(int fd, short ev, void *d)
1547 log_info(NULL, "%d connected clients", connected_clients);
1550 void
1551 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1553 ctx = ctx_;
1555 SPLAY_INIT(&clients);
1557 event_init();
1559 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1560 event_add(&e4, NULL);
1562 if (sock6 != -1) {
1563 has_ipv6 = 1;
1564 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1565 event_add(&e6, NULL);
1568 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1569 event_add(&imsgev, NULL);
1571 #ifdef SIGINFO
1572 has_siginfo = 1;
1573 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1574 signal_add(&siginfo, NULL);
1575 #endif
1576 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1577 signal_add(&sigusr2, NULL);
1579 sandbox_server_process();
1580 event_dispatch();
1581 _exit(0);
1584 int
1585 client_tree_cmp(struct client *a, struct client *b)
1587 if (a->id == b->id)
1588 return 0;
1589 else if (a->id < b->id)
1590 return -1;
1591 else
1592 return +1;
1595 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)