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_fastcgi(struct client*);
51 static int apply_require_ca(struct client*);
52 static size_t host_nth(struct vhost*);
53 static void start_cgi(const char*, const char*, struct client*);
54 static void open_dir(struct client*);
55 static void redirect_canonical_dir(struct client*);
57 static void client_tls_readcb(int, short, void *);
58 static void client_tls_writecb(int, short, void *);
60 static void client_read(struct bufferevent *, void *);
61 void client_write(struct bufferevent *, void *);
62 static void client_error(struct bufferevent *, short, void *);
64 static void client_close_ev(int, short, void *);
66 static void cgi_read(struct bufferevent *, void *);
67 static void cgi_write(struct bufferevent *, void *);
68 static void cgi_error(struct bufferevent *, short, void *);
70 static void do_accept(int, short, void*);
71 static struct client *client_by_id(int);
73 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
74 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
75 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
76 static void handle_dispatch_imsg(int, short, void *);
77 static void handle_siginfo(int, short, void*);
79 static imsg_handlerfn *handlers[] = {
80 [IMSG_QUIT] = handle_imsg_quit,
81 [IMSG_CGI_RES] = handle_imsg_cgi_res,
82 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
83 };
85 static uint32_t server_client_id;
87 struct client_tree_id clients;
89 static inline int
90 matches(const char *pattern, const char *path)
91 {
92 if (*path == '/')
93 path++;
94 return !fnmatch(pattern, path, 0);
95 }
97 const char *
98 vhost_lang(struct vhost *v, const char *path)
99 {
100 struct location *loc;
102 if (v == NULL || path == NULL)
103 return NULL;
105 loc = TAILQ_FIRST(&v->locations);
106 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
107 if (loc->lang != NULL) {
108 if (matches(loc->match, path))
109 return loc->lang;
113 return TAILQ_FIRST(&v->locations)->lang;
116 const char *
117 vhost_default_mime(struct vhost *v, const char *path)
119 struct location *loc;
120 const char *default_mime = "application/octet-stream";
122 if (v == NULL || path == NULL)
123 return default_mime;
125 loc = TAILQ_FIRST(&v->locations);
126 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
127 if (loc->default_mime != NULL) {
128 if (matches(loc->match, path))
129 return loc->default_mime;
133 loc = TAILQ_FIRST(&v->locations);
134 if (loc->default_mime != NULL)
135 return loc->default_mime;
136 return default_mime;
139 const char *
140 vhost_index(struct vhost *v, const char *path)
142 struct location *loc;
143 const char *index = "index.gmi";
145 if (v == NULL || path == NULL)
146 return index;
148 loc = TAILQ_FIRST(&v->locations);
149 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
150 if (loc->index != NULL) {
151 if (matches(loc->match, path))
152 return loc->index;
156 loc = TAILQ_FIRST(&v->locations);
157 if (loc->index != NULL)
158 return loc->index;
159 return index;
162 int
163 vhost_auto_index(struct vhost *v, const char *path)
165 struct location *loc;
167 if (v == NULL || path == NULL)
168 return 0;
170 loc = TAILQ_FIRST(&v->locations);
171 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
172 if (loc->auto_index != 0) {
173 if (matches(loc->match, path))
174 return loc->auto_index == 1;
178 loc = TAILQ_FIRST(&v->locations);
179 return loc->auto_index == 1;
182 int
183 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
185 struct location *loc;
187 if (v == NULL || path == NULL)
188 return 0;
190 loc = TAILQ_FIRST(&v->locations);
191 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
192 if (loc->block_code != 0) {
193 if (matches(loc->match, path)) {
194 *code = loc->block_code;
195 *fmt = loc->block_fmt;
196 return 1;
201 loc = TAILQ_FIRST(&v->locations);
202 *code = loc->block_code;
203 *fmt = loc->block_fmt;
204 return loc->block_code != 0;
207 int
208 vhost_fastcgi(struct vhost *v, const char *path)
210 struct location *loc;
212 if (v == NULL || path == NULL)
213 return -1;
215 loc = TAILQ_FIRST(&v->locations);
216 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
217 if (loc->fcgi != -1)
218 if (matches(loc->match, path))
219 return loc->fcgi;
222 loc = TAILQ_FIRST(&v->locations);
223 return loc->fcgi;
226 int
227 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
229 struct location *loc;
230 size_t l = 0;
232 if (v == NULL || path == NULL)
233 return -1;
235 loc = TAILQ_FIRST(&v->locations);
236 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
237 l++;
238 if (loc->dirfd != -1)
239 if (matches(loc->match, path)) {
240 *retloc = l;
241 return loc->dirfd;
245 *retloc = 0;
246 loc = TAILQ_FIRST(&v->locations);
247 return loc->dirfd;
250 int
251 vhost_strip(struct vhost *v, const char *path)
253 struct location *loc;
255 if (v == NULL || path == NULL)
256 return 0;
258 loc = TAILQ_FIRST(&v->locations);
259 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
260 if (loc->strip != 0) {
261 if (matches(loc->match, path))
262 return loc->strip;
266 loc = TAILQ_FIRST(&v->locations);
267 return loc->strip;
270 X509_STORE *
271 vhost_require_ca(struct vhost *v, const char *path)
273 struct location *loc;
275 if (v == NULL || path == NULL)
276 return NULL;
278 loc = TAILQ_FIRST(&v->locations);
279 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
280 if (loc->reqca != NULL) {
281 if (matches(loc->match, path))
282 return loc->reqca;
286 loc = TAILQ_FIRST(&v->locations);
287 return loc->reqca;
290 int
291 vhost_disable_log(struct vhost *v, const char *path)
293 struct location *loc;
295 if (v == NULL || path == NULL)
296 return 0;
298 loc = TAILQ_FIRST(&v->locations);
299 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
300 if (loc->disable_log && matches(loc->match, path))
301 return 1;
304 loc = TAILQ_FIRST(&v->locations);
305 return loc->disable_log;
308 static int
309 check_path(struct client *c, const char *path, int *fd)
311 struct stat sb;
312 const char *p;
313 int dirfd, strip;
315 assert(path != NULL);
317 /*
318 * in send_dir we add an initial / (to be redirect-friendly),
319 * but here we want to skip it
320 */
321 if (*path == '/')
322 path++;
324 strip = vhost_strip(c->host, path);
325 p = strip_path(path, strip);
327 if (*p == '/')
328 p = p+1;
329 if (*p == '\0')
330 p = ".";
332 dirfd = vhost_dirfd(c->host, path, &c->loc);
333 log_debug(c, "check_path: strip=%d path=%s original=%s",
334 strip, p, path);
335 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
336 return FILE_MISSING;
338 if (fstat(*fd, &sb) == -1) {
339 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
340 return FILE_MISSING;
343 if (S_ISDIR(sb.st_mode))
344 return FILE_DIRECTORY;
346 if (sb.st_mode & S_IXUSR)
347 return FILE_EXECUTABLE;
349 return FILE_EXISTS;
352 static void
353 open_file(struct client *c)
355 switch (check_path(c, c->iri.path, &c->pfd)) {
356 case FILE_EXECUTABLE:
357 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
358 start_cgi(c->iri.path, "", c);
359 return;
362 /* fallthrough */
364 case FILE_EXISTS:
365 c->type = REQUEST_FILE;
366 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
367 return;
369 case FILE_DIRECTORY:
370 open_dir(c);
371 return;
373 case FILE_MISSING:
374 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
375 check_for_cgi(c);
376 return;
378 start_reply(c, NOT_FOUND, "not found");
379 return;
381 default:
382 /* unreachable */
383 abort();
387 /*
388 * the inverse of this algorithm, i.e. starting from the start of the
389 * path + strlen(cgi), and checking if each component, should be
390 * faster. But it's tedious to write. This does the opposite: starts
391 * from the end and strip one component at a time, until either an
392 * executable is found or we emptied the path.
393 */
394 static void
395 check_for_cgi(struct client *c)
397 char path[PATH_MAX];
398 char *end;
400 strlcpy(path, c->iri.path, sizeof(path));
401 end = strchr(path, '\0');
403 while (end > path) {
404 /*
405 * go up one level. UNIX paths are simple and POSIX
406 * dirname, with its ambiguities on if the given
407 * pointer is changed or not, gives me headaches.
408 */
409 while (*end != '/' && end > path)
410 end--;
412 if (end == path)
413 break;
415 *end = '\0';
417 switch (check_path(c, path, &c->pfd)) {
418 case FILE_EXECUTABLE:
419 start_cgi(path, end+1, c);
420 return;
421 case FILE_MISSING:
422 break;
423 default:
424 goto err;
427 *end = '/';
428 end--;
431 err:
432 start_reply(c, NOT_FOUND, "not found");
433 return;
436 void
437 mark_nonblock(int fd)
439 int flags;
441 if ((flags = fcntl(fd, F_GETFL)) == -1)
442 fatal("fcntl(F_GETFL): %s", strerror(errno));
443 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
444 fatal("fcntl(F_SETFL): %s", strerror(errno));
447 static void
448 handle_handshake(int fd, short ev, void *d)
450 struct client *c = d;
451 struct vhost *h;
452 struct alist *a;
453 const char *servname;
454 const char *parse_err = "unknown error";
456 switch (tls_handshake(c->ctx)) {
457 case 0: /* success */
458 case -1: /* already handshaked */
459 break;
460 case TLS_WANT_POLLIN:
461 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
462 return;
463 case TLS_WANT_POLLOUT:
464 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
465 return;
466 default:
467 /* unreachable */
468 abort();
471 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
472 log_debug(c, "handshake: missing SNI");
473 goto err;
476 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
477 log_info(c, "puny_decode: %s", parse_err);
478 goto err;
481 TAILQ_FOREACH(h, &hosts, vhosts) {
482 if (matches(h->domain, c->domain))
483 goto found;
484 TAILQ_FOREACH(a, &h->aliases, aliases) {
485 if (matches(a->alias, c->domain))
486 goto found;
490 found:
491 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
492 servname != NULL ? servname : "(null)",
493 c->domain,
494 h != NULL ? h->domain : "(null)");
496 if (h != NULL) {
497 c->host = h;
499 c->bev = bufferevent_new(fd, client_read, client_write,
500 client_error, c);
501 if (c->bev == NULL)
502 fatal("%s: failed to allocate client buffer: %s",
503 __func__, strerror(errno));
505 event_set(&c->bev->ev_read, c->fd, EV_READ,
506 client_tls_readcb, c->bev);
507 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
508 client_tls_writecb, c->bev);
510 #if HAVE_LIBEVENT2
511 evbuffer_unfreeze(c->bev->input, 0);
512 evbuffer_unfreeze(c->bev->output, 1);
513 #endif
515 bufferevent_enable(c->bev, EV_READ);
517 return;
520 err:
521 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
524 static const char *
525 strip_path(const char *path, int strip)
527 char *t;
529 while (strip > 0) {
530 if ((t = strchr(path, '/')) == NULL) {
531 path = strchr(path, '\0');
532 break;
534 path = t;
535 strip--;
538 return path;
541 static void
542 fmt_sbuf(const char *fmt, struct client *c, const char *path)
544 size_t i;
545 char buf[32];
547 memset(buf, 0, sizeof(buf));
548 for (i = 0; *fmt; ++fmt) {
549 if (i == sizeof(buf)-1 || *fmt == '%') {
550 strlcat(c->sbuf, buf, sizeof(c->sbuf));
551 memset(buf, 0, sizeof(buf));
552 i = 0;
555 if (*fmt != '%') {
556 buf[i++] = *fmt;
557 continue;
560 switch (*++fmt) {
561 case '%':
562 strlcat(c->sbuf, "%", sizeof(c->sbuf));
563 break;
564 case 'p':
565 if (*path != '/')
566 strlcat(c->sbuf, "/", sizeof(c->sbuf));
567 strlcat(c->sbuf, path, sizeof(c->sbuf));
568 break;
569 case 'q':
570 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
571 break;
572 case 'P':
573 snprintf(buf, sizeof(buf), "%d", conf.port);
574 strlcat(c->sbuf, buf, sizeof(c->sbuf));
575 memset(buf, 0, sizeof(buf));
576 break;
577 case 'N':
578 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
579 break;
580 default:
581 fatal("%s: unknown fmt specifier %c",
582 __func__, *fmt);
586 if (i != 0)
587 strlcat(c->sbuf, buf, sizeof(c->sbuf));
590 /* 1 if a matching `block return' (and apply it), 0 otherwise */
591 static int
592 apply_block_return(struct client *c)
594 const char *fmt, *path;
595 int code;
597 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
598 return 0;
600 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
601 fmt_sbuf(fmt, c, path);
603 start_reply(c, code, c->sbuf);
604 return 1;
607 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
608 static int
609 apply_fastcgi(struct client *c)
611 int id;
612 struct fcgi *f;
614 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
615 return 0;
617 f = &fcgi[id];
619 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
620 f->path, f->port, f->prog);
622 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
623 &id, sizeof(id));
624 imsg_flush(&exibuf);
625 return 1;
628 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
629 static int
630 apply_require_ca(struct client *c)
632 X509_STORE *store;
633 const uint8_t *cert;
634 size_t len;
636 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
637 return 0;
639 if (!tls_peer_cert_provided(c->ctx)) {
640 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
641 return 1;
644 cert = tls_peer_cert_chain_pem(c->ctx, &len);
645 if (!validate_against_ca(store, cert, len)) {
646 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
647 return 1;
650 return 0;
653 static size_t
654 host_nth(struct vhost *h)
656 struct vhost *v;
657 size_t i = 0;
659 TAILQ_FOREACH(v, &hosts, vhosts) {
660 if (v == h)
661 return i;
662 i++;
665 abort();
668 static void
669 start_cgi(const char *spath, const char *relpath, struct client *c)
671 char addr[NI_MAXHOST];
672 const char *t;
673 struct cgireq req;
674 int e;
676 c->type = REQUEST_CGI;
678 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
679 addr, sizeof(addr),
680 NULL, 0,
681 NI_NUMERICHOST);
682 if (e != 0)
683 fatal("getnameinfo failed");
685 memset(&req, 0, sizeof(req));
687 memcpy(req.buf, c->req, sizeof(req.buf));
689 req.iri_schema_off = c->iri.schema - c->req;
690 req.iri_host_off = c->iri.host - c->req;
691 req.iri_port_off = c->iri.port - c->req;
692 req.iri_path_off = c->iri.path - c->req;
693 req.iri_query_off = c->iri.query - c->req;
694 req.iri_fragment_off = c->iri.fragment - c->req;
696 req.iri_portno = c->iri.port_no;
698 strlcpy(req.spath, spath, sizeof(req.spath));
699 strlcpy(req.relpath, relpath, sizeof(req.relpath));
700 strlcpy(req.addr, addr, sizeof(req.addr));
702 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
703 strlcpy(req.subject, t, sizeof(req.subject));
704 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
705 strlcpy(req.issuer, t, sizeof(req.issuer));
706 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
707 strlcpy(req.hash, t, sizeof(req.hash));
708 if ((t = tls_conn_version(c->ctx)) != NULL)
709 strlcpy(req.version, t, sizeof(req.version));
710 if ((t = tls_conn_cipher(c->ctx)) != NULL)
711 strlcpy(req.cipher, t, sizeof(req.cipher));
713 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
714 req.notbefore = tls_peer_cert_notbefore(c->ctx);
715 req.notafter = tls_peer_cert_notafter(c->ctx);
717 req.host_off = host_nth(c->host);
718 req.loc_off = c->loc;
720 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
721 imsg_flush(&exibuf);
723 close(c->pfd);
726 static void
727 open_dir(struct client *c)
729 size_t len;
730 int dirfd, root;
731 char *before_file;
733 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
735 len = strlen(c->iri.path);
736 if (len > 0 && !ends_with(c->iri.path, "/")) {
737 redirect_canonical_dir(c);
738 return;
741 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
742 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
743 if (!ends_with(c->sbuf, "/"))
744 strlcat(c->sbuf, "/", sizeof(c->sbuf));
745 before_file = strchr(c->sbuf, '\0');
746 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
747 sizeof(c->sbuf));
748 if (len >= sizeof(c->sbuf)) {
749 start_reply(c, TEMP_FAILURE, "internal server error");
750 return;
753 c->iri.path = c->sbuf;
755 /* close later unless we have to generate the dir listing */
756 dirfd = c->pfd;
757 c->pfd = -1;
759 switch (check_path(c, c->iri.path, &c->pfd)) {
760 case FILE_EXECUTABLE:
761 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
762 start_cgi(c->iri.path, "", c);
763 break;
766 /* fallthrough */
768 case FILE_EXISTS:
769 c->type = REQUEST_FILE;
770 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
771 break;
773 case FILE_DIRECTORY:
774 start_reply(c, TEMP_REDIRECT, c->sbuf);
775 break;
777 case FILE_MISSING:
778 *before_file = '\0';
780 if (!vhost_auto_index(c->host, c->iri.path)) {
781 start_reply(c, NOT_FOUND, "not found");
782 break;
785 c->type = REQUEST_DIR;
787 c->dirlen = scandir_fd(dirfd, &c->dir,
788 root ? select_non_dotdot : select_non_dot,
789 alphasort);
790 if (c->dirlen == -1) {
791 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
792 c->pfd, c->host->domain, c->iri.path, strerror(errno));
793 start_reply(c, TEMP_FAILURE, "internal server error");
794 return;
796 c->diroff = 0;
797 c->off = 0;
799 start_reply(c, SUCCESS, "text/gemini");
800 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
801 "# Index of %s\n\n", c->iri.path);
802 return;
804 default:
805 /* unreachable */
806 abort();
809 close(dirfd);
812 static void
813 redirect_canonical_dir(struct client *c)
815 size_t len;
817 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
818 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
819 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
821 if (len >= sizeof(c->sbuf)) {
822 start_reply(c, TEMP_FAILURE, "internal server error");
823 return;
826 start_reply(c, TEMP_REDIRECT, c->sbuf);
829 static void
830 client_tls_readcb(int fd, short event, void *d)
832 struct bufferevent *bufev = d;
833 struct client *client = bufev->cbarg;
834 ssize_t ret;
835 size_t len;
836 int what = EVBUFFER_READ;
837 int howmuch = IBUF_READ_SIZE;
838 char buf[IBUF_READ_SIZE];
840 if (event == EV_TIMEOUT) {
841 what |= EVBUFFER_TIMEOUT;
842 goto err;
845 if (bufev->wm_read.high != 0)
846 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
848 switch (ret = tls_read(client->ctx, buf, howmuch)) {
849 case TLS_WANT_POLLIN:
850 case TLS_WANT_POLLOUT:
851 goto retry;
852 case -1:
853 what |= EVBUFFER_ERROR;
854 goto err;
856 len = ret;
858 if (len == 0) {
859 what |= EVBUFFER_EOF;
860 goto err;
863 if (evbuffer_add(bufev->input, buf, len) == -1) {
864 what |= EVBUFFER_ERROR;
865 goto err;
868 event_add(&bufev->ev_read, NULL);
869 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
870 return;
871 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
872 /*
873 * here we could implement a read pressure policy.
874 */
877 if (bufev->readcb != NULL)
878 (*bufev->readcb)(bufev, bufev->cbarg);
880 return;
882 retry:
883 event_add(&bufev->ev_read, NULL);
884 return;
886 err:
887 (*bufev->errorcb)(bufev, what, bufev->cbarg);
890 static void
891 client_tls_writecb(int fd, short event, void *d)
893 struct bufferevent *bufev = d;
894 struct client *client = bufev->cbarg;
895 ssize_t ret;
896 size_t len;
897 short what = EVBUFFER_WRITE;
899 if (event == EV_TIMEOUT) {
900 what |= EVBUFFER_TIMEOUT;
901 goto err;
904 if (EVBUFFER_LENGTH(bufev->output) != 0) {
905 ret = tls_write(client->ctx,
906 EVBUFFER_DATA(bufev->output),
907 EVBUFFER_LENGTH(bufev->output));
908 switch (ret) {
909 case TLS_WANT_POLLIN:
910 case TLS_WANT_POLLOUT:
911 goto retry;
912 case -1:
913 what |= EVBUFFER_ERROR;
914 goto err;
916 len = ret;
917 evbuffer_drain(bufev->output, len);
920 if (EVBUFFER_LENGTH(bufev->output) != 0)
921 event_add(&bufev->ev_write, NULL);
923 if (bufev->writecb != NULL &&
924 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
925 (*bufev->writecb)(bufev, bufev->cbarg);
926 return;
928 retry:
929 event_add(&bufev->ev_write, NULL);
930 return;
931 err:
932 log_err(client, "tls error: %s", tls_error(client->ctx));
933 (*bufev->errorcb)(bufev, what, bufev->cbarg);
936 static void
937 client_read(struct bufferevent *bev, void *d)
939 struct client *c = d;
940 struct evbuffer *src = EVBUFFER_INPUT(bev);
941 const char *parse_err = "invalid request";
942 char decoded[DOMAIN_NAME_LEN];
943 size_t len;
945 bufferevent_disable(bev, EVBUFFER_READ);
947 /* max url len + \r\n */
948 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
949 log_err(c, "too much data received");
950 start_reply(c, BAD_REQUEST, "bad request");
951 return;
954 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
955 if (c->req == NULL) {
956 /* not enough data yet. */
957 bufferevent_enable(bev, EVBUFFER_READ);
958 return;
961 if (!parse_iri(c->req, &c->iri, &parse_err) ||
962 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
963 log_err(c, "IRI parse error: %s", parse_err);
964 start_reply(c, BAD_REQUEST, "bad request");
965 return;
968 if (c->iri.port_no != conf.port ||
969 strcmp(c->iri.schema, "gemini") ||
970 strcmp(decoded, c->domain)) {
971 start_reply(c, PROXY_REFUSED, "won't proxy request");
972 return;
975 if (apply_require_ca(c) ||
976 apply_block_return(c)||
977 apply_fastcgi(c))
978 return;
980 if (c->host->entrypoint != NULL) {
981 c->loc = 0;
982 start_cgi(c->host->entrypoint, c->iri.path, c);
983 return;
986 open_file(c);
989 void
990 client_write(struct bufferevent *bev, void *d)
992 struct client *c = d;
993 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
994 char buf[BUFSIZ];
995 ssize_t r;
997 switch (c->type) {
998 case REQUEST_UNDECIDED:
999 /*
1000 * Ignore spurious calls when we still don't have idea
1001 * what to do with the request.
1003 break;
1005 case REQUEST_FILE:
1006 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1007 log_warn(c, "read: %s", strerror(errno));
1008 client_error(bev, EVBUFFER_ERROR, c);
1009 return;
1010 } else if (r == 0) {
1011 client_close(c);
1012 return;
1013 } else if (r != sizeof(buf))
1014 c->type = REQUEST_DONE;
1015 bufferevent_write(bev, buf, r);
1016 break;
1018 case REQUEST_DIR:
1019 /* TODO: handle big big directories better */
1020 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1021 evbuffer_add_printf(out, "=> %s\n",
1022 c->dir[c->diroff]->d_name);
1023 free(c->dir[c->diroff]);
1025 free(c->dir);
1026 c->dir = NULL;
1028 c->type = REQUEST_DONE;
1030 event_add(&c->bev->ev_write, NULL);
1031 break;
1033 case REQUEST_CGI:
1034 case REQUEST_FCGI:
1036 * Here we depend on on the cgi script or fastcgi
1037 * connection to provide data.
1039 break;
1041 case REQUEST_DONE:
1042 if (EVBUFFER_LENGTH(out) == 0)
1043 client_close(c);
1044 break;
1048 static void
1049 client_error(struct bufferevent *bev, short error, void *d)
1051 struct client *c = d;
1053 c->type = REQUEST_DONE;
1055 if (error & EVBUFFER_TIMEOUT) {
1056 log_warn(c, "timeout reached, "
1057 "forcefully closing the connection");
1058 if (c->code == 0)
1059 start_reply(c, BAD_REQUEST, "timeout");
1060 else
1061 client_close(c);
1062 return;
1065 if (error & EVBUFFER_EOF) {
1066 client_close(c);
1067 return;
1070 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1071 client_close(c);
1074 void
1075 start_reply(struct client *c, int code, const char *meta)
1077 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1078 const char *lang;
1079 int r, rr;
1081 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1083 c->code = code;
1084 c->meta = meta;
1086 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1087 if (r == -1)
1088 goto err;
1090 /* 2 digit status + space + 1024 max reply */
1091 if (r > 1027)
1092 goto overflow;
1094 if (c->type != REQUEST_CGI &&
1095 c->type != REQUEST_FCGI &&
1096 !strcmp(meta, "text/gemini") &&
1097 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1098 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1099 if (rr == -1)
1100 goto err;
1101 if (r + rr > 1027)
1102 goto overflow;
1105 bufferevent_write(c->bev, "\r\n", 2);
1107 if (!vhost_disable_log(c->host, c->iri.path))
1108 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1110 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1111 c->type = REQUEST_DONE;
1113 return;
1115 err:
1116 log_err(c, "evbuffer_add_printf error: no memory");
1117 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1118 client_close(c);
1119 return;
1121 overflow:
1122 log_warn(c, "reply header overflow");
1123 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1124 start_reply(c, TEMP_FAILURE, "internal error");
1127 static void
1128 client_close_ev(int fd, short event, void *d)
1130 struct client *c = d;
1132 switch (tls_close(c->ctx)) {
1133 case TLS_WANT_POLLIN:
1134 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1135 break;
1136 case TLS_WANT_POLLOUT:
1137 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1138 break;
1141 connected_clients--;
1143 free(c->req);
1145 tls_free(c->ctx);
1146 c->ctx = NULL;
1148 free(c->header);
1150 if (c->pfd != -1)
1151 close(c->pfd);
1153 if (c->dir != NULL)
1154 free(c->dir);
1156 close(c->fd);
1157 c->fd = -1;
1160 void
1161 client_close(struct client *c)
1164 * We may end up calling client_close in various situations
1165 * and for the most unexpected reasons. Therefore, we need to
1166 * ensure that everything is properly released once we reach
1167 * this point.
1170 SPLAY_REMOVE(client_tree_id, &clients, c);
1172 if (c->cgibev != NULL) {
1173 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1174 bufferevent_free(c->cgibev);
1175 c->cgibev = NULL;
1176 close(c->pfd);
1177 c->pfd = -1;
1180 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1181 bufferevent_free(c->bev);
1182 c->bev = NULL;
1184 client_close_ev(c->fd, 0, c);
1187 static void
1188 cgi_read(struct bufferevent *bev, void *d)
1190 struct client *client = d;
1191 struct evbuffer *src = EVBUFFER_INPUT(bev);
1192 char *header;
1193 size_t len;
1194 int code;
1196 /* intercept the header */
1197 if (client->code == 0) {
1198 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1199 if (header == NULL) {
1200 /* max reply + \r\n */
1201 if (EVBUFFER_LENGTH(src) > 1026) {
1202 log_warn(client, "CGI script is trying to "
1203 "send a header too long.");
1204 cgi_error(bev, EVBUFFER_READ, client);
1207 /* wait a bit */
1208 return;
1211 if (len < 3 || len > 1029 ||
1212 !isdigit(header[0]) ||
1213 !isdigit(header[1]) ||
1214 !isspace(header[2])) {
1215 free(header);
1216 log_warn(client, "CGI script is trying to send a "
1217 "malformed header");
1218 cgi_error(bev, EVBUFFER_READ, client);
1219 return;
1222 client->header = header;
1223 code = (header[0] - '0') * 10 + (header[1] - '0');
1225 if (code < 10 || code >= 70) {
1226 log_warn(client, "CGI script is trying to send an "
1227 "invalid reply code (%d)", code);
1228 cgi_error(bev, EVBUFFER_READ, client);
1229 return;
1232 start_reply(client, code, header + 3);
1234 if (client->code < 20 || client->code > 29) {
1235 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1236 return;
1240 bufferevent_write_buffer(client->bev, src);
1243 static void
1244 cgi_write(struct bufferevent *bev, void *d)
1247 * Never called. We don't send data to a CGI script.
1249 abort();
1252 static void
1253 cgi_error(struct bufferevent *bev, short error, void *d)
1255 struct client *client = d;
1257 if (error & EVBUFFER_ERROR)
1258 log_err(client, "%s: evbuffer error (%x): %s",
1259 __func__, error, strerror(errno));
1261 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1262 bufferevent_free(bev);
1263 client->cgibev = NULL;
1265 close(client->pfd);
1266 client->pfd = -1;
1268 client->type = REQUEST_DONE;
1269 if (client->code != 0)
1270 client_write(client->bev, client);
1271 else
1272 start_reply(client, CGI_ERROR, "CGI error");
1275 static void
1276 do_accept(int sock, short et, void *d)
1278 struct client *c;
1279 struct sockaddr_storage addr;
1280 struct sockaddr *saddr;
1281 socklen_t len;
1282 int fd;
1284 saddr = (struct sockaddr*)&addr;
1285 len = sizeof(addr);
1286 if ((fd = accept(sock, saddr, &len)) == -1) {
1287 if (errno == EWOULDBLOCK || errno == EAGAIN)
1288 return;
1289 fatal("accept: %s", strerror(errno));
1292 mark_nonblock(fd);
1294 c = xcalloc(1, sizeof(*c));
1295 c->id = ++server_client_id;
1296 c->fd = fd;
1297 c->pfd = -1;
1298 c->addr = addr;
1300 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1301 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1302 close(c->fd);
1303 free(c);
1304 return;
1307 SPLAY_INSERT(client_tree_id, &clients, c);
1308 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1309 connected_clients++;
1312 static struct client *
1313 client_by_id(int id)
1315 struct client *c;
1317 if ((c = try_client_by_id(id)) == NULL)
1318 fatal("in client_by_id: invalid id %d", id);
1319 return c;
1322 struct client *
1323 try_client_by_id(int id)
1325 struct client find;
1327 find.id = id;
1328 return SPLAY_FIND(client_tree_id, &clients, &find);
1331 static void
1332 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1334 struct client *c;
1336 c = client_by_id(imsg->hdr.peerid);
1338 if ((c->pfd = imsg->fd) == -1) {
1339 start_reply(c, TEMP_FAILURE, "internal server error");
1340 return;
1343 c->type = REQUEST_CGI;
1345 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1346 cgi_error, c);
1348 bufferevent_enable(c->cgibev, EV_READ);
1351 static void
1352 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1354 struct client *c;
1355 int id;
1357 id = imsg->hdr.peerid;
1359 if ((c = try_client_by_id(id)) == NULL) {
1360 if (imsg->fd != -1)
1361 close(imsg->fd);
1362 return;
1365 if ((c->pfd = imsg->fd) == -1) {
1366 start_reply(c, CGI_ERROR, "CGI error");
1367 return;
1370 mark_nonblock(c->pfd);
1372 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1373 fcgi_error, c);
1374 if (c->cgibev == NULL) {
1375 start_reply(c, TEMP_FAILURE, "internal server error");
1376 return;
1379 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1380 fcgi_req(c);
1383 static void
1384 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1387 * don't call event_loopbreak since we want to finish to
1388 * handle the ongoing connections.
1391 shutting_down = 1;
1393 event_del(&e4);
1394 if (has_ipv6)
1395 event_del(&e6);
1396 if (has_siginfo)
1397 signal_del(&siginfo);
1398 event_del(&imsgev);
1399 signal_del(&sigusr2);
1402 static void
1403 handle_dispatch_imsg(int fd, short ev, void *d)
1405 struct imsgbuf *ibuf = d;
1406 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1409 static void
1410 handle_siginfo(int fd, short ev, void *d)
1412 log_info(NULL, "%d connected clients", connected_clients);
1415 void
1416 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1418 ctx = ctx_;
1420 SPLAY_INIT(&clients);
1422 event_init();
1424 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1425 event_add(&e4, NULL);
1427 if (sock6 != -1) {
1428 has_ipv6 = 1;
1429 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1430 event_add(&e6, NULL);
1433 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1434 event_add(&imsgev, NULL);
1436 #ifdef SIGINFO
1437 has_siginfo = 1;
1438 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1439 signal_add(&siginfo, NULL);
1440 #endif
1441 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1442 signal_add(&sigusr2, NULL);
1444 sandbox_server_process();
1445 event_dispatch();
1446 _exit(0);
1449 int
1450 client_tree_cmp(struct client *a, struct client *b)
1452 if (a->id == b->id)
1453 return 0;
1454 else if (a->id < b->id)
1455 return -1;
1456 else
1457 return +1;
1460 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)