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 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
609 static int
610 apply_reverse_proxy(struct client *c)
612 struct proxy *p;
613 struct connreq r;
615 p = &c->host->proxy;
616 if (p->host == NULL)
617 return 0;
619 log_debug(c, "opening proxy connection for %s:%s",
620 p->host, p->port);
622 strlcpy(r.host, p->host, sizeof(r.host));
623 strlcpy(r.port, p->port, sizeof(r.port));
625 strlcpy(c->domain, p->host, sizeof(c->domain));
627 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
628 imsg_flush(&exibuf);
630 return 1;
633 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
634 static int
635 apply_fastcgi(struct client *c)
637 int id;
638 struct fcgi *f;
640 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
641 return 0;
643 f = &fcgi[id];
645 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
646 f->path, f->port, f->prog);
648 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
649 &id, sizeof(id));
650 imsg_flush(&exibuf);
651 return 1;
654 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
655 static int
656 apply_require_ca(struct client *c)
658 X509_STORE *store;
659 const uint8_t *cert;
660 size_t len;
662 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
663 return 0;
665 if (!tls_peer_cert_provided(c->ctx)) {
666 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
667 return 1;
670 cert = tls_peer_cert_chain_pem(c->ctx, &len);
671 if (!validate_against_ca(store, cert, len)) {
672 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
673 return 1;
676 return 0;
679 static size_t
680 host_nth(struct vhost *h)
682 struct vhost *v;
683 size_t i = 0;
685 TAILQ_FOREACH(v, &hosts, vhosts) {
686 if (v == h)
687 return i;
688 i++;
691 abort();
694 static void
695 start_cgi(const char *spath, const char *relpath, struct client *c)
697 char addr[NI_MAXHOST];
698 const char *t;
699 struct cgireq req;
700 int e;
702 c->type = REQUEST_CGI;
704 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
705 addr, sizeof(addr),
706 NULL, 0,
707 NI_NUMERICHOST);
708 if (e != 0)
709 fatal("getnameinfo failed");
711 memset(&req, 0, sizeof(req));
713 memcpy(req.buf, c->req, sizeof(req.buf));
715 req.iri_schema_off = c->iri.schema - c->req;
716 req.iri_host_off = c->iri.host - c->req;
717 req.iri_port_off = c->iri.port - c->req;
718 req.iri_path_off = c->iri.path - c->req;
719 req.iri_query_off = c->iri.query - c->req;
720 req.iri_fragment_off = c->iri.fragment - c->req;
722 req.iri_portno = c->iri.port_no;
724 strlcpy(req.spath, spath, sizeof(req.spath));
725 strlcpy(req.relpath, relpath, sizeof(req.relpath));
726 strlcpy(req.addr, addr, sizeof(req.addr));
728 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
729 strlcpy(req.subject, t, sizeof(req.subject));
730 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
731 strlcpy(req.issuer, t, sizeof(req.issuer));
732 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
733 strlcpy(req.hash, t, sizeof(req.hash));
734 if ((t = tls_conn_version(c->ctx)) != NULL)
735 strlcpy(req.version, t, sizeof(req.version));
736 if ((t = tls_conn_cipher(c->ctx)) != NULL)
737 strlcpy(req.cipher, t, sizeof(req.cipher));
739 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
740 req.notbefore = tls_peer_cert_notbefore(c->ctx);
741 req.notafter = tls_peer_cert_notafter(c->ctx);
743 req.host_off = host_nth(c->host);
744 req.loc_off = c->loc;
746 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
747 imsg_flush(&exibuf);
749 close(c->pfd);
752 static void
753 open_dir(struct client *c)
755 size_t len;
756 int dirfd, root;
757 char *before_file;
759 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
761 len = strlen(c->iri.path);
762 if (len > 0 && !ends_with(c->iri.path, "/")) {
763 redirect_canonical_dir(c);
764 return;
767 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
768 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
769 if (!ends_with(c->sbuf, "/"))
770 strlcat(c->sbuf, "/", sizeof(c->sbuf));
771 before_file = strchr(c->sbuf, '\0');
772 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
773 sizeof(c->sbuf));
774 if (len >= sizeof(c->sbuf)) {
775 start_reply(c, TEMP_FAILURE, "internal server error");
776 return;
779 c->iri.path = c->sbuf;
781 /* close later unless we have to generate the dir listing */
782 dirfd = c->pfd;
783 c->pfd = -1;
785 switch (check_path(c, c->iri.path, &c->pfd)) {
786 case FILE_EXECUTABLE:
787 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
788 start_cgi(c->iri.path, "", c);
789 break;
792 /* fallthrough */
794 case FILE_EXISTS:
795 c->type = REQUEST_FILE;
796 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
797 break;
799 case FILE_DIRECTORY:
800 start_reply(c, TEMP_REDIRECT, c->sbuf);
801 break;
803 case FILE_MISSING:
804 *before_file = '\0';
806 if (!vhost_auto_index(c->host, c->iri.path)) {
807 start_reply(c, NOT_FOUND, "not found");
808 break;
811 c->type = REQUEST_DIR;
813 c->dirlen = scandir_fd(dirfd, &c->dir,
814 root ? select_non_dotdot : select_non_dot,
815 alphasort);
816 if (c->dirlen == -1) {
817 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
818 c->pfd, c->host->domain, c->iri.path, strerror(errno));
819 start_reply(c, TEMP_FAILURE, "internal server error");
820 return;
822 c->diroff = 0;
823 c->off = 0;
825 start_reply(c, SUCCESS, "text/gemini");
826 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
827 "# Index of %s\n\n", c->iri.path);
828 return;
830 default:
831 /* unreachable */
832 abort();
835 close(dirfd);
838 static void
839 redirect_canonical_dir(struct client *c)
841 size_t len;
843 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
844 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
845 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
847 if (len >= sizeof(c->sbuf)) {
848 start_reply(c, TEMP_FAILURE, "internal server error");
849 return;
852 start_reply(c, TEMP_REDIRECT, c->sbuf);
855 static void
856 client_tls_readcb(int fd, short event, void *d)
858 struct bufferevent *bufev = d;
859 struct client *client = bufev->cbarg;
860 ssize_t ret;
861 size_t len;
862 int what = EVBUFFER_READ;
863 int howmuch = IBUF_READ_SIZE;
864 char buf[IBUF_READ_SIZE];
866 if (event == EV_TIMEOUT) {
867 what |= EVBUFFER_TIMEOUT;
868 goto err;
871 if (bufev->wm_read.high != 0)
872 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
874 switch (ret = tls_read(client->ctx, buf, howmuch)) {
875 case TLS_WANT_POLLIN:
876 case TLS_WANT_POLLOUT:
877 goto retry;
878 case -1:
879 what |= EVBUFFER_ERROR;
880 goto err;
882 len = ret;
884 if (len == 0) {
885 what |= EVBUFFER_EOF;
886 goto err;
889 if (evbuffer_add(bufev->input, buf, len) == -1) {
890 what |= EVBUFFER_ERROR;
891 goto err;
894 event_add(&bufev->ev_read, NULL);
895 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
896 return;
897 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
898 /*
899 * here we could implement a read pressure policy.
900 */
903 if (bufev->readcb != NULL)
904 (*bufev->readcb)(bufev, bufev->cbarg);
906 return;
908 retry:
909 event_add(&bufev->ev_read, NULL);
910 return;
912 err:
913 (*bufev->errorcb)(bufev, what, bufev->cbarg);
916 static void
917 client_tls_writecb(int fd, short event, void *d)
919 struct bufferevent *bufev = d;
920 struct client *client = bufev->cbarg;
921 ssize_t ret;
922 size_t len;
923 short what = EVBUFFER_WRITE;
925 if (event == EV_TIMEOUT) {
926 what |= EVBUFFER_TIMEOUT;
927 goto err;
930 if (EVBUFFER_LENGTH(bufev->output) != 0) {
931 ret = tls_write(client->ctx,
932 EVBUFFER_DATA(bufev->output),
933 EVBUFFER_LENGTH(bufev->output));
934 switch (ret) {
935 case TLS_WANT_POLLIN:
936 case TLS_WANT_POLLOUT:
937 goto retry;
938 case -1:
939 what |= EVBUFFER_ERROR;
940 goto err;
942 len = ret;
943 evbuffer_drain(bufev->output, len);
946 if (EVBUFFER_LENGTH(bufev->output) != 0)
947 event_add(&bufev->ev_write, NULL);
949 if (bufev->writecb != NULL &&
950 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
951 (*bufev->writecb)(bufev, bufev->cbarg);
952 return;
954 retry:
955 event_add(&bufev->ev_write, NULL);
956 return;
957 err:
958 log_err(client, "tls error: %s", tls_error(client->ctx));
959 (*bufev->errorcb)(bufev, what, bufev->cbarg);
962 static void
963 client_read(struct bufferevent *bev, void *d)
965 struct client *c = d;
966 struct evbuffer *src = EVBUFFER_INPUT(bev);
967 const char *parse_err = "invalid request";
968 char decoded[DOMAIN_NAME_LEN];
969 size_t len;
971 bufferevent_disable(bev, EVBUFFER_READ);
973 /* max url len + \r\n */
974 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
975 log_err(c, "too much data received");
976 start_reply(c, BAD_REQUEST, "bad request");
977 return;
980 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
981 if (c->req == NULL) {
982 /* not enough data yet. */
983 bufferevent_enable(bev, EVBUFFER_READ);
984 return;
987 if (!parse_iri(c->req, &c->iri, &parse_err) ||
988 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
989 log_err(c, "IRI parse error: %s", parse_err);
990 start_reply(c, BAD_REQUEST, "bad request");
991 return;
994 if (apply_reverse_proxy(c))
995 return;
997 /* ignore the port number */
998 if (strcmp(c->iri.schema, "gemini") ||
999 strcmp(decoded, c->domain)) {
1000 start_reply(c, PROXY_REFUSED, "won't proxy request");
1001 return;
1004 if (apply_require_ca(c) ||
1005 apply_block_return(c)||
1006 apply_fastcgi(c))
1007 return;
1009 if (c->host->entrypoint != NULL) {
1010 c->loc = 0;
1011 start_cgi(c->host->entrypoint, c->iri.path, c);
1012 return;
1015 open_file(c);
1018 void
1019 client_write(struct bufferevent *bev, void *d)
1021 struct client *c = d;
1022 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1023 char buf[BUFSIZ];
1024 ssize_t r;
1026 switch (c->type) {
1027 case REQUEST_UNDECIDED:
1029 * Ignore spurious calls when we still don't have idea
1030 * what to do with the request.
1032 break;
1034 case REQUEST_FILE:
1035 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1036 log_warn(c, "read: %s", strerror(errno));
1037 client_error(bev, EVBUFFER_ERROR, c);
1038 return;
1039 } else if (r == 0) {
1040 client_close(c);
1041 return;
1042 } else if (r != sizeof(buf))
1043 c->type = REQUEST_DONE;
1044 bufferevent_write(bev, buf, r);
1045 break;
1047 case REQUEST_DIR:
1048 /* TODO: handle big big directories better */
1049 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1050 evbuffer_add_printf(out, "=> %s\n",
1051 c->dir[c->diroff]->d_name);
1052 free(c->dir[c->diroff]);
1054 free(c->dir);
1055 c->dir = NULL;
1057 c->type = REQUEST_DONE;
1059 event_add(&c->bev->ev_write, NULL);
1060 break;
1062 case REQUEST_CGI:
1063 case REQUEST_FCGI:
1064 case REQUEST_PROXY:
1066 * Here we depend on on the cgi script or fastcgi
1067 * connection to provide data.
1069 break;
1071 case REQUEST_DONE:
1072 if (EVBUFFER_LENGTH(out) == 0)
1073 client_close(c);
1074 break;
1078 static void
1079 client_error(struct bufferevent *bev, short error, void *d)
1081 struct client *c = d;
1083 c->type = REQUEST_DONE;
1085 if (error & EVBUFFER_TIMEOUT) {
1086 log_warn(c, "timeout reached, "
1087 "forcefully closing the connection");
1088 if (c->code == 0)
1089 start_reply(c, BAD_REQUEST, "timeout");
1090 else
1091 client_close(c);
1092 return;
1095 if (error & EVBUFFER_EOF) {
1096 client_close(c);
1097 return;
1100 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1101 client_close(c);
1104 void
1105 start_reply(struct client *c, int code, const char *meta)
1107 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1108 const char *lang;
1109 int r, rr;
1111 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1113 c->code = code;
1114 c->meta = meta;
1116 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1117 if (r == -1)
1118 goto err;
1120 /* 2 digit status + space + 1024 max reply */
1121 if (r > 1027)
1122 goto overflow;
1124 if (c->type != REQUEST_CGI &&
1125 c->type != REQUEST_FCGI &&
1126 c->type != REQUEST_PROXY &&
1127 !strcmp(meta, "text/gemini") &&
1128 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1129 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1130 if (rr == -1)
1131 goto err;
1132 if (r + rr > 1027)
1133 goto overflow;
1136 bufferevent_write(c->bev, "\r\n", 2);
1138 if (!vhost_disable_log(c->host, c->iri.path))
1139 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1141 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1142 c->type = REQUEST_DONE;
1144 return;
1146 err:
1147 log_err(c, "evbuffer_add_printf error: no memory");
1148 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1149 client_close(c);
1150 return;
1152 overflow:
1153 log_warn(c, "reply header overflow");
1154 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1155 start_reply(c, TEMP_FAILURE, "internal error");
1158 static void
1159 client_close_ev(int fd, short event, void *d)
1161 struct client *c = d;
1163 switch (tls_close(c->ctx)) {
1164 case TLS_WANT_POLLIN:
1165 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1166 break;
1167 case TLS_WANT_POLLOUT:
1168 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1169 break;
1172 connected_clients--;
1174 free(c->req);
1176 tls_free(c->ctx);
1177 c->ctx = NULL;
1179 free(c->header);
1181 if (c->pfd != -1)
1182 close(c->pfd);
1184 if (c->dir != NULL)
1185 free(c->dir);
1187 close(c->fd);
1188 c->fd = -1;
1191 static void
1192 client_proxy_close(int fd, short event, void *d)
1194 struct tls *ctx = d;
1196 if (ctx == NULL) {
1197 close(fd);
1198 return;
1201 switch (tls_close(ctx)) {
1202 case TLS_WANT_POLLIN:
1203 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1204 break;
1205 case TLS_WANT_POLLOUT:
1206 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1207 break;
1210 tls_free(ctx);
1211 close(fd);
1214 void
1215 client_close(struct client *c)
1218 * We may end up calling client_close in various situations
1219 * and for the most unexpected reasons. Therefore, we need to
1220 * ensure that everything is properly released once we reach
1221 * this point.
1224 SPLAY_REMOVE(client_tree_id, &clients, c);
1226 if (c->cgibev != NULL) {
1227 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1228 bufferevent_free(c->cgibev);
1229 c->cgibev = NULL;
1230 close(c->pfd);
1231 c->pfd = -1;
1234 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1235 bufferevent_free(c->bev);
1236 c->bev = NULL;
1238 if (c->proxybev != NULL) {
1239 if (event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL))
1240 event_del(&c->proxyev);
1242 if (c->pfd != -1) {
1243 client_proxy_close(c->pfd, 0, c->proxyctx);
1244 c->pfd = -1;
1247 bufferevent_free(c->proxybev);
1250 client_close_ev(c->fd, 0, c);
1253 static void
1254 cgi_read(struct bufferevent *bev, void *d)
1256 struct client *client = d;
1257 struct evbuffer *src = EVBUFFER_INPUT(bev);
1258 char *header;
1259 size_t len;
1260 int code;
1262 /* intercept the header */
1263 if (client->code == 0) {
1264 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1265 if (header == NULL) {
1266 /* max reply + \r\n */
1267 if (EVBUFFER_LENGTH(src) > 1029) {
1268 log_warn(client, "CGI script is trying to "
1269 "send a header too long.");
1270 cgi_error(bev, EVBUFFER_READ, client);
1273 /* wait a bit */
1274 return;
1277 if (len < 3 || len > 1029 ||
1278 !isdigit(header[0]) ||
1279 !isdigit(header[1]) ||
1280 !isspace(header[2])) {
1281 free(header);
1282 log_warn(client, "CGI script is trying to send a "
1283 "malformed header");
1284 cgi_error(bev, EVBUFFER_READ, client);
1285 return;
1288 client->header = header;
1289 code = (header[0] - '0') * 10 + (header[1] - '0');
1291 if (code < 10 || code >= 70) {
1292 log_warn(client, "CGI script is trying to send an "
1293 "invalid reply code (%d)", code);
1294 cgi_error(bev, EVBUFFER_READ, client);
1295 return;
1298 start_reply(client, code, header + 3);
1300 if (client->code < 20 || client->code > 29) {
1301 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1302 return;
1306 bufferevent_write_buffer(client->bev, src);
1309 static void
1310 cgi_write(struct bufferevent *bev, void *d)
1313 * Never called. We don't send data to a CGI script.
1315 abort();
1318 static void
1319 cgi_error(struct bufferevent *bev, short error, void *d)
1321 struct client *client = d;
1323 if (error & EVBUFFER_ERROR)
1324 log_err(client, "%s: evbuffer error (%x): %s",
1325 __func__, error, strerror(errno));
1327 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1328 bufferevent_free(bev);
1329 client->cgibev = NULL;
1331 close(client->pfd);
1332 client->pfd = -1;
1334 client->type = REQUEST_DONE;
1335 if (client->code != 0)
1336 client_write(client->bev, client);
1337 else
1338 start_reply(client, CGI_ERROR, "CGI error");
1341 static void
1342 do_accept(int sock, short et, void *d)
1344 struct client *c;
1345 struct sockaddr_storage addr;
1346 struct sockaddr *saddr;
1347 socklen_t len;
1348 int fd;
1350 saddr = (struct sockaddr*)&addr;
1351 len = sizeof(addr);
1352 if ((fd = accept(sock, saddr, &len)) == -1) {
1353 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1354 errno == ECONNABORTED)
1355 return;
1356 fatal("accept: %s", strerror(errno));
1359 mark_nonblock(fd);
1361 c = xcalloc(1, sizeof(*c));
1362 c->id = ++server_client_id;
1363 c->fd = fd;
1364 c->pfd = -1;
1365 c->addr = addr;
1367 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1368 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1369 close(c->fd);
1370 free(c);
1371 return;
1374 SPLAY_INSERT(client_tree_id, &clients, c);
1375 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1376 connected_clients++;
1379 static struct client *
1380 client_by_id(int id)
1382 struct client *c;
1384 if ((c = try_client_by_id(id)) == NULL)
1385 fatal("in client_by_id: invalid id %d", id);
1386 return c;
1389 struct client *
1390 try_client_by_id(int id)
1392 struct client find;
1394 find.id = id;
1395 return SPLAY_FIND(client_tree_id, &clients, &find);
1398 static void
1399 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1401 struct client *c;
1403 c = client_by_id(imsg->hdr.peerid);
1405 if ((c->pfd = imsg->fd) == -1) {
1406 start_reply(c, TEMP_FAILURE, "internal server error");
1407 return;
1410 c->type = REQUEST_CGI;
1412 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1413 cgi_error, c);
1415 bufferevent_enable(c->cgibev, EV_READ);
1418 static void
1419 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1421 struct client *c;
1422 int id;
1424 id = imsg->hdr.peerid;
1426 if ((c = try_client_by_id(id)) == NULL) {
1427 if (imsg->fd != -1)
1428 close(imsg->fd);
1429 return;
1432 if ((c->pfd = imsg->fd) == -1) {
1433 start_reply(c, CGI_ERROR, "CGI error");
1434 return;
1437 mark_nonblock(c->pfd);
1439 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1440 fcgi_error, c);
1441 if (c->cgibev == NULL) {
1442 start_reply(c, TEMP_FAILURE, "internal server error");
1443 return;
1446 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1447 fcgi_req(c);
1450 static void
1451 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1453 struct client *c;
1454 int id;
1456 id = imsg->hdr.peerid;
1457 if ((c = try_client_by_id(id)) == NULL) {
1458 if (imsg->fd != -1)
1459 close(imsg->fd);
1460 return;
1463 if ((c->pfd = imsg->fd) == -1) {
1464 start_reply(c, PROXY_ERROR, "proxy error");
1465 return;
1468 mark_nonblock(c->pfd);
1470 if (proxy_init(c) == -1)
1471 start_reply(c, PROXY_ERROR, "proxy error");
1474 static void
1475 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1478 * don't call event_loopbreak since we want to finish to
1479 * handle the ongoing connections.
1482 shutting_down = 1;
1484 event_del(&e4);
1485 if (has_ipv6)
1486 event_del(&e6);
1487 if (has_siginfo)
1488 signal_del(&siginfo);
1489 event_del(&imsgev);
1490 signal_del(&sigusr2);
1493 static void
1494 handle_dispatch_imsg(int fd, short ev, void *d)
1496 struct imsgbuf *ibuf = d;
1497 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1500 static void
1501 handle_siginfo(int fd, short ev, void *d)
1503 log_info(NULL, "%d connected clients", connected_clients);
1506 void
1507 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1509 ctx = ctx_;
1511 SPLAY_INIT(&clients);
1513 event_init();
1515 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1516 event_add(&e4, NULL);
1518 if (sock6 != -1) {
1519 has_ipv6 = 1;
1520 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1521 event_add(&e6, NULL);
1524 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1525 event_add(&imsgev, NULL);
1527 #ifdef SIGINFO
1528 has_siginfo = 1;
1529 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1530 signal_add(&siginfo, NULL);
1531 #endif
1532 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1533 signal_add(&sigusr2, NULL);
1535 sandbox_server_process();
1536 event_dispatch();
1537 _exit(0);
1540 int
1541 client_tree_cmp(struct client *a, struct client *b)
1543 if (a->id == b->id)
1544 return 0;
1545 else if (a->id < b->id)
1546 return -1;
1547 else
1548 return +1;
1551 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)