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 struct client clients[MAX_USERS];
36 static struct tls *ctx;
38 static struct event e4, e6, imsgev, siginfo, sigusr2;
39 static int has_ipv6, has_siginfo;
41 int connected_clients;
43 static inline int matches(const char*, const char*);
45 static int check_path(struct client*, const char*, int*);
46 static void open_file(struct client*);
47 static void check_for_cgi(struct client*);
48 static void handle_handshake(int, short, void*);
49 static const char *strip_path(const char*, int);
50 static void fmt_sbuf(const char*, struct client*, const char*);
51 static int apply_block_return(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*);
73 static struct client *client_by_id(int);
75 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
76 static void handle_imsg_fcgi_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 };
87 static inline int
88 matches(const char *pattern, const char *path)
89 {
90 if (*path == '/')
91 path++;
92 return !fnmatch(pattern, path, 0);
93 }
95 const char *
96 vhost_lang(struct vhost *v, const char *path)
97 {
98 struct location *loc;
100 if (v == NULL || path == NULL)
101 return NULL;
103 loc = TAILQ_FIRST(&v->locations);
104 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
105 if (loc->lang != NULL) {
106 if (matches(loc->match, path))
107 return loc->lang;
111 return TAILQ_FIRST(&v->locations)->lang;
114 const char *
115 vhost_default_mime(struct vhost *v, const char *path)
117 struct location *loc;
118 const char *default_mime = "application/octet-stream";
120 if (v == NULL || path == NULL)
121 return default_mime;
123 loc = TAILQ_FIRST(&v->locations);
124 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
125 if (loc->default_mime != NULL) {
126 if (matches(loc->match, path))
127 return loc->default_mime;
131 loc = TAILQ_FIRST(&v->locations);
132 if (loc->default_mime != NULL)
133 return loc->default_mime;
134 return default_mime;
137 const char *
138 vhost_index(struct vhost *v, const char *path)
140 struct location *loc;
141 const char *index = "index.gmi";
143 if (v == NULL || path == NULL)
144 return index;
146 loc = TAILQ_FIRST(&v->locations);
147 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
148 if (loc->index != NULL) {
149 if (matches(loc->match, path))
150 return loc->index;
154 loc = TAILQ_FIRST(&v->locations);
155 if (loc->index != NULL)
156 return loc->index;
157 return index;
160 int
161 vhost_auto_index(struct vhost *v, const char *path)
163 struct location *loc;
165 if (v == NULL || path == NULL)
166 return 0;
168 loc = TAILQ_FIRST(&v->locations);
169 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
170 if (loc->auto_index != 0) {
171 if (matches(loc->match, path))
172 return loc->auto_index == 1;
176 loc = TAILQ_FIRST(&v->locations);
177 return loc->auto_index == 1;
180 int
181 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
183 struct location *loc;
185 if (v == NULL || path == NULL)
186 return 0;
188 loc = TAILQ_FIRST(&v->locations);
189 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
190 if (loc->block_code != 0) {
191 if (matches(loc->match, path)) {
192 *code = loc->block_code;
193 *fmt = loc->block_fmt;
194 return 1;
199 loc = TAILQ_FIRST(&v->locations);
200 *code = loc->block_code;
201 *fmt = loc->block_fmt;
202 return loc->block_code != 0;
205 int
206 vhost_fastcgi(struct vhost *v, const char *path)
208 struct location *loc;
210 if (v == NULL || path == NULL)
211 return -1;
213 loc = TAILQ_FIRST(&v->locations);
214 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
215 if (loc->fcgi != -1)
216 if (matches(loc->match, path))
217 return loc->fcgi;
220 loc = TAILQ_FIRST(&v->locations);
221 return loc->fcgi;
224 int
225 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
227 struct location *loc;
228 size_t l = 0;
230 if (v == NULL || path == NULL)
231 return -1;
233 loc = TAILQ_FIRST(&v->locations);
234 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
235 l++;
236 if (loc->dirfd != -1)
237 if (matches(loc->match, path)) {
238 *retloc = l;
239 return loc->dirfd;
243 *retloc = 0;
244 loc = TAILQ_FIRST(&v->locations);
245 return loc->dirfd;
248 int
249 vhost_strip(struct vhost *v, const char *path)
251 struct location *loc;
253 if (v == NULL || path == NULL)
254 return 0;
256 loc = TAILQ_FIRST(&v->locations);
257 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
258 if (loc->strip != 0) {
259 if (matches(loc->match, path))
260 return loc->strip;
264 loc = TAILQ_FIRST(&v->locations);
265 return loc->strip;
268 X509_STORE *
269 vhost_require_ca(struct vhost *v, const char *path)
271 struct location *loc;
273 if (v == NULL || path == NULL)
274 return NULL;
276 loc = TAILQ_FIRST(&v->locations);
277 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
278 if (loc->reqca != NULL) {
279 if (matches(loc->match, path))
280 return loc->reqca;
284 loc = TAILQ_FIRST(&v->locations);
285 return loc->reqca;
288 int
289 vhost_disable_log(struct vhost *v, const char *path)
291 struct location *loc;
293 if (v == NULL || path == NULL)
294 return 0;
296 loc = TAILQ_FIRST(&v->locations);
297 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
298 if (loc->disable_log && matches(loc->match, path))
299 return 1;
302 loc = TAILQ_FIRST(&v->locations);
303 return loc->disable_log;
306 static int
307 check_path(struct client *c, const char *path, int *fd)
309 struct stat sb;
310 const char *p;
311 int dirfd, strip;
313 assert(path != NULL);
315 /*
316 * in send_dir we add an initial / (to be redirect-friendly),
317 * but here we want to skip it
318 */
319 if (*path == '/')
320 path++;
322 strip = vhost_strip(c->host, path);
323 p = strip_path(path, strip);
325 if (*p == '/')
326 p = p+1;
327 if (*p == '\0')
328 p = ".";
330 dirfd = vhost_dirfd(c->host, path, &c->loc);
331 log_debug(c, "check_path: strip=%d path=%s original=%s",
332 strip, p, path);
333 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
334 return FILE_MISSING;
336 if (fstat(*fd, &sb) == -1) {
337 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
338 return FILE_MISSING;
341 if (S_ISDIR(sb.st_mode))
342 return FILE_DIRECTORY;
344 if (sb.st_mode & S_IXUSR)
345 return FILE_EXECUTABLE;
347 return FILE_EXISTS;
350 static void
351 open_file(struct client *c)
353 switch (check_path(c, c->iri.path, &c->pfd)) {
354 case FILE_EXECUTABLE:
355 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
356 start_cgi(c->iri.path, "", c);
357 return;
360 /* fallthrough */
362 case FILE_EXISTS:
363 c->type = REQUEST_FILE;
364 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
365 return;
367 case FILE_DIRECTORY:
368 open_dir(c);
369 return;
371 case FILE_MISSING:
372 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
373 check_for_cgi(c);
374 return;
376 start_reply(c, NOT_FOUND, "not found");
377 return;
379 default:
380 /* unreachable */
381 abort();
385 /*
386 * the inverse of this algorithm, i.e. starting from the start of the
387 * path + strlen(cgi), and checking if each component, should be
388 * faster. But it's tedious to write. This does the opposite: starts
389 * from the end and strip one component at a time, until either an
390 * executable is found or we emptied the path.
391 */
392 static void
393 check_for_cgi(struct client *c)
395 char path[PATH_MAX];
396 char *end;
398 strlcpy(path, c->iri.path, sizeof(path));
399 end = strchr(path, '\0');
401 while (end > path) {
402 /*
403 * go up one level. UNIX paths are simple and POSIX
404 * dirname, with its ambiguities on if the given
405 * pointer is changed or not, gives me headaches.
406 */
407 while (*end != '/' && end > path)
408 end--;
410 if (end == path)
411 break;
413 *end = '\0';
415 switch (check_path(c, path, &c->pfd)) {
416 case FILE_EXECUTABLE:
417 start_cgi(path, end+1, c);
418 return;
419 case FILE_MISSING:
420 break;
421 default:
422 goto err;
425 *end = '/';
426 end--;
429 err:
430 start_reply(c, NOT_FOUND, "not found");
431 return;
434 void
435 mark_nonblock(int fd)
437 int flags;
439 if ((flags = fcntl(fd, F_GETFL)) == -1)
440 fatal("fcntl(F_GETFL): %s", strerror(errno));
441 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
442 fatal("fcntl(F_SETFL): %s", strerror(errno));
445 static void
446 handle_handshake(int fd, short ev, void *d)
448 struct client *c = d;
449 struct vhost *h;
450 struct alist *a;
451 const char *servname;
452 const char *parse_err = "unknown error";
454 switch (tls_handshake(c->ctx)) {
455 case 0: /* success */
456 case -1: /* already handshaked */
457 break;
458 case TLS_WANT_POLLIN:
459 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
460 return;
461 case TLS_WANT_POLLOUT:
462 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
463 return;
464 default:
465 /* unreachable */
466 abort();
469 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
470 log_debug(c, "handshake: missing SNI");
471 goto err;
474 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
475 log_info(c, "puny_decode: %s", parse_err);
476 goto err;
479 TAILQ_FOREACH(h, &hosts, vhosts) {
480 if (matches(h->domain, c->domain))
481 goto found;
482 TAILQ_FOREACH(a, &h->aliases, aliases) {
483 if (matches(a->alias, c->domain))
484 goto found;
488 found:
489 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
490 servname != NULL ? servname : "(null)",
491 c->domain,
492 h != NULL ? h->domain : "(null)");
494 if (h != NULL) {
495 c->host = h;
497 c->bev = bufferevent_new(fd, client_read, client_write,
498 client_error, c);
499 if (c->bev == NULL)
500 fatal("%s: failed to allocate client buffer: %s",
501 __func__, strerror(errno));
503 event_set(&c->bev->ev_read, c->fd, EV_READ,
504 client_tls_readcb, c->bev);
505 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
506 client_tls_writecb, c->bev);
508 #if HAVE_LIBEVENT2
509 evbuffer_unfreeze(c->bev->input, 0);
510 evbuffer_unfreeze(c->bev->output, 1);
511 #endif
513 bufferevent_enable(c->bev, EV_READ);
515 return;
518 err:
519 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
522 static const char *
523 strip_path(const char *path, int strip)
525 char *t;
527 while (strip > 0) {
528 if ((t = strchr(path, '/')) == NULL) {
529 path = strchr(path, '\0');
530 break;
532 path = t;
533 strip--;
536 return path;
539 static void
540 fmt_sbuf(const char *fmt, struct client *c, const char *path)
542 size_t i;
543 char buf[32];
545 memset(buf, 0, sizeof(buf));
546 for (i = 0; *fmt; ++fmt) {
547 if (i == sizeof(buf)-1 || *fmt == '%') {
548 strlcat(c->sbuf, buf, sizeof(c->sbuf));
549 memset(buf, 0, sizeof(buf));
550 i = 0;
553 if (*fmt != '%') {
554 buf[i++] = *fmt;
555 continue;
558 switch (*++fmt) {
559 case '%':
560 strlcat(c->sbuf, "%", sizeof(c->sbuf));
561 break;
562 case 'p':
563 if (*path != '/')
564 strlcat(c->sbuf, "/", sizeof(c->sbuf));
565 strlcat(c->sbuf, path, sizeof(c->sbuf));
566 break;
567 case 'q':
568 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
569 break;
570 case 'P':
571 snprintf(buf, sizeof(buf), "%d", conf.port);
572 strlcat(c->sbuf, buf, sizeof(c->sbuf));
573 memset(buf, 0, sizeof(buf));
574 break;
575 case 'N':
576 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
577 break;
578 default:
579 fatal("%s: unknown fmt specifier %c",
580 __func__, *fmt);
584 if (i != 0)
585 strlcat(c->sbuf, buf, sizeof(c->sbuf));
588 /* 1 if a matching `block return' (and apply it), 0 otherwise */
589 static int
590 apply_block_return(struct client *c)
592 const char *fmt, *path;
593 int code;
595 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
596 return 0;
598 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
599 fmt_sbuf(fmt, c, path);
601 start_reply(c, code, c->sbuf);
602 return 1;
605 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
606 static int
607 apply_fastcgi(struct client *c)
609 int id;
610 struct fcgi *f;
612 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
613 return 0;
615 switch ((f = &fcgi[id])->s) {
616 case FCGI_OFF:
617 f->s = FCGI_INFLIGHT;
618 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
619 f->path, f->port, f->prog);
620 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
621 &id, sizeof(id));
622 imsg_flush(&exibuf);
623 /* fallthrough */
624 case FCGI_INFLIGHT:
625 c->fcgi = id;
626 break;
627 case FCGI_READY:
628 c->fcgi = id;
629 fcgi_req(f, c);
630 break;
633 return 1;
636 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
637 static int
638 apply_require_ca(struct client *c)
640 X509_STORE *store;
641 const uint8_t *cert;
642 size_t len;
644 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
645 return 0;
647 if (!tls_peer_cert_provided(c->ctx)) {
648 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
649 return 1;
652 cert = tls_peer_cert_chain_pem(c->ctx, &len);
653 if (!validate_against_ca(store, cert, len)) {
654 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
655 return 1;
658 return 0;
661 static size_t
662 host_nth(struct vhost *h)
664 struct vhost *v;
665 size_t i = 0;
667 TAILQ_FOREACH(v, &hosts, vhosts) {
668 if (v == h)
669 return i;
670 i++;
673 abort();
676 static void
677 start_cgi(const char *spath, const char *relpath, struct client *c)
679 char addr[NI_MAXHOST];
680 const char *t;
681 struct cgireq req;
682 int e;
684 c->type = REQUEST_CGI;
686 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
687 addr, sizeof(addr),
688 NULL, 0,
689 NI_NUMERICHOST);
690 if (e != 0)
691 fatal("getnameinfo failed");
693 memset(&req, 0, sizeof(req));
695 memcpy(req.buf, c->req, sizeof(req.buf));
697 req.iri_schema_off = c->iri.schema - c->req;
698 req.iri_host_off = c->iri.host - c->req;
699 req.iri_port_off = c->iri.port - c->req;
700 req.iri_path_off = c->iri.path - c->req;
701 req.iri_query_off = c->iri.query - c->req;
702 req.iri_fragment_off = c->iri.fragment - c->req;
704 req.iri_portno = c->iri.port_no;
706 strlcpy(req.spath, spath, sizeof(req.spath));
707 strlcpy(req.relpath, relpath, sizeof(req.relpath));
708 strlcpy(req.addr, addr, sizeof(req.addr));
710 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
711 strlcpy(req.subject, t, sizeof(req.subject));
712 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
713 strlcpy(req.issuer, t, sizeof(req.issuer));
714 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
715 strlcpy(req.hash, t, sizeof(req.hash));
716 if ((t = tls_conn_version(c->ctx)) != NULL)
717 strlcpy(req.version, t, sizeof(req.version));
718 if ((t = tls_conn_cipher(c->ctx)) != NULL)
719 strlcpy(req.cipher, t, sizeof(req.cipher));
721 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
722 req.notbefore = tls_peer_cert_notbefore(c->ctx);
723 req.notafter = tls_peer_cert_notafter(c->ctx);
725 req.host_off = host_nth(c->host);
726 req.loc_off = c->loc;
728 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
729 imsg_flush(&exibuf);
731 close(c->pfd);
734 static void
735 open_dir(struct client *c)
737 size_t len;
738 int dirfd, root;
739 char *before_file;
741 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
743 len = strlen(c->iri.path);
744 if (len > 0 && !ends_with(c->iri.path, "/")) {
745 redirect_canonical_dir(c);
746 return;
749 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
750 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
751 if (!ends_with(c->sbuf, "/"))
752 strlcat(c->sbuf, "/", sizeof(c->sbuf));
753 before_file = strchr(c->sbuf, '\0');
754 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
755 sizeof(c->sbuf));
756 if (len >= sizeof(c->sbuf)) {
757 start_reply(c, TEMP_FAILURE, "internal server error");
758 return;
761 c->iri.path = c->sbuf;
763 /* close later unless we have to generate the dir listing */
764 dirfd = c->pfd;
765 c->pfd = -1;
767 switch (check_path(c, c->iri.path, &c->pfd)) {
768 case FILE_EXECUTABLE:
769 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
770 start_cgi(c->iri.path, "", c);
771 break;
774 /* fallthrough */
776 case FILE_EXISTS:
777 c->type = REQUEST_FILE;
778 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
779 break;
781 case FILE_DIRECTORY:
782 start_reply(c, TEMP_REDIRECT, c->sbuf);
783 break;
785 case FILE_MISSING:
786 *before_file = '\0';
788 if (!vhost_auto_index(c->host, c->iri.path)) {
789 start_reply(c, NOT_FOUND, "not found");
790 break;
793 c->type = REQUEST_DIR;
795 c->dirlen = scandir_fd(dirfd, &c->dir,
796 root ? select_non_dotdot : select_non_dot,
797 alphasort);
798 if (c->dirlen == -1) {
799 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
800 c->pfd, c->host->domain, c->iri.path, strerror(errno));
801 start_reply(c, TEMP_FAILURE, "internal server error");
802 return;
804 c->diroff = 0;
805 c->off = 0;
807 start_reply(c, SUCCESS, "text/gemini");
808 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
809 "# Index of %s\n\n", c->iri.path);
810 return;
812 default:
813 /* unreachable */
814 abort();
817 close(dirfd);
820 static void
821 redirect_canonical_dir(struct client *c)
823 size_t len;
825 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
826 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
827 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
829 if (len >= sizeof(c->sbuf)) {
830 start_reply(c, TEMP_FAILURE, "internal server error");
831 return;
834 start_reply(c, TEMP_REDIRECT, c->sbuf);
837 static void
838 client_tls_readcb(int fd, short event, void *d)
840 struct bufferevent *bufev = d;
841 struct client *client = bufev->cbarg;
842 ssize_t ret;
843 size_t len;
844 int what = EVBUFFER_READ;
845 int howmuch = IBUF_READ_SIZE;
846 char buf[IBUF_READ_SIZE];
848 if (event == EV_TIMEOUT) {
849 what |= EVBUFFER_TIMEOUT;
850 goto err;
853 if (bufev->wm_read.high != 0)
854 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
856 switch (ret = tls_read(client->ctx, buf, howmuch)) {
857 case TLS_WANT_POLLIN:
858 case TLS_WANT_POLLOUT:
859 goto retry;
860 case -1:
861 what |= EVBUFFER_ERROR;
862 goto err;
864 len = ret;
866 if (len == 0) {
867 what |= EVBUFFER_EOF;
868 goto err;
871 if (evbuffer_add(bufev->input, buf, len) == -1) {
872 what |= EVBUFFER_ERROR;
873 goto err;
876 event_add(&bufev->ev_read, NULL);
877 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
878 return;
879 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
880 /*
881 * here we could implement a read pressure policy.
882 */
885 if (bufev->readcb != NULL)
886 (*bufev->readcb)(bufev, bufev->cbarg);
888 return;
890 retry:
891 event_add(&bufev->ev_read, NULL);
892 return;
894 err:
895 (*bufev->errorcb)(bufev, what, bufev->cbarg);
898 static void
899 client_tls_writecb(int fd, short event, void *d)
901 struct bufferevent *bufev = d;
902 struct client *client = bufev->cbarg;
903 ssize_t ret;
904 size_t len;
905 short what = EVBUFFER_WRITE;
907 if (event == EV_TIMEOUT) {
908 what |= EVBUFFER_TIMEOUT;
909 goto err;
912 if (EVBUFFER_LENGTH(bufev->output) != 0) {
913 ret = tls_write(client->ctx,
914 EVBUFFER_DATA(bufev->output),
915 EVBUFFER_LENGTH(bufev->output));
916 switch (ret) {
917 case TLS_WANT_POLLIN:
918 case TLS_WANT_POLLOUT:
919 goto retry;
920 case -1:
921 what |= EVBUFFER_ERROR;
922 goto err;
924 len = ret;
925 evbuffer_drain(bufev->output, len);
928 if (EVBUFFER_LENGTH(bufev->output) != 0)
929 event_add(&bufev->ev_write, NULL);
931 if (bufev->writecb != NULL &&
932 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
933 (*bufev->writecb)(bufev, bufev->cbarg);
934 return;
936 retry:
937 event_add(&bufev->ev_write, NULL);
938 return;
939 err:
940 log_err(client, "tls error: %s", tls_error(client->ctx));
941 (*bufev->errorcb)(bufev, what, bufev->cbarg);
944 static void
945 client_read(struct bufferevent *bev, void *d)
947 struct client *c = d;
948 struct evbuffer *src = EVBUFFER_INPUT(bev);
949 const char *parse_err = "invalid request";
950 char decoded[DOMAIN_NAME_LEN];
951 size_t len;
953 bufferevent_disable(bev, EVBUFFER_READ);
955 /* max url len + \r\n */
956 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
957 log_err(c, "too much data received");
958 start_reply(c, BAD_REQUEST, "bad request");
959 return;
962 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
963 if (c->req == NULL) {
964 /* not enough data yet. */
965 bufferevent_enable(bev, EVBUFFER_READ);
966 return;
969 if (!parse_iri(c->req, &c->iri, &parse_err) ||
970 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
971 log_err(c, "IRI parse error: %s", parse_err);
972 start_reply(c, BAD_REQUEST, "bad request");
973 return;
976 if (c->iri.port_no != conf.port ||
977 strcmp(c->iri.schema, "gemini") ||
978 strcmp(decoded, c->domain)) {
979 start_reply(c, PROXY_REFUSED, "won't proxy request");
980 return;
983 if (apply_require_ca(c) ||
984 apply_block_return(c)||
985 apply_fastcgi(c))
986 return;
988 if (c->host->entrypoint != NULL) {
989 c->loc = 0;
990 start_cgi(c->host->entrypoint, c->iri.path, c);
991 return;
994 open_file(c);
997 void
998 client_write(struct bufferevent *bev, void *d)
1000 struct client *c = d;
1001 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1002 char buf[BUFSIZ];
1003 ssize_t r;
1005 switch (c->type) {
1006 case REQUEST_UNDECIDED:
1008 * Ignore spurious calls when we still don't have idea
1009 * what to do with the request.
1011 break;
1013 case REQUEST_FILE:
1014 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1015 log_warn(c, "read: %s", strerror(errno));
1016 client_error(bev, EVBUFFER_ERROR, c);
1017 return;
1018 } else if (r == 0) {
1019 client_close(c);
1020 return;
1021 } else if (r != sizeof(buf))
1022 c->type = REQUEST_DONE;
1023 bufferevent_write(bev, buf, r);
1024 break;
1026 case REQUEST_DIR:
1027 /* TODO: handle big big directories better */
1028 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1029 evbuffer_add_printf(out, "=> %s\n",
1030 c->dir[c->diroff]->d_name);
1031 free(c->dir[c->diroff]);
1033 free(c->dir);
1034 c->dir = NULL;
1036 c->type = REQUEST_DONE;
1038 event_add(&c->bev->ev_write, NULL);
1039 break;
1041 case REQUEST_CGI:
1042 case REQUEST_FCGI:
1044 * Here we depend on on the cgi script or fastcgi
1045 * connection to provide data.
1047 break;
1049 case REQUEST_DONE:
1050 if (EVBUFFER_LENGTH(out) == 0)
1051 client_close(c);
1052 break;
1056 static void
1057 client_error(struct bufferevent *bev, short error, void *d)
1059 struct client *c = d;
1061 if (c->type == REQUEST_FCGI)
1062 fcgi_abort_request(c);
1064 c->type = REQUEST_DONE;
1066 if (error & EVBUFFER_TIMEOUT) {
1067 log_warn(c, "timeout reached, "
1068 "forcefully closing the connection");
1069 if (c->code == 0)
1070 start_reply(c, BAD_REQUEST, "timeout");
1071 else
1072 client_close(c);
1073 return;
1076 if (error & EVBUFFER_EOF) {
1077 client_close(c);
1078 return;
1081 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1082 client_close(c);
1085 void
1086 start_reply(struct client *c, int code, const char *meta)
1088 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1089 const char *lang;
1090 int r, rr;
1092 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1094 c->code = code;
1095 c->meta = meta;
1097 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1098 if (r == -1)
1099 goto err;
1101 /* 2 digit status + space + 1024 max reply */
1102 if (r > 1027)
1103 goto overflow;
1105 if (c->type != REQUEST_CGI &&
1106 c->type != REQUEST_FCGI &&
1107 !strcmp(meta, "text/gemini") &&
1108 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1109 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1110 if (rr == -1)
1111 goto err;
1112 if (r + rr > 1027)
1113 goto overflow;
1116 bufferevent_write(c->bev, "\r\n", 2);
1118 if (!vhost_disable_log(c->host, c->iri.path))
1119 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1121 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1122 c->type = REQUEST_DONE;
1124 return;
1126 err:
1127 log_err(c, "evbuffer_add_printf error: no memory");
1128 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1129 client_close(c);
1130 return;
1132 overflow:
1133 log_warn(c, "reply header overflow");
1134 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1135 start_reply(c, TEMP_FAILURE, "internal error");
1138 static void
1139 client_close_ev(int fd, short event, void *d)
1141 struct client *c = d;
1143 switch (tls_close(c->ctx)) {
1144 case TLS_WANT_POLLIN:
1145 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1146 break;
1147 case TLS_WANT_POLLOUT:
1148 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1149 break;
1152 connected_clients--;
1154 tls_free(c->ctx);
1155 c->ctx = NULL;
1157 free(c->header);
1159 if (c->pfd != -1)
1160 close(c->pfd);
1162 if (c->dir != NULL)
1163 free(c->dir);
1165 close(c->fd);
1166 c->fd = -1;
1169 void
1170 client_close(struct client *c)
1173 * We may end up calling client_close in various situations
1174 * and for the most unexpected reasons. Therefore, we need to
1175 * ensure that everything is properly released once we reach
1176 * this point.
1179 if (c->type == REQUEST_FCGI)
1180 fcgi_abort_request(c);
1182 if (c->cgibev != NULL) {
1183 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1184 bufferevent_free(c->cgibev);
1185 c->cgibev = NULL;
1186 close(c->pfd);
1187 c->pfd = -1;
1190 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1191 bufferevent_free(c->bev);
1192 c->bev = NULL;
1194 client_close_ev(c->fd, 0, c);
1197 static void
1198 cgi_read(struct bufferevent *bev, void *d)
1200 struct client *client = d;
1201 struct evbuffer *src = EVBUFFER_INPUT(bev);
1202 char *header;
1203 size_t len;
1204 int code;
1206 /* intercept the header */
1207 if (client->code == 0) {
1208 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1209 if (header == NULL) {
1210 /* max reply + \r\n */
1211 if (EVBUFFER_LENGTH(src) > 1026) {
1212 log_warn(client, "CGI script is trying to "
1213 "send a header too long.");
1214 cgi_error(bev, EVBUFFER_READ, client);
1217 /* wait a bit */
1218 return;
1221 if (len < 3 || len > 1029 ||
1222 !isdigit(header[0]) ||
1223 !isdigit(header[1]) ||
1224 !isspace(header[2])) {
1225 free(header);
1226 log_warn(client, "CGI script is trying to send a "
1227 "malformed header");
1228 cgi_error(bev, EVBUFFER_READ, client);
1229 return;
1232 client->header = header;
1233 code = (header[0] - '0') * 10 + (header[1] - '0');
1235 if (code < 10 || code >= 70) {
1236 log_warn(client, "CGI script is trying to send an "
1237 "invalid reply code (%d)", code);
1238 cgi_error(bev, EVBUFFER_READ, client);
1239 return;
1242 start_reply(client, code, header + 3);
1244 if (client->code < 20 || client->code > 29) {
1245 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1246 return;
1250 bufferevent_write_buffer(client->bev, src);
1253 static void
1254 cgi_write(struct bufferevent *bev, void *d)
1257 * Never called. We don't send data to a CGI script.
1259 abort();
1262 static void
1263 cgi_error(struct bufferevent *bev, short error, void *d)
1265 struct client *client = d;
1267 if (error & EVBUFFER_ERROR)
1268 log_err(client, "%s: evbuffer error (%x): %s",
1269 __func__, error, strerror(errno));
1271 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1272 bufferevent_free(bev);
1273 client->cgibev = NULL;
1275 close(client->pfd);
1276 client->pfd = -1;
1278 client->type = REQUEST_DONE;
1279 if (client->code != 0)
1280 client_write(client->bev, client);
1281 else
1282 start_reply(client, CGI_ERROR, "CGI error");
1285 static void
1286 do_accept(int sock, short et, void *d)
1288 struct client *c;
1289 struct sockaddr_storage addr;
1290 struct sockaddr *saddr;
1291 socklen_t len;
1292 int i, fd;
1294 (void)et;
1296 saddr = (struct sockaddr*)&addr;
1297 len = sizeof(addr);
1298 if ((fd = accept(sock, saddr, &len)) == -1) {
1299 if (errno == EWOULDBLOCK || errno == EAGAIN)
1300 return;
1301 fatal("accept: %s", strerror(errno));
1304 mark_nonblock(fd);
1306 for (i = 0; i < MAX_USERS; ++i) {
1307 c = &clients[i];
1308 if (c->fd == -1) {
1309 memset(c, 0, sizeof(*c));
1310 c->id = i;
1311 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1312 break; /* goodbye fd! */
1314 c->fd = fd;
1315 c->pfd = -1;
1316 c->dir = NULL;
1317 c->addr = addr;
1318 c->fcgi = -1;
1320 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake,
1321 c, NULL);
1323 connected_clients++;
1324 return;
1328 close(fd);
1331 static struct client *
1332 client_by_id(int id)
1334 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1335 fatal("in client_by_id: invalid id %d", id);
1336 return &clients[id];
1339 struct client *
1340 try_client_by_id(int id)
1342 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1343 return NULL;
1344 return &clients[id];
1347 static void
1348 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1350 struct client *c;
1352 c = client_by_id(imsg->hdr.peerid);
1354 if ((c->pfd = imsg->fd) == -1) {
1355 start_reply(c, TEMP_FAILURE, "internal server error");
1356 return;
1359 c->type = REQUEST_CGI;
1361 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1362 cgi_error, c);
1364 bufferevent_enable(c->cgibev, EV_READ);
1367 static void
1368 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1370 struct client *c;
1371 struct fcgi *f;
1372 int i, id;
1374 id = imsg->hdr.peerid;
1375 f = &fcgi[id];
1377 if ((f->fd = imsg->fd) == -1)
1378 f->s = FCGI_OFF;
1379 else {
1380 mark_nonblock(f->fd);
1382 f->s = FCGI_READY;
1384 f->bev = bufferevent_new(f->fd, fcgi_read, fcgi_write,
1385 fcgi_error, f);
1386 if (f->bev == NULL) {
1387 close(f->fd);
1388 log_err(NULL, "%s: failed to allocate client buffer",
1389 __func__);
1390 f->s = FCGI_OFF;
1393 bufferevent_enable(f->bev, EV_READ|EV_WRITE);
1396 for (i = 0; i < MAX_USERS; ++i) {
1397 c = &clients[i];
1398 if (c->fd == -1)
1399 continue;
1400 if (c->fcgi != id)
1401 continue;
1403 if (f->s == FCGI_OFF) {
1404 c->fcgi = -1;
1405 start_reply(c, TEMP_FAILURE, "internal server error");
1406 } else
1407 fcgi_req(f, c);
1411 static void
1412 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1414 size_t i;
1416 (void)imsg;
1417 (void)len;
1420 * don't call event_loopbreak since we want to finish to
1421 * handle the ongoing connections.
1424 shutting_down = 1;
1426 event_del(&e4);
1427 if (has_ipv6)
1428 event_del(&e6);
1429 if (has_siginfo)
1430 signal_del(&siginfo);
1431 event_del(&imsgev);
1432 signal_del(&sigusr2);
1434 for (i = 0; i < FCGI_MAX; ++i) {
1435 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
1436 break;
1438 if (fcgi[i].bev == NULL || fcgi[i].pending != 0)
1439 continue;
1441 fcgi_close_backend(&fcgi[i]);
1445 static void
1446 handle_dispatch_imsg(int fd, short ev, void *d)
1448 struct imsgbuf *ibuf = d;
1449 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1452 static void
1453 handle_siginfo(int fd, short ev, void *d)
1455 (void)fd;
1456 (void)ev;
1457 (void)d;
1459 log_info(NULL, "%d connected clients", connected_clients);
1462 void
1463 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1465 size_t i;
1467 ctx = ctx_;
1469 event_init();
1471 memset(&clients, 0, sizeof(clients));
1472 for (i = 0; i < MAX_USERS; ++i)
1473 clients[i].fd = -1;
1475 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1476 event_add(&e4, NULL);
1478 if (sock6 != -1) {
1479 has_ipv6 = 1;
1480 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1481 event_add(&e6, NULL);
1484 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1485 event_add(&imsgev, NULL);
1487 #ifdef SIGINFO
1488 has_siginfo = 1;
1489 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1490 signal_add(&siginfo, NULL);
1491 #endif
1492 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1493 signal_add(&sigusr2, NULL);
1495 sandbox_server_process();
1496 event_dispatch();
1497 _exit(0);