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 struct location *
211 vhost_reverse_proxy(struct vhost *v, const char *path)
213 struct location *loc;
215 if (v == NULL || path == NULL)
216 return NULL;
218 loc = TAILQ_FIRST(&v->locations);
219 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
220 if (loc->proxy_host != NULL)
221 if (matches(loc->match, path))
222 return loc;
225 loc = TAILQ_FIRST(&v->locations);
226 if (loc->proxy_host != NULL)
227 return loc;
228 return NULL;
231 int
232 vhost_fastcgi(struct vhost *v, const char *path)
234 struct location *loc;
236 if (v == NULL || path == NULL)
237 return -1;
239 loc = TAILQ_FIRST(&v->locations);
240 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
241 if (loc->fcgi != -1)
242 if (matches(loc->match, path))
243 return loc->fcgi;
246 loc = TAILQ_FIRST(&v->locations);
247 return loc->fcgi;
250 int
251 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
253 struct location *loc;
254 size_t l = 0;
256 if (v == NULL || path == NULL)
257 return -1;
259 loc = TAILQ_FIRST(&v->locations);
260 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
261 l++;
262 if (loc->dirfd != -1)
263 if (matches(loc->match, path)) {
264 *retloc = l;
265 return loc->dirfd;
269 *retloc = 0;
270 loc = TAILQ_FIRST(&v->locations);
271 return loc->dirfd;
274 int
275 vhost_strip(struct vhost *v, const char *path)
277 struct location *loc;
279 if (v == NULL || path == NULL)
280 return 0;
282 loc = TAILQ_FIRST(&v->locations);
283 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
284 if (loc->strip != 0) {
285 if (matches(loc->match, path))
286 return loc->strip;
290 loc = TAILQ_FIRST(&v->locations);
291 return loc->strip;
294 X509_STORE *
295 vhost_require_ca(struct vhost *v, const char *path)
297 struct location *loc;
299 if (v == NULL || path == NULL)
300 return NULL;
302 loc = TAILQ_FIRST(&v->locations);
303 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
304 if (loc->reqca != NULL) {
305 if (matches(loc->match, path))
306 return loc->reqca;
310 loc = TAILQ_FIRST(&v->locations);
311 return loc->reqca;
314 int
315 vhost_disable_log(struct vhost *v, const char *path)
317 struct location *loc;
319 if (v == NULL || path == NULL)
320 return 0;
322 loc = TAILQ_FIRST(&v->locations);
323 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
324 if (loc->disable_log && matches(loc->match, path))
325 return 1;
328 loc = TAILQ_FIRST(&v->locations);
329 return loc->disable_log;
332 static int
333 check_path(struct client *c, const char *path, int *fd)
335 struct stat sb;
336 const char *p;
337 int dirfd, strip;
339 assert(path != NULL);
341 /*
342 * in send_dir we add an initial / (to be redirect-friendly),
343 * but here we want to skip it
344 */
345 if (*path == '/')
346 path++;
348 strip = vhost_strip(c->host, path);
349 p = strip_path(path, strip);
351 if (*p == '/')
352 p = p+1;
353 if (*p == '\0')
354 p = ".";
356 dirfd = vhost_dirfd(c->host, path, &c->loc);
357 log_debug(c, "check_path: strip=%d path=%s original=%s",
358 strip, p, path);
359 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
360 return FILE_MISSING;
362 if (fstat(*fd, &sb) == -1) {
363 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
364 return FILE_MISSING;
367 if (S_ISDIR(sb.st_mode))
368 return FILE_DIRECTORY;
370 if (sb.st_mode & S_IXUSR)
371 return FILE_EXECUTABLE;
373 return FILE_EXISTS;
376 static void
377 open_file(struct client *c)
379 switch (check_path(c, c->iri.path, &c->pfd)) {
380 case FILE_EXECUTABLE:
381 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
382 start_cgi(c->iri.path, "", c);
383 return;
386 /* fallthrough */
388 case FILE_EXISTS:
389 c->type = REQUEST_FILE;
390 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
391 return;
393 case FILE_DIRECTORY:
394 open_dir(c);
395 return;
397 case FILE_MISSING:
398 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
399 check_for_cgi(c);
400 return;
402 start_reply(c, NOT_FOUND, "not found");
403 return;
405 default:
406 /* unreachable */
407 abort();
411 /*
412 * the inverse of this algorithm, i.e. starting from the start of the
413 * path + strlen(cgi), and checking if each component, should be
414 * faster. But it's tedious to write. This does the opposite: starts
415 * from the end and strip one component at a time, until either an
416 * executable is found or we emptied the path.
417 */
418 static void
419 check_for_cgi(struct client *c)
421 char path[PATH_MAX];
422 char *end;
424 strlcpy(path, c->iri.path, sizeof(path));
425 end = strchr(path, '\0');
427 while (end > path) {
428 /*
429 * go up one level. UNIX paths are simple and POSIX
430 * dirname, with its ambiguities on if the given
431 * pointer is changed or not, gives me headaches.
432 */
433 while (*end != '/' && end > path)
434 end--;
436 if (end == path)
437 break;
439 *end = '\0';
441 switch (check_path(c, path, &c->pfd)) {
442 case FILE_EXECUTABLE:
443 start_cgi(path, end+1, c);
444 return;
445 case FILE_MISSING:
446 break;
447 default:
448 goto err;
451 *end = '/';
452 end--;
455 err:
456 start_reply(c, NOT_FOUND, "not found");
457 return;
460 void
461 mark_nonblock(int fd)
463 int flags;
465 if ((flags = fcntl(fd, F_GETFL)) == -1)
466 fatal("fcntl(F_GETFL): %s", strerror(errno));
467 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
468 fatal("fcntl(F_SETFL): %s", strerror(errno));
471 static void
472 handle_handshake(int fd, short ev, void *d)
474 struct client *c = d;
475 struct vhost *h;
476 struct alist *a;
477 const char *servname;
478 const char *parse_err = "unknown error";
480 switch (tls_handshake(c->ctx)) {
481 case 0: /* success */
482 case -1: /* already handshaked */
483 break;
484 case TLS_WANT_POLLIN:
485 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
486 return;
487 case TLS_WANT_POLLOUT:
488 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
489 return;
490 default:
491 /* unreachable */
492 abort();
495 c->bev = bufferevent_new(fd, client_read, client_write,
496 client_error, c);
497 if (c->bev == NULL)
498 fatal("%s: failed to allocate client buffer: %s",
499 __func__, strerror(errno));
501 event_set(&c->bev->ev_read, c->fd, EV_READ,
502 client_tls_readcb, c->bev);
503 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
504 client_tls_writecb, c->bev);
506 #if HAVE_LIBEVENT2
507 evbuffer_unfreeze(c->bev->input, 0);
508 evbuffer_unfreeze(c->bev->output, 1);
509 #endif
511 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
512 log_debug(c, "handshake: missing SNI");
513 goto err;
516 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
517 log_info(c, "puny_decode: %s", parse_err);
518 goto err;
521 TAILQ_FOREACH(h, &hosts, vhosts) {
522 if (matches(h->domain, c->domain))
523 goto found;
524 TAILQ_FOREACH(a, &h->aliases, aliases) {
525 if (matches(a->alias, c->domain))
526 goto found;
530 found:
531 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
532 servname != NULL ? servname : "(null)",
533 c->domain,
534 h != NULL ? h->domain : "(null)");
536 if (h != NULL) {
537 c->host = h;
538 bufferevent_enable(c->bev, EV_READ);
539 return;
542 err:
543 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
546 static const char *
547 strip_path(const char *path, int strip)
549 char *t;
551 while (strip > 0) {
552 if ((t = strchr(path, '/')) == NULL) {
553 path = strchr(path, '\0');
554 break;
556 path = t;
557 strip--;
560 return path;
563 static void
564 fmt_sbuf(const char *fmt, struct client *c, const char *path)
566 size_t i;
567 char buf[32];
569 memset(buf, 0, sizeof(buf));
570 for (i = 0; *fmt; ++fmt) {
571 if (i == sizeof(buf)-1 || *fmt == '%') {
572 strlcat(c->sbuf, buf, sizeof(c->sbuf));
573 memset(buf, 0, sizeof(buf));
574 i = 0;
577 if (*fmt != '%') {
578 buf[i++] = *fmt;
579 continue;
582 switch (*++fmt) {
583 case '%':
584 strlcat(c->sbuf, "%", sizeof(c->sbuf));
585 break;
586 case 'p':
587 if (*path != '/')
588 strlcat(c->sbuf, "/", sizeof(c->sbuf));
589 strlcat(c->sbuf, path, sizeof(c->sbuf));
590 break;
591 case 'q':
592 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
593 break;
594 case 'P':
595 snprintf(buf, sizeof(buf), "%d", conf.port);
596 strlcat(c->sbuf, buf, sizeof(c->sbuf));
597 memset(buf, 0, sizeof(buf));
598 break;
599 case 'N':
600 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
601 break;
602 default:
603 fatal("%s: unknown fmt specifier %c",
604 __func__, *fmt);
608 if (i != 0)
609 strlcat(c->sbuf, buf, sizeof(c->sbuf));
612 /* 1 if a matching `block return' (and apply it), 0 otherwise */
613 static int
614 apply_block_return(struct client *c)
616 const char *fmt, *path;
617 int code;
619 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
620 return 0;
622 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
623 fmt_sbuf(fmt, c, path);
625 start_reply(c, code, c->sbuf);
626 return 1;
629 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
630 static int
631 apply_reverse_proxy(struct client *c)
633 struct location *loc;
634 struct connreq r;
636 if ((loc = vhost_reverse_proxy(c->host, c->iri.path)) == NULL)
637 return 0;
639 log_debug(c, "opening proxy connection for %s:%s",
640 loc->proxy_host, loc->proxy_port);
642 strlcpy(r.host, loc->proxy_host, sizeof(r.host));
643 strlcpy(r.port, loc->proxy_port, sizeof(r.port));
645 strlcpy(c->domain, loc->proxy_host, sizeof(c->domain));
647 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
648 imsg_flush(&exibuf);
650 return 1;
653 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
654 static int
655 apply_fastcgi(struct client *c)
657 int id;
658 struct fcgi *f;
660 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
661 return 0;
663 f = &fcgi[id];
665 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
666 f->path, f->port, f->prog);
668 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
669 &id, sizeof(id));
670 imsg_flush(&exibuf);
671 return 1;
674 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
675 static int
676 apply_require_ca(struct client *c)
678 X509_STORE *store;
679 const uint8_t *cert;
680 size_t len;
682 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
683 return 0;
685 if (!tls_peer_cert_provided(c->ctx)) {
686 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
687 return 1;
690 cert = tls_peer_cert_chain_pem(c->ctx, &len);
691 if (!validate_against_ca(store, cert, len)) {
692 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
693 return 1;
696 return 0;
699 static size_t
700 host_nth(struct vhost *h)
702 struct vhost *v;
703 size_t i = 0;
705 TAILQ_FOREACH(v, &hosts, vhosts) {
706 if (v == h)
707 return i;
708 i++;
711 abort();
714 static void
715 start_cgi(const char *spath, const char *relpath, struct client *c)
717 char addr[NI_MAXHOST];
718 const char *t;
719 struct cgireq req;
720 int e;
722 c->type = REQUEST_CGI;
724 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
725 addr, sizeof(addr),
726 NULL, 0,
727 NI_NUMERICHOST);
728 if (e != 0)
729 fatal("getnameinfo failed");
731 memset(&req, 0, sizeof(req));
733 memcpy(req.buf, c->req, sizeof(req.buf));
735 req.iri_schema_off = c->iri.schema - c->req;
736 req.iri_host_off = c->iri.host - c->req;
737 req.iri_port_off = c->iri.port - c->req;
738 req.iri_path_off = c->iri.path - c->req;
739 req.iri_query_off = c->iri.query - c->req;
740 req.iri_fragment_off = c->iri.fragment - c->req;
742 req.iri_portno = c->iri.port_no;
744 strlcpy(req.spath, spath, sizeof(req.spath));
745 strlcpy(req.relpath, relpath, sizeof(req.relpath));
746 strlcpy(req.addr, addr, sizeof(req.addr));
748 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
749 strlcpy(req.subject, t, sizeof(req.subject));
750 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
751 strlcpy(req.issuer, t, sizeof(req.issuer));
752 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
753 strlcpy(req.hash, t, sizeof(req.hash));
754 if ((t = tls_conn_version(c->ctx)) != NULL)
755 strlcpy(req.version, t, sizeof(req.version));
756 if ((t = tls_conn_cipher(c->ctx)) != NULL)
757 strlcpy(req.cipher, t, sizeof(req.cipher));
759 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
760 req.notbefore = tls_peer_cert_notbefore(c->ctx);
761 req.notafter = tls_peer_cert_notafter(c->ctx);
763 req.host_off = host_nth(c->host);
764 req.loc_off = c->loc;
766 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
767 imsg_flush(&exibuf);
769 close(c->pfd);
772 static void
773 open_dir(struct client *c)
775 size_t len;
776 int dirfd, root;
777 char *before_file;
779 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
781 len = strlen(c->iri.path);
782 if (len > 0 && !ends_with(c->iri.path, "/")) {
783 redirect_canonical_dir(c);
784 return;
787 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
788 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
789 if (!ends_with(c->sbuf, "/"))
790 strlcat(c->sbuf, "/", sizeof(c->sbuf));
791 before_file = strchr(c->sbuf, '\0');
792 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
793 sizeof(c->sbuf));
794 if (len >= sizeof(c->sbuf)) {
795 start_reply(c, TEMP_FAILURE, "internal server error");
796 return;
799 c->iri.path = c->sbuf;
801 /* close later unless we have to generate the dir listing */
802 dirfd = c->pfd;
803 c->pfd = -1;
805 switch (check_path(c, c->iri.path, &c->pfd)) {
806 case FILE_EXECUTABLE:
807 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
808 start_cgi(c->iri.path, "", c);
809 break;
812 /* fallthrough */
814 case FILE_EXISTS:
815 c->type = REQUEST_FILE;
816 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
817 break;
819 case FILE_DIRECTORY:
820 start_reply(c, TEMP_REDIRECT, c->sbuf);
821 break;
823 case FILE_MISSING:
824 *before_file = '\0';
826 if (!vhost_auto_index(c->host, c->iri.path)) {
827 start_reply(c, NOT_FOUND, "not found");
828 break;
831 c->type = REQUEST_DIR;
833 c->dirlen = scandir_fd(dirfd, &c->dir,
834 root ? select_non_dotdot : select_non_dot,
835 alphasort);
836 if (c->dirlen == -1) {
837 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
838 c->pfd, c->host->domain, c->iri.path, strerror(errno));
839 start_reply(c, TEMP_FAILURE, "internal server error");
840 return;
842 c->diroff = 0;
843 c->off = 0;
845 start_reply(c, SUCCESS, "text/gemini");
846 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
847 "# Index of %s\n\n", c->iri.path);
848 return;
850 default:
851 /* unreachable */
852 abort();
855 close(dirfd);
858 static void
859 redirect_canonical_dir(struct client *c)
861 size_t len;
863 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
864 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
865 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
867 if (len >= sizeof(c->sbuf)) {
868 start_reply(c, TEMP_FAILURE, "internal server error");
869 return;
872 start_reply(c, TEMP_REDIRECT, c->sbuf);
875 static void
876 client_tls_readcb(int fd, short event, void *d)
878 struct bufferevent *bufev = d;
879 struct client *client = bufev->cbarg;
880 ssize_t ret;
881 size_t len;
882 int what = EVBUFFER_READ;
883 int howmuch = IBUF_READ_SIZE;
884 char buf[IBUF_READ_SIZE];
886 if (event == EV_TIMEOUT) {
887 what |= EVBUFFER_TIMEOUT;
888 goto err;
891 if (bufev->wm_read.high != 0)
892 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
894 switch (ret = tls_read(client->ctx, buf, howmuch)) {
895 case TLS_WANT_POLLIN:
896 case TLS_WANT_POLLOUT:
897 goto retry;
898 case -1:
899 what |= EVBUFFER_ERROR;
900 goto err;
902 len = ret;
904 if (len == 0) {
905 what |= EVBUFFER_EOF;
906 goto err;
909 if (evbuffer_add(bufev->input, buf, len) == -1) {
910 what |= EVBUFFER_ERROR;
911 goto err;
914 event_add(&bufev->ev_read, NULL);
915 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
916 return;
917 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
918 /*
919 * here we could implement a read pressure policy.
920 */
923 if (bufev->readcb != NULL)
924 (*bufev->readcb)(bufev, bufev->cbarg);
926 return;
928 retry:
929 event_add(&bufev->ev_read, NULL);
930 return;
932 err:
933 (*bufev->errorcb)(bufev, what, bufev->cbarg);
936 static void
937 client_tls_writecb(int fd, short event, void *d)
939 struct bufferevent *bufev = d;
940 struct client *client = bufev->cbarg;
941 ssize_t ret;
942 size_t len;
943 short what = EVBUFFER_WRITE;
945 if (event == EV_TIMEOUT) {
946 what |= EVBUFFER_TIMEOUT;
947 goto err;
950 if (EVBUFFER_LENGTH(bufev->output) != 0) {
951 ret = tls_write(client->ctx,
952 EVBUFFER_DATA(bufev->output),
953 EVBUFFER_LENGTH(bufev->output));
954 switch (ret) {
955 case TLS_WANT_POLLIN:
956 case TLS_WANT_POLLOUT:
957 goto retry;
958 case -1:
959 what |= EVBUFFER_ERROR;
960 goto err;
962 len = ret;
963 evbuffer_drain(bufev->output, len);
966 if (EVBUFFER_LENGTH(bufev->output) != 0)
967 event_add(&bufev->ev_write, NULL);
969 if (bufev->writecb != NULL &&
970 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
971 (*bufev->writecb)(bufev, bufev->cbarg);
972 return;
974 retry:
975 event_add(&bufev->ev_write, NULL);
976 return;
977 err:
978 log_err(client, "tls error: %s", tls_error(client->ctx));
979 (*bufev->errorcb)(bufev, what, bufev->cbarg);
982 static void
983 client_read(struct bufferevent *bev, void *d)
985 struct client *c = d;
986 struct evbuffer *src = EVBUFFER_INPUT(bev);
987 const char *parse_err = "invalid request";
988 char decoded[DOMAIN_NAME_LEN];
989 size_t len;
991 bufferevent_disable(bev, EVBUFFER_READ);
993 /* max url len + \r\n */
994 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
995 log_err(c, "too much data received");
996 start_reply(c, BAD_REQUEST, "bad request");
997 return;
1000 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1001 if (c->req == NULL) {
1002 /* not enough data yet. */
1003 bufferevent_enable(bev, EVBUFFER_READ);
1004 return;
1007 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1008 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1009 log_err(c, "IRI parse error: %s", parse_err);
1010 start_reply(c, BAD_REQUEST, "bad request");
1011 return;
1014 if (apply_reverse_proxy(c))
1015 return;
1017 /* ignore the port number */
1018 if (strcmp(c->iri.schema, "gemini") ||
1019 strcmp(decoded, c->domain)) {
1020 start_reply(c, PROXY_REFUSED, "won't proxy request");
1021 return;
1024 if (apply_require_ca(c) ||
1025 apply_block_return(c)||
1026 apply_fastcgi(c))
1027 return;
1029 if (c->host->entrypoint != NULL) {
1030 c->loc = 0;
1031 start_cgi(c->host->entrypoint, c->iri.path, c);
1032 return;
1035 open_file(c);
1038 void
1039 client_write(struct bufferevent *bev, void *d)
1041 struct client *c = d;
1042 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1043 char buf[BUFSIZ];
1044 ssize_t r;
1046 switch (c->type) {
1047 case REQUEST_UNDECIDED:
1049 * Ignore spurious calls when we still don't have idea
1050 * what to do with the request.
1052 break;
1054 case REQUEST_FILE:
1055 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1056 log_warn(c, "read: %s", strerror(errno));
1057 client_error(bev, EVBUFFER_ERROR, c);
1058 return;
1059 } else if (r == 0) {
1060 client_close(c);
1061 return;
1062 } else if (r != sizeof(buf))
1063 c->type = REQUEST_DONE;
1064 bufferevent_write(bev, buf, r);
1065 break;
1067 case REQUEST_DIR:
1068 /* TODO: handle big big directories better */
1069 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1070 evbuffer_add_printf(out, "=> %s\n",
1071 c->dir[c->diroff]->d_name);
1072 free(c->dir[c->diroff]);
1074 free(c->dir);
1075 c->dir = NULL;
1077 c->type = REQUEST_DONE;
1079 event_add(&c->bev->ev_write, NULL);
1080 break;
1082 case REQUEST_CGI:
1083 case REQUEST_FCGI:
1084 case REQUEST_PROXY:
1086 * Here we depend on on the cgi script or fastcgi
1087 * connection to provide data.
1089 break;
1091 case REQUEST_DONE:
1092 if (EVBUFFER_LENGTH(out) == 0)
1093 client_close(c);
1094 break;
1098 static void
1099 client_error(struct bufferevent *bev, short error, void *d)
1101 struct client *c = d;
1103 c->type = REQUEST_DONE;
1105 if (error & EVBUFFER_TIMEOUT) {
1106 log_warn(c, "timeout reached, "
1107 "forcefully closing the connection");
1108 if (c->code == 0)
1109 start_reply(c, BAD_REQUEST, "timeout");
1110 else
1111 client_close(c);
1112 return;
1115 if (error & EVBUFFER_EOF) {
1116 client_close(c);
1117 return;
1120 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1121 client_close(c);
1124 void
1125 start_reply(struct client *c, int code, const char *meta)
1127 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1128 const char *lang;
1129 int r, rr;
1131 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1133 c->code = code;
1134 c->meta = meta;
1136 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1137 if (r == -1)
1138 goto err;
1140 /* 2 digit status + space + 1024 max reply */
1141 if (r > 1027)
1142 goto overflow;
1144 if (c->type != REQUEST_CGI &&
1145 c->type != REQUEST_FCGI &&
1146 c->type != REQUEST_PROXY &&
1147 !strcmp(meta, "text/gemini") &&
1148 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1149 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1150 if (rr == -1)
1151 goto err;
1152 if (r + rr > 1027)
1153 goto overflow;
1156 bufferevent_write(c->bev, "\r\n", 2);
1158 if (!vhost_disable_log(c->host, c->iri.path))
1159 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1161 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1162 c->type = REQUEST_DONE;
1164 return;
1166 err:
1167 log_err(c, "evbuffer_add_printf error: no memory");
1168 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1169 client_close(c);
1170 return;
1172 overflow:
1173 log_warn(c, "reply header overflow");
1174 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1175 start_reply(c, TEMP_FAILURE, "internal error");
1178 static void
1179 client_close_ev(int fd, short event, void *d)
1181 struct client *c = d;
1183 switch (tls_close(c->ctx)) {
1184 case TLS_WANT_POLLIN:
1185 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1186 break;
1187 case TLS_WANT_POLLOUT:
1188 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1189 break;
1192 connected_clients--;
1194 free(c->req);
1196 tls_free(c->ctx);
1197 c->ctx = NULL;
1199 free(c->header);
1201 if (c->pfd != -1)
1202 close(c->pfd);
1204 if (c->dir != NULL)
1205 free(c->dir);
1207 close(c->fd);
1208 c->fd = -1;
1211 static void
1212 client_proxy_close(int fd, short event, void *d)
1214 struct tls *ctx = d;
1216 if (ctx == NULL) {
1217 close(fd);
1218 return;
1221 switch (tls_close(ctx)) {
1222 case TLS_WANT_POLLIN:
1223 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1224 break;
1225 case TLS_WANT_POLLOUT:
1226 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1227 break;
1230 tls_free(ctx);
1231 close(fd);
1234 void
1235 client_close(struct client *c)
1238 * We may end up calling client_close in various situations
1239 * and for the most unexpected reasons. Therefore, we need to
1240 * ensure that everything is properly released once we reach
1241 * this point.
1244 SPLAY_REMOVE(client_tree_id, &clients, c);
1246 if (c->cgibev != NULL) {
1247 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1248 bufferevent_free(c->cgibev);
1249 c->cgibev = NULL;
1250 close(c->pfd);
1251 c->pfd = -1;
1254 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1255 bufferevent_free(c->bev);
1256 c->bev = NULL;
1258 if (c->proxybev != NULL) {
1259 if (event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL))
1260 event_del(&c->proxyev);
1262 if (c->pfd != -1) {
1263 client_proxy_close(c->pfd, 0, c->proxyctx);
1264 c->pfd = -1;
1267 bufferevent_free(c->proxybev);
1270 client_close_ev(c->fd, 0, c);
1273 static void
1274 cgi_read(struct bufferevent *bev, void *d)
1276 struct client *client = d;
1277 struct evbuffer *src = EVBUFFER_INPUT(bev);
1278 char *header;
1279 size_t len;
1280 int code;
1282 /* intercept the header */
1283 if (client->code == 0) {
1284 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1285 if (header == NULL) {
1286 /* max reply + \r\n */
1287 if (EVBUFFER_LENGTH(src) > 1026) {
1288 log_warn(client, "CGI script is trying to "
1289 "send a header too long.");
1290 cgi_error(bev, EVBUFFER_READ, client);
1293 /* wait a bit */
1294 return;
1297 if (len < 3 || len > 1029 ||
1298 !isdigit(header[0]) ||
1299 !isdigit(header[1]) ||
1300 !isspace(header[2])) {
1301 free(header);
1302 log_warn(client, "CGI script is trying to send a "
1303 "malformed header");
1304 cgi_error(bev, EVBUFFER_READ, client);
1305 return;
1308 client->header = header;
1309 code = (header[0] - '0') * 10 + (header[1] - '0');
1311 if (code < 10 || code >= 70) {
1312 log_warn(client, "CGI script is trying to send an "
1313 "invalid reply code (%d)", code);
1314 cgi_error(bev, EVBUFFER_READ, client);
1315 return;
1318 start_reply(client, code, header + 3);
1320 if (client->code < 20 || client->code > 29) {
1321 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1322 return;
1326 bufferevent_write_buffer(client->bev, src);
1329 static void
1330 cgi_write(struct bufferevent *bev, void *d)
1333 * Never called. We don't send data to a CGI script.
1335 abort();
1338 static void
1339 cgi_error(struct bufferevent *bev, short error, void *d)
1341 struct client *client = d;
1343 if (error & EVBUFFER_ERROR)
1344 log_err(client, "%s: evbuffer error (%x): %s",
1345 __func__, error, strerror(errno));
1347 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1348 bufferevent_free(bev);
1349 client->cgibev = NULL;
1351 close(client->pfd);
1352 client->pfd = -1;
1354 client->type = REQUEST_DONE;
1355 if (client->code != 0)
1356 client_write(client->bev, client);
1357 else
1358 start_reply(client, CGI_ERROR, "CGI error");
1361 static void
1362 do_accept(int sock, short et, void *d)
1364 struct client *c;
1365 struct sockaddr_storage addr;
1366 struct sockaddr *saddr;
1367 socklen_t len;
1368 int fd;
1370 saddr = (struct sockaddr*)&addr;
1371 len = sizeof(addr);
1372 if ((fd = accept(sock, saddr, &len)) == -1) {
1373 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1374 errno == ECONNABORTED)
1375 return;
1376 fatal("accept: %s", strerror(errno));
1379 mark_nonblock(fd);
1381 c = xcalloc(1, sizeof(*c));
1382 c->id = ++server_client_id;
1383 c->fd = fd;
1384 c->pfd = -1;
1385 c->addr = addr;
1387 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1388 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1389 close(c->fd);
1390 free(c);
1391 return;
1394 SPLAY_INSERT(client_tree_id, &clients, c);
1395 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1396 connected_clients++;
1399 static struct client *
1400 client_by_id(int id)
1402 struct client *c;
1404 if ((c = try_client_by_id(id)) == NULL)
1405 fatal("in client_by_id: invalid id %d", id);
1406 return c;
1409 struct client *
1410 try_client_by_id(int id)
1412 struct client find;
1414 find.id = id;
1415 return SPLAY_FIND(client_tree_id, &clients, &find);
1418 static void
1419 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1421 struct client *c;
1423 c = client_by_id(imsg->hdr.peerid);
1425 if ((c->pfd = imsg->fd) == -1) {
1426 start_reply(c, TEMP_FAILURE, "internal server error");
1427 return;
1430 c->type = REQUEST_CGI;
1432 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1433 cgi_error, c);
1435 bufferevent_enable(c->cgibev, EV_READ);
1438 static void
1439 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1441 struct client *c;
1442 int id;
1444 id = imsg->hdr.peerid;
1446 if ((c = try_client_by_id(id)) == NULL) {
1447 if (imsg->fd != -1)
1448 close(imsg->fd);
1449 return;
1452 if ((c->pfd = imsg->fd) == -1) {
1453 start_reply(c, CGI_ERROR, "CGI error");
1454 return;
1457 mark_nonblock(c->pfd);
1459 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1460 fcgi_error, c);
1461 if (c->cgibev == NULL) {
1462 start_reply(c, TEMP_FAILURE, "internal server error");
1463 return;
1466 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1467 fcgi_req(c);
1470 static void
1471 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1473 struct client *c;
1474 int id;
1476 id = imsg->hdr.peerid;
1477 if ((c = try_client_by_id(id)) == NULL) {
1478 if (imsg->fd != -1)
1479 close(imsg->fd);
1480 return;
1483 if ((c->pfd = imsg->fd) == -1) {
1484 start_reply(c, PROXY_ERROR, "proxy error");
1485 return;
1488 mark_nonblock(c->pfd);
1490 if (proxy_init(c) == -1)
1491 start_reply(c, PROXY_ERROR, "proxy error");
1494 static void
1495 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1498 * don't call event_loopbreak since we want to finish to
1499 * handle the ongoing connections.
1502 shutting_down = 1;
1504 event_del(&e4);
1505 if (has_ipv6)
1506 event_del(&e6);
1507 if (has_siginfo)
1508 signal_del(&siginfo);
1509 event_del(&imsgev);
1510 signal_del(&sigusr2);
1513 static void
1514 handle_dispatch_imsg(int fd, short ev, void *d)
1516 struct imsgbuf *ibuf = d;
1517 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1520 static void
1521 handle_siginfo(int fd, short ev, void *d)
1523 log_info(NULL, "%d connected clients", connected_clients);
1526 void
1527 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1529 ctx = ctx_;
1531 SPLAY_INIT(&clients);
1533 event_init();
1535 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1536 event_add(&e4, NULL);
1538 if (sock6 != -1) {
1539 has_ipv6 = 1;
1540 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1541 event_add(&e6, NULL);
1544 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1545 event_add(&imsgev, NULL);
1547 #ifdef SIGINFO
1548 has_siginfo = 1;
1549 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1550 signal_add(&siginfo, NULL);
1551 #endif
1552 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1553 signal_add(&sigusr2, NULL);
1555 sandbox_server_process();
1556 event_dispatch();
1557 _exit(0);
1560 int
1561 client_tree_cmp(struct client *a, struct client *b)
1563 if (a->id == b->id)
1564 return 0;
1565 else if (a->id < b->id)
1566 return -1;
1567 else
1568 return +1;
1571 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)