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 bufferevent_enable(c->bev, EV_READ);
510 return;
513 err:
514 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
517 static const char *
518 strip_path(const char *path, int strip)
520 char *t;
522 while (strip > 0) {
523 if ((t = strchr(path, '/')) == NULL) {
524 path = strchr(path, '\0');
525 break;
527 path = t;
528 strip--;
531 return path;
534 static void
535 fmt_sbuf(const char *fmt, struct client *c, const char *path)
537 size_t i;
538 char buf[32];
540 memset(buf, 0, sizeof(buf));
541 for (i = 0; *fmt; ++fmt) {
542 if (i == sizeof(buf)-1 || *fmt == '%') {
543 strlcat(c->sbuf, buf, sizeof(c->sbuf));
544 memset(buf, 0, sizeof(buf));
545 i = 0;
548 if (*fmt != '%') {
549 buf[i++] = *fmt;
550 continue;
553 switch (*++fmt) {
554 case '%':
555 strlcat(c->sbuf, "%", sizeof(c->sbuf));
556 break;
557 case 'p':
558 if (*path != '/')
559 strlcat(c->sbuf, "/", sizeof(c->sbuf));
560 strlcat(c->sbuf, path, sizeof(c->sbuf));
561 break;
562 case 'q':
563 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
564 break;
565 case 'P':
566 snprintf(buf, sizeof(buf), "%d", conf.port);
567 strlcat(c->sbuf, buf, sizeof(c->sbuf));
568 memset(buf, 0, sizeof(buf));
569 break;
570 case 'N':
571 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
572 break;
573 default:
574 fatal("%s: unknown fmt specifier %c",
575 __func__, *fmt);
579 if (i != 0)
580 strlcat(c->sbuf, buf, sizeof(c->sbuf));
583 /* 1 if a matching `block return' (and apply it), 0 otherwise */
584 static int
585 apply_block_return(struct client *c)
587 const char *fmt, *path;
588 int code;
590 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
591 return 0;
593 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
594 fmt_sbuf(fmt, c, path);
596 start_reply(c, code, c->sbuf);
597 return 1;
600 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
601 static int
602 apply_fastcgi(struct client *c)
604 int id;
605 struct fcgi *f;
607 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
608 return 0;
610 switch ((f = &fcgi[id])->s) {
611 case FCGI_OFF:
612 f->s = FCGI_INFLIGHT;
613 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
614 f->path, f->port, f->prog);
615 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
616 &id, sizeof(id));
617 imsg_flush(&exibuf);
618 /* fallthrough */
619 case FCGI_INFLIGHT:
620 c->fcgi = id;
621 break;
622 case FCGI_READY:
623 c->fcgi = id;
624 fcgi_req(f, c);
625 break;
628 return 1;
631 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
632 static int
633 apply_require_ca(struct client *c)
635 X509_STORE *store;
636 const uint8_t *cert;
637 size_t len;
639 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
640 return 0;
642 if (!tls_peer_cert_provided(c->ctx)) {
643 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
644 return 1;
647 cert = tls_peer_cert_chain_pem(c->ctx, &len);
648 if (!validate_against_ca(store, cert, len)) {
649 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
650 return 1;
653 return 0;
656 static size_t
657 host_nth(struct vhost *h)
659 struct vhost *v;
660 size_t i = 0;
662 TAILQ_FOREACH(v, &hosts, vhosts) {
663 if (v == h)
664 return i;
665 i++;
668 abort();
671 static void
672 start_cgi(const char *spath, const char *relpath, struct client *c)
674 char addr[NI_MAXHOST];
675 const char *t;
676 struct cgireq req;
677 int e;
679 c->type = REQUEST_CGI;
681 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
682 addr, sizeof(addr),
683 NULL, 0,
684 NI_NUMERICHOST);
685 if (e != 0)
686 fatal("getnameinfo failed");
688 memset(&req, 0, sizeof(req));
690 memcpy(req.buf, c->req, sizeof(req.buf));
692 req.iri_schema_off = c->iri.schema - c->req;
693 req.iri_host_off = c->iri.host - c->req;
694 req.iri_port_off = c->iri.port - c->req;
695 req.iri_path_off = c->iri.path - c->req;
696 req.iri_query_off = c->iri.query - c->req;
697 req.iri_fragment_off = c->iri.fragment - c->req;
699 req.iri_portno = c->iri.port_no;
701 strlcpy(req.spath, spath, sizeof(req.spath));
702 strlcpy(req.relpath, relpath, sizeof(req.relpath));
703 strlcpy(req.addr, addr, sizeof(req.addr));
705 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
706 strlcpy(req.subject, t, sizeof(req.subject));
707 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
708 strlcpy(req.issuer, t, sizeof(req.issuer));
709 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
710 strlcpy(req.hash, t, sizeof(req.hash));
711 if ((t = tls_conn_version(c->ctx)) != NULL)
712 strlcpy(req.version, t, sizeof(req.version));
713 if ((t = tls_conn_cipher(c->ctx)) != NULL)
714 strlcpy(req.cipher, t, sizeof(req.cipher));
716 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
717 req.notbefore = tls_peer_cert_notbefore(c->ctx);
718 req.notafter = tls_peer_cert_notafter(c->ctx);
720 req.host_off = host_nth(c->host);
721 req.loc_off = c->loc;
723 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
724 imsg_flush(&exibuf);
726 close(c->pfd);
729 static void
730 open_dir(struct client *c)
732 size_t len;
733 int dirfd, root;
734 char *before_file;
736 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
738 len = strlen(c->iri.path);
739 if (len > 0 && !ends_with(c->iri.path, "/")) {
740 redirect_canonical_dir(c);
741 return;
744 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
745 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
746 if (!ends_with(c->sbuf, "/"))
747 strlcat(c->sbuf, "/", sizeof(c->sbuf));
748 before_file = strchr(c->sbuf, '\0');
749 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
750 sizeof(c->sbuf));
751 if (len >= sizeof(c->sbuf)) {
752 start_reply(c, TEMP_FAILURE, "internal server error");
753 return;
756 c->iri.path = c->sbuf;
758 /* close later unless we have to generate the dir listing */
759 dirfd = c->pfd;
760 c->pfd = -1;
762 switch (check_path(c, c->iri.path, &c->pfd)) {
763 case FILE_EXECUTABLE:
764 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
765 start_cgi(c->iri.path, "", c);
766 break;
769 /* fallthrough */
771 case FILE_EXISTS:
772 c->type = REQUEST_FILE;
773 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
774 break;
776 case FILE_DIRECTORY:
777 start_reply(c, TEMP_REDIRECT, c->sbuf);
778 break;
780 case FILE_MISSING:
781 *before_file = '\0';
783 if (!vhost_auto_index(c->host, c->iri.path)) {
784 start_reply(c, NOT_FOUND, "not found");
785 break;
788 c->type = REQUEST_DIR;
790 c->dirlen = scandir_fd(dirfd, &c->dir,
791 root ? select_non_dotdot : select_non_dot,
792 alphasort);
793 if (c->dirlen == -1) {
794 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
795 c->pfd, c->host->domain, c->iri.path, strerror(errno));
796 start_reply(c, TEMP_FAILURE, "internal server error");
797 return;
799 c->diroff = 0;
800 c->off = 0;
802 start_reply(c, SUCCESS, "text/gemini");
803 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
804 "# Index of %s\n\n", c->iri.path);
805 return;
807 default:
808 /* unreachable */
809 abort();
812 close(dirfd);
815 static void
816 redirect_canonical_dir(struct client *c)
818 size_t len;
820 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
821 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
822 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
824 if (len >= sizeof(c->sbuf)) {
825 start_reply(c, TEMP_FAILURE, "internal server error");
826 return;
829 start_reply(c, TEMP_REDIRECT, c->sbuf);
832 static void
833 client_tls_readcb(int fd, short event, void *d)
835 struct bufferevent *bufev = d;
836 struct client *client = bufev->cbarg;
837 ssize_t ret;
838 size_t len;
839 int what = EVBUFFER_READ;
840 int howmuch = IBUF_READ_SIZE;
841 char buf[IBUF_READ_SIZE];
843 if (event == EV_TIMEOUT) {
844 what |= EVBUFFER_TIMEOUT;
845 goto err;
848 if (bufev->wm_read.high != 0)
849 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
851 switch (ret = tls_read(client->ctx, buf, howmuch)) {
852 case TLS_WANT_POLLIN:
853 case TLS_WANT_POLLOUT:
854 goto retry;
855 case -1:
856 what |= EVBUFFER_ERROR;
857 goto err;
859 len = ret;
861 if (len == 0) {
862 what |= EVBUFFER_EOF;
863 goto err;
866 if (evbuffer_add(bufev->input, buf, len) == -1) {
867 what |= EVBUFFER_ERROR;
868 goto err;
871 event_add(&bufev->ev_read, NULL);
872 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
873 return;
874 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
875 /*
876 * here we could implement a read pressure policy.
877 */
880 if (bufev->readcb != NULL)
881 (*bufev->readcb)(bufev, bufev->cbarg);
883 return;
885 retry:
886 event_add(&bufev->ev_read, NULL);
887 return;
889 err:
890 (*bufev->errorcb)(bufev, what, bufev->cbarg);
893 static void
894 client_tls_writecb(int fd, short event, void *d)
896 struct bufferevent *bufev = d;
897 struct client *client = bufev->cbarg;
898 ssize_t ret;
899 size_t len;
900 short what = EVBUFFER_WRITE;
902 if (event == EV_TIMEOUT) {
903 what |= EVBUFFER_TIMEOUT;
904 goto err;
907 if (EVBUFFER_LENGTH(bufev->output) != 0) {
908 ret = tls_write(client->ctx,
909 EVBUFFER_DATA(bufev->output),
910 EVBUFFER_LENGTH(bufev->output));
911 switch (ret) {
912 case TLS_WANT_POLLIN:
913 case TLS_WANT_POLLOUT:
914 goto retry;
915 case -1:
916 what |= EVBUFFER_ERROR;
917 goto err;
919 len = ret;
920 evbuffer_drain(bufev->output, len);
923 if (EVBUFFER_LENGTH(bufev->output) != 0)
924 event_add(&bufev->ev_write, NULL);
926 if (bufev->writecb != NULL &&
927 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
928 (*bufev->writecb)(bufev, bufev->cbarg);
929 return;
931 retry:
932 event_add(&bufev->ev_write, NULL);
933 return;
934 err:
935 log_err(client, "tls error: %s", tls_error(client->ctx));
936 (*bufev->errorcb)(bufev, what, bufev->cbarg);
939 static void
940 client_read(struct bufferevent *bev, void *d)
942 struct client *c = d;
943 struct evbuffer *src = EVBUFFER_INPUT(bev);
944 const char *parse_err = "invalid request";
945 char decoded[DOMAIN_NAME_LEN];
946 size_t len;
948 bufferevent_disable(bev, EVBUFFER_READ);
950 /* max url len + \r\n */
951 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
952 log_err(c, "too much data received");
953 start_reply(c, BAD_REQUEST, "bad request");
954 return;
957 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
958 if (c->req == NULL) {
959 /* not enough data yet. */
960 bufferevent_enable(bev, EVBUFFER_READ);
961 return;
964 if (!parse_iri(c->req, &c->iri, &parse_err) ||
965 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
966 log_err(c, "IRI parse error: %s", parse_err);
967 start_reply(c, BAD_REQUEST, "bad request");
968 return;
971 if (c->iri.port_no != conf.port ||
972 strcmp(c->iri.schema, "gemini") ||
973 strcmp(decoded, c->domain)) {
974 start_reply(c, PROXY_REFUSED, "won't proxy request");
975 return;
978 if (apply_require_ca(c) ||
979 apply_block_return(c)||
980 apply_fastcgi(c))
981 return;
983 if (c->host->entrypoint != NULL) {
984 c->loc = 0;
985 start_cgi(c->host->entrypoint, c->iri.path, c);
986 return;
989 open_file(c);
992 void
993 client_write(struct bufferevent *bev, void *d)
995 struct client *c = d;
996 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
997 char buf[BUFSIZ];
998 ssize_t r;
1000 switch (c->type) {
1001 case REQUEST_UNDECIDED:
1003 * Ignore spurious calls when we still don't have idea
1004 * what to do with the request.
1006 break;
1008 case REQUEST_FILE:
1009 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1010 log_warn(c, "read: %s", strerror(errno));
1011 client_error(bev, EVBUFFER_ERROR, c);
1012 return;
1013 } else if (r == 0) {
1014 client_close(c);
1015 return;
1016 } else if (r != sizeof(buf))
1017 c->type = REQUEST_DONE;
1018 bufferevent_write(bev, buf, r);
1019 break;
1021 case REQUEST_DIR:
1022 /* TODO: handle big big directories better */
1023 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1024 evbuffer_add_printf(out, "=> %s\n",
1025 c->dir[c->diroff]->d_name);
1026 free(c->dir[c->diroff]);
1028 free(c->dir);
1029 c->dir = NULL;
1031 c->type = REQUEST_DONE;
1033 event_add(&c->bev->ev_write, NULL);
1034 break;
1036 case REQUEST_CGI:
1037 case REQUEST_FCGI:
1039 * Here we depend on on the cgi script or fastcgi
1040 * connection to provide data.
1042 break;
1044 case REQUEST_DONE:
1045 if (EVBUFFER_LENGTH(out) == 0)
1046 client_close(c);
1047 break;
1051 static void
1052 client_error(struct bufferevent *bev, short error, void *d)
1054 struct client *c = d;
1056 if (c->type == REQUEST_FCGI)
1057 fcgi_abort_request(c);
1059 c->type = REQUEST_DONE;
1061 if (error & EVBUFFER_TIMEOUT) {
1062 log_warn(c, "timeout reached, "
1063 "forcefully closing the connection");
1064 if (c->code == 0)
1065 start_reply(c, BAD_REQUEST, "timeout");
1066 else
1067 client_close(c);
1068 return;
1071 if (error & EVBUFFER_EOF) {
1072 client_close(c);
1073 return;
1076 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1077 client_close(c);
1080 void
1081 start_reply(struct client *c, int code, const char *meta)
1083 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1084 const char *lang;
1085 int r, rr;
1087 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1089 c->code = code;
1090 c->meta = meta;
1092 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1093 if (r == -1)
1094 goto err;
1096 /* 2 digit status + space + 1024 max reply */
1097 if (r > 1027)
1098 goto overflow;
1100 if (c->type != REQUEST_CGI &&
1101 c->type != REQUEST_FCGI &&
1102 !strcmp(meta, "text/gemini") &&
1103 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1104 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1105 if (rr == -1)
1106 goto err;
1107 if (r + rr > 1027)
1108 goto overflow;
1111 bufferevent_write(c->bev, "\r\n", 2);
1113 if (!vhost_disable_log(c->host, c->iri.path))
1114 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1116 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1117 c->type = REQUEST_DONE;
1119 return;
1121 err:
1122 log_err(c, "evbuffer_add_printf error: no memory");
1123 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1124 client_close(c);
1125 return;
1127 overflow:
1128 log_warn(c, "reply header overflow");
1129 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1130 start_reply(c, TEMP_FAILURE, "internal error");
1133 static void
1134 client_close_ev(int fd, short event, void *d)
1136 struct client *c = d;
1138 switch (tls_close(c->ctx)) {
1139 case TLS_WANT_POLLIN:
1140 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1141 break;
1142 case TLS_WANT_POLLOUT:
1143 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1144 break;
1147 connected_clients--;
1149 tls_free(c->ctx);
1150 c->ctx = NULL;
1152 free(c->header);
1154 if (c->pfd != -1)
1155 close(c->pfd);
1157 if (c->dir != NULL)
1158 free(c->dir);
1160 close(c->fd);
1161 c->fd = -1;
1164 void
1165 client_close(struct client *c)
1168 * We may end up calling client_close in various situations
1169 * and for the most unexpected reasons. Therefore, we need to
1170 * ensure that everything is properly released once we reach
1171 * this point.
1174 if (c->type == REQUEST_FCGI)
1175 fcgi_abort_request(c);
1177 if (c->cgibev != NULL) {
1178 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1179 bufferevent_free(c->cgibev);
1180 c->cgibev = NULL;
1181 close(c->pfd);
1182 c->pfd = -1;
1185 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1186 bufferevent_free(c->bev);
1187 c->bev = NULL;
1189 client_close_ev(c->fd, 0, c);
1192 static void
1193 cgi_read(struct bufferevent *bev, void *d)
1195 struct client *client = d;
1196 struct evbuffer *src = EVBUFFER_INPUT(bev);
1197 char *header;
1198 size_t len;
1199 int code;
1201 /* intercept the header */
1202 if (client->code == 0) {
1203 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1204 if (header == NULL) {
1205 /* max reply + \r\n */
1206 if (EVBUFFER_LENGTH(src) > 1026) {
1207 log_warn(client, "CGI script is trying to "
1208 "send a header too long.");
1209 cgi_error(bev, EVBUFFER_READ, client);
1212 /* wait a bit */
1213 return;
1216 if (len < 3 || len > 1029 ||
1217 !isdigit(header[0]) ||
1218 !isdigit(header[1]) ||
1219 !isspace(header[2])) {
1220 free(header);
1221 log_warn(client, "CGI script is trying to send a "
1222 "malformed header");
1223 cgi_error(bev, EVBUFFER_READ, client);
1224 return;
1227 client->header = header;
1228 code = (header[0] - '0') * 10 + (header[1] - '0');
1230 if (code < 10 || code >= 70) {
1231 log_warn(client, "CGI script is trying to send an "
1232 "invalid reply code (%d)", code);
1233 cgi_error(bev, EVBUFFER_READ, client);
1234 return;
1237 start_reply(client, code, header + 3);
1239 if (client->code < 20 || client->code > 29) {
1240 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1241 return;
1245 bufferevent_write_buffer(client->bev, src);
1248 static void
1249 cgi_write(struct bufferevent *bev, void *d)
1252 * Never called. We don't send data to a CGI script.
1254 abort();
1257 static void
1258 cgi_error(struct bufferevent *bev, short error, void *d)
1260 struct client *client = d;
1262 if (error & EVBUFFER_ERROR)
1263 log_err(client, "%s: evbuffer error (%x): %s",
1264 __func__, error, strerror(errno));
1266 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1267 bufferevent_free(bev);
1268 client->cgibev = NULL;
1270 close(client->pfd);
1271 client->pfd = -1;
1273 client->type = REQUEST_DONE;
1274 if (client->code != 0)
1275 client_write(client->bev, client);
1276 else
1277 start_reply(client, CGI_ERROR, "CGI error");
1280 static void
1281 do_accept(int sock, short et, void *d)
1283 struct client *c;
1284 struct sockaddr_storage addr;
1285 struct sockaddr *saddr;
1286 socklen_t len;
1287 int i, fd;
1289 (void)et;
1291 saddr = (struct sockaddr*)&addr;
1292 len = sizeof(addr);
1293 if ((fd = accept(sock, saddr, &len)) == -1) {
1294 if (errno == EWOULDBLOCK || errno == EAGAIN)
1295 return;
1296 fatal("accept: %s", strerror(errno));
1299 mark_nonblock(fd);
1301 for (i = 0; i < MAX_USERS; ++i) {
1302 c = &clients[i];
1303 if (c->fd == -1) {
1304 memset(c, 0, sizeof(*c));
1305 c->id = i;
1306 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1307 break; /* goodbye fd! */
1309 c->fd = fd;
1310 c->pfd = -1;
1311 c->dir = NULL;
1312 c->addr = addr;
1313 c->fcgi = -1;
1315 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake,
1316 c, NULL);
1318 connected_clients++;
1319 return;
1323 close(fd);
1326 static struct client *
1327 client_by_id(int id)
1329 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1330 fatal("in client_by_id: invalid id %d", id);
1331 return &clients[id];
1334 struct client *
1335 try_client_by_id(int id)
1337 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1338 return NULL;
1339 return &clients[id];
1342 static void
1343 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1345 struct client *c;
1347 c = client_by_id(imsg->hdr.peerid);
1349 if ((c->pfd = imsg->fd) == -1) {
1350 start_reply(c, TEMP_FAILURE, "internal server error");
1351 return;
1354 c->type = REQUEST_CGI;
1356 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1357 cgi_error, c);
1359 bufferevent_enable(c->cgibev, EV_READ);
1362 static void
1363 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1365 struct client *c;
1366 struct fcgi *f;
1367 int i, id;
1369 id = imsg->hdr.peerid;
1370 f = &fcgi[id];
1372 if ((f->fd = imsg->fd) == -1)
1373 f->s = FCGI_OFF;
1374 else {
1375 mark_nonblock(f->fd);
1377 f->s = FCGI_READY;
1379 f->bev = bufferevent_new(f->fd, fcgi_read, fcgi_write,
1380 fcgi_error, f);
1381 if (f->bev == NULL) {
1382 close(f->fd);
1383 log_err(NULL, "%s: failed to allocate client buffer",
1384 __func__);
1385 f->s = FCGI_OFF;
1388 bufferevent_enable(f->bev, EV_READ|EV_WRITE);
1391 for (i = 0; i < MAX_USERS; ++i) {
1392 c = &clients[i];
1393 if (c->fd == -1)
1394 continue;
1395 if (c->fcgi != id)
1396 continue;
1398 if (f->s == FCGI_OFF) {
1399 c->fcgi = -1;
1400 start_reply(c, TEMP_FAILURE, "internal server error");
1401 } else
1402 fcgi_req(f, c);
1406 static void
1407 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1409 size_t i;
1411 (void)imsg;
1412 (void)len;
1415 * don't call event_loopbreak since we want to finish to
1416 * handle the ongoing connections.
1419 shutting_down = 1;
1421 event_del(&e4);
1422 if (has_ipv6)
1423 event_del(&e6);
1424 if (has_siginfo)
1425 signal_del(&siginfo);
1426 event_del(&imsgev);
1427 signal_del(&sigusr2);
1429 for (i = 0; i < FCGI_MAX; ++i) {
1430 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
1431 break;
1433 if (fcgi[i].bev == NULL || fcgi[i].pending != 0)
1434 continue;
1436 fcgi_close_backend(&fcgi[i]);
1440 static void
1441 handle_dispatch_imsg(int fd, short ev, void *d)
1443 struct imsgbuf *ibuf = d;
1444 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1447 static void
1448 handle_siginfo(int fd, short ev, void *d)
1450 (void)fd;
1451 (void)ev;
1452 (void)d;
1454 log_info(NULL, "%d connected clients", connected_clients);
1457 void
1458 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1460 size_t i;
1462 ctx = ctx_;
1464 event_init();
1466 memset(&clients, 0, sizeof(clients));
1467 for (i = 0; i < MAX_USERS; ++i)
1468 clients[i].fd = -1;
1470 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1471 event_add(&e4, NULL);
1473 if (sock6 != -1) {
1474 has_ipv6 = 1;
1475 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1476 event_add(&e6, NULL);
1479 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1480 event_add(&imsgev, NULL);
1482 #ifdef SIGINFO
1483 has_siginfo = 1;
1484 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1485 signal_add(&siginfo, NULL);
1486 #endif
1487 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1488 signal_add(&sigusr2, NULL);
1490 sandbox_server_process();
1491 event_dispatch();
1492 _exit(0);