2 * Copyright (c) 2021, 2022 Omar Polo <op@omarpolo.com>
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.
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.
34 #define MIN(a, b) ((a) < (b) ? (a) : (b))
38 static struct tls *ctx;
40 static struct event e4, e6, imsgev, siginfo, sigusr2;
41 static int has_ipv6, has_siginfo;
43 int connected_clients;
45 static inline int matches(const char*, const char*);
47 static int check_path(struct client*, const char*, int*);
48 static void open_file(struct client*);
49 static void handle_handshake(int, short, void*);
50 static const char *strip_path(const char*, int);
51 static void fmt_sbuf(const char*, struct client*, const char*);
52 static int apply_block_return(struct client*);
53 static int check_matching_certificate(X509_STORE *, struct client *);
54 static int apply_reverse_proxy(struct client *);
55 static int apply_fastcgi(struct client*);
56 static int apply_require_ca(struct client*);
57 static void open_dir(struct client*);
58 static void redirect_canonical_dir(struct client*);
60 static void client_tls_readcb(int, short, void *);
61 static void client_tls_writecb(int, short, void *);
63 static void client_read(struct bufferevent *, void *);
64 void client_write(struct bufferevent *, void *);
65 static void client_error(struct bufferevent *, short, void *);
67 static void client_close_ev(int, short, void *);
69 static void do_accept(int, short, void*);
71 static void handle_dispatch_imsg(int, short, void *);
72 static void handle_siginfo(int, short, void*);
74 static uint32_t server_client_id;
76 struct client_tree_id clients;
79 matches(const char *pattern, const char *path)
83 return !fnmatch(pattern, path, 0);
87 vhost_lang(struct vhost *v, const char *path)
91 if (v == NULL || path == NULL)
94 loc = TAILQ_FIRST(&v->locations);
95 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
96 if (*loc->lang != '\0') {
97 if (matches(loc->match, path))
102 loc = TAILQ_FIRST(&v->locations);
103 if (*loc->lang == '\0')
109 vhost_default_mime(struct vhost *v, const char *path)
111 struct location *loc;
112 const char *default_mime = "application/octet-stream";
114 if (v == NULL || path == NULL)
117 loc = TAILQ_FIRST(&v->locations);
118 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
119 if (*loc->default_mime != '\0') {
120 if (matches(loc->match, path))
121 return loc->default_mime;
125 loc = TAILQ_FIRST(&v->locations);
126 if (*loc->default_mime != '\0')
127 return loc->default_mime;
132 vhost_index(struct vhost *v, const char *path)
134 struct location *loc;
135 const char *index = "index.gmi";
137 if (v == NULL || path == NULL)
140 loc = TAILQ_FIRST(&v->locations);
141 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
142 if (*loc->index != '\0') {
143 if (matches(loc->match, path))
148 loc = TAILQ_FIRST(&v->locations);
149 if (*loc->index != '\0')
155 vhost_auto_index(struct vhost *v, const char *path)
157 struct location *loc;
159 if (v == NULL || path == NULL)
162 loc = TAILQ_FIRST(&v->locations);
163 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
164 if (loc->auto_index != 0) {
165 if (matches(loc->match, path))
166 return loc->auto_index == 1;
170 loc = TAILQ_FIRST(&v->locations);
171 return loc->auto_index == 1;
175 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
177 struct location *loc;
179 if (v == NULL || path == NULL)
182 loc = TAILQ_FIRST(&v->locations);
183 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
184 if (loc->block_code != 0) {
185 if (matches(loc->match, path)) {
186 *code = loc->block_code;
187 *fmt = loc->block_fmt;
193 loc = TAILQ_FIRST(&v->locations);
194 *code = loc->block_code;
195 *fmt = loc->block_fmt;
196 return loc->block_code != 0;
200 vhost_fastcgi(struct vhost *v, const char *path)
202 struct location *loc;
204 if (v == NULL || path == NULL)
207 loc = TAILQ_FIRST(&v->locations);
208 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
210 if (matches(loc->match, path))
214 loc = TAILQ_FIRST(&v->locations);
219 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
221 struct location *loc;
224 if (v == NULL || path == NULL)
227 loc = TAILQ_FIRST(&v->locations);
228 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
230 if (loc->dirfd != -1)
231 if (matches(loc->match, path)) {
238 loc = TAILQ_FIRST(&v->locations);
243 vhost_strip(struct vhost *v, const char *path)
245 struct location *loc;
247 if (v == NULL || path == NULL)
250 loc = TAILQ_FIRST(&v->locations);
251 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
252 if (loc->strip != 0) {
253 if (matches(loc->match, path))
258 loc = TAILQ_FIRST(&v->locations);
263 vhost_require_ca(struct vhost *v, const char *path)
265 struct location *loc;
267 if (v == NULL || path == NULL)
270 loc = TAILQ_FIRST(&v->locations);
271 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
272 if (loc->reqca != NULL) {
273 if (matches(loc->match, path))
278 loc = TAILQ_FIRST(&v->locations);
283 vhost_disable_log(struct vhost *v, const char *path)
285 struct location *loc;
287 if (v == NULL || path == NULL)
290 loc = TAILQ_FIRST(&v->locations);
291 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
292 if (loc->disable_log && matches(loc->match, path))
296 loc = TAILQ_FIRST(&v->locations);
297 return loc->disable_log;
301 check_path(struct client *c, const char *path, int *fd)
307 assert(path != NULL);
310 * in send_dir we add an initial / (to be redirect-friendly),
311 * but here we want to skip it
316 strip = vhost_strip(c->host, path);
317 p = strip_path(path, strip);
324 dirfd = vhost_dirfd(c->host, path, &c->loc);
325 log_debug("check_path: strip=%d path=%s original=%s",
327 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
329 log_info("can't open %s: %s", p, strerror(errno));
333 if (fstat(*fd, &sb) == -1) {
334 log_warn("fstat %s", path);
338 if (S_ISDIR(sb.st_mode))
339 return FILE_DIRECTORY;
345 open_file(struct client *c)
347 switch (check_path(c, c->iri.path, &c->pfd)) {
349 c->type = REQUEST_FILE;
350 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
358 start_reply(c, NOT_FOUND, "not found");
368 mark_nonblock(int fd)
372 if ((flags = fcntl(fd, F_GETFL)) == -1)
373 fatal("fcntl(F_GETFL)");
374 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
375 fatal("fcntl(F_SETFL)");
379 handle_handshake(int fd, short ev, void *d)
381 struct client *c = d;
384 const char *servname;
385 const char *parse_err = "unknown error";
387 switch (tls_handshake(c->ctx)) {
388 case 0: /* success */
389 case -1: /* already handshaked */
391 case TLS_WANT_POLLIN:
392 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
394 case TLS_WANT_POLLOUT:
395 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
402 c->bev = bufferevent_new(fd, client_read, client_write,
405 fatal("%s: failed to allocate client buffer", __func__);
407 event_set(&c->bev->ev_read, c->fd, EV_READ,
408 client_tls_readcb, c->bev);
409 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
410 client_tls_writecb, c->bev);
413 evbuffer_unfreeze(c->bev->input, 0);
414 evbuffer_unfreeze(c->bev->output, 1);
417 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
418 log_debug("handshake: missing SNI");
422 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
423 log_info("puny_decode: %s", parse_err);
427 TAILQ_FOREACH(h, &hosts, vhosts) {
428 if (matches(h->domain, c->domain))
430 TAILQ_FOREACH(a, &h->aliases, aliases) {
431 if (matches(a->alias, c->domain))
437 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
438 servname != NULL ? servname : "(null)",
440 h != NULL ? h->domain : "(null)");
444 bufferevent_enable(c->bev, EV_READ);
449 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
453 strip_path(const char *path, int strip)
458 if ((t = strchr(path, '/')) == NULL) {
459 path = strchr(path, '\0');
470 fmt_sbuf(const char *fmt, struct client *c, const char *path)
475 memset(buf, 0, sizeof(buf));
476 for (i = 0; *fmt; ++fmt) {
477 if (i == sizeof(buf)-1 || *fmt == '%') {
478 strlcat(c->sbuf, buf, sizeof(c->sbuf));
479 memset(buf, 0, sizeof(buf));
490 strlcat(c->sbuf, "%", sizeof(c->sbuf));
494 strlcat(c->sbuf, "/", sizeof(c->sbuf));
495 strlcat(c->sbuf, path, sizeof(c->sbuf));
498 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
501 snprintf(buf, sizeof(buf), "%d", conf.port);
502 strlcat(c->sbuf, buf, sizeof(c->sbuf));
503 memset(buf, 0, sizeof(buf));
506 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
509 fatalx("%s: unknown fmt specifier %c",
515 strlcat(c->sbuf, buf, sizeof(c->sbuf));
518 /* 1 if a matching `block return' (and apply it), 0 otherwise */
520 apply_block_return(struct client *c)
522 const char *fmt, *path;
525 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
528 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
529 fmt_sbuf(fmt, c, path);
531 start_reply(c, code, c->sbuf);
535 static struct proxy *
536 matched_proxy(struct client *c)
543 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
544 if (*(proto = p->match_proto) == '\0')
546 if (*(host = p->match_host) == '\0')
548 if (*(port = p->match_port) == '\0')
551 if (matches(proto, c->iri.schema) &&
552 matches(host, c->domain) &&
553 matches(port, c->iri.port))
561 check_matching_certificate(X509_STORE *store, struct client *c)
566 if (!tls_peer_cert_provided(c->ctx)) {
567 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
571 cert = tls_peer_cert_chain_pem(c->ctx, &len);
572 if (!validate_against_ca(store, cert, len)) {
573 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
581 proxy_socket(struct client *c, const char *host, const char *port)
583 struct addrinfo hints, *res, *res0;
584 int r, sock, save_errno;
585 const char *cause = NULL;
587 memset(&hints, 0, sizeof(hints));
588 hints.ai_family = AF_UNSPEC;
589 hints.ai_socktype = SOCK_STREAM;
591 /* XXX: asr_run? :> */
592 r = getaddrinfo(host, port, &hints, &res0);
594 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
595 host, port, gai_strerror(r));
599 for (res = res0; res; res = res->ai_next) {
600 sock = socket(res->ai_family, res->ai_socktype,
607 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
620 log_warn("can't connect to %s:%s: %s", host, port, cause);
627 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
629 apply_reverse_proxy(struct client *c)
633 if ((p = matched_proxy(c)) == NULL)
638 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
641 log_debug("opening proxy connection for %s:%s",
644 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
645 start_reply(c, PROXY_ERROR, "proxy error");
649 mark_nonblock(c->pfd);
650 if (proxy_init(c) == -1)
651 start_reply(c, PROXY_ERROR, "proxy error");
657 fcgi_open_sock(struct fcgi *f)
659 struct sockaddr_un addr;
662 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
667 memset(&addr, 0, sizeof(addr));
668 addr.sun_family = AF_UNIX;
669 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
671 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
672 log_warn("failed to connect to %s", f->path);
681 fcgi_open_conn(struct fcgi *f)
683 struct addrinfo hints, *servinfo, *p;
684 int r, sock, save_errno;
685 const char *cause = NULL;
687 memset(&hints, 0, sizeof(hints));
688 hints.ai_family = AF_UNSPEC;
689 hints.ai_socktype = SOCK_STREAM;
690 hints.ai_flags = AI_ADDRCONFIG;
692 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
693 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
698 for (p = servinfo; p != NULL; p = p->ai_next) {
699 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
704 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
715 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
720 freeaddrinfo(servinfo);
724 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
726 apply_fastcgi(struct client *c)
731 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
736 log_debug("opening fastcgi connection for (%s,%s)",
739 if (*f->port == '\0')
740 c->pfd = fcgi_open_sock(f);
742 c->pfd = fcgi_open_conn(f);
745 start_reply(c, CGI_ERROR, "CGI error");
749 mark_nonblock(c->pfd);
751 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
753 if (c->cgibev == NULL) {
754 start_reply(c, TEMP_FAILURE, "internal server error");
758 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
764 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
766 apply_require_ca(struct client *c)
770 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
772 return check_matching_certificate(store, c);
776 open_dir(struct client *c)
782 log_debug("in open_dir");
784 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
786 len = strlen(c->iri.path);
787 if (len > 0 && !ends_with(c->iri.path, "/")) {
788 redirect_canonical_dir(c);
792 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
793 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
794 if (!ends_with(c->sbuf, "/"))
795 strlcat(c->sbuf, "/", sizeof(c->sbuf));
796 before_file = strchr(c->sbuf, '\0');
797 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
799 if (len >= sizeof(c->sbuf)) {
800 start_reply(c, TEMP_FAILURE, "internal server error");
804 c->iri.path = c->sbuf;
806 /* close later unless we have to generate the dir listing */
810 switch (check_path(c, c->iri.path, &c->pfd)) {
812 c->type = REQUEST_FILE;
813 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
817 start_reply(c, TEMP_REDIRECT, c->sbuf);
823 if (!vhost_auto_index(c->host, c->iri.path)) {
824 start_reply(c, NOT_FOUND, "not found");
828 c->type = REQUEST_DIR;
830 c->dirlen = scandir_fd(dirfd, &c->dir,
831 root ? select_non_dotdot : select_non_dot,
833 if (c->dirlen == -1) {
834 log_warn("scandir_fd(%d) (vhost:%s) %s",
835 c->pfd, c->host->domain, c->iri.path);
836 start_reply(c, TEMP_FAILURE, "internal server error");
842 start_reply(c, SUCCESS, "text/gemini");
843 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
844 "# Index of %s\n\n", c->iri.path);
856 redirect_canonical_dir(struct client *c)
860 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
861 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
862 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
864 if (len >= sizeof(c->sbuf)) {
865 start_reply(c, TEMP_FAILURE, "internal server error");
869 start_reply(c, TEMP_REDIRECT, c->sbuf);
873 client_tls_readcb(int fd, short event, void *d)
875 struct bufferevent *bufev = d;
876 struct client *client = bufev->cbarg;
879 int what = EVBUFFER_READ;
880 int howmuch = IBUF_READ_SIZE;
881 char buf[IBUF_READ_SIZE];
883 if (event == EV_TIMEOUT) {
884 what |= EVBUFFER_TIMEOUT;
888 if (bufev->wm_read.high != 0)
889 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
891 switch (ret = tls_read(client->ctx, buf, howmuch)) {
892 case TLS_WANT_POLLIN:
893 case TLS_WANT_POLLOUT:
896 what |= EVBUFFER_ERROR;
902 what |= EVBUFFER_EOF;
906 if (evbuffer_add(bufev->input, buf, len) == -1) {
907 what |= EVBUFFER_ERROR;
911 event_add(&bufev->ev_read, NULL);
912 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
914 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
916 * here we could implement a read pressure policy.
920 if (bufev->readcb != NULL)
921 (*bufev->readcb)(bufev, bufev->cbarg);
926 event_add(&bufev->ev_read, NULL);
930 (*bufev->errorcb)(bufev, what, bufev->cbarg);
934 client_tls_writecb(int fd, short event, void *d)
936 struct bufferevent *bufev = d;
937 struct client *client = bufev->cbarg;
940 short what = EVBUFFER_WRITE;
942 if (event == EV_TIMEOUT) {
943 what |= EVBUFFER_TIMEOUT;
947 if (EVBUFFER_LENGTH(bufev->output) != 0) {
948 ret = tls_write(client->ctx,
949 EVBUFFER_DATA(bufev->output),
950 EVBUFFER_LENGTH(bufev->output));
952 case TLS_WANT_POLLIN:
953 case TLS_WANT_POLLOUT:
956 what |= EVBUFFER_ERROR;
960 evbuffer_drain(bufev->output, len);
963 if (EVBUFFER_LENGTH(bufev->output) != 0)
964 event_add(&bufev->ev_write, NULL);
966 if (bufev->writecb != NULL &&
967 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
968 (*bufev->writecb)(bufev, bufev->cbarg);
972 event_add(&bufev->ev_write, NULL);
975 log_warnx("tls error: %s", tls_error(client->ctx));
976 (*bufev->errorcb)(bufev, what, bufev->cbarg);
980 client_read(struct bufferevent *bev, void *d)
982 struct client *c = d;
983 struct evbuffer *src = EVBUFFER_INPUT(bev);
984 const char *parse_err = "invalid request";
985 char decoded[DOMAIN_NAME_LEN];
988 bufferevent_disable(bev, EVBUFFER_READ);
991 * libevent2 can still somehow call this function, even
992 * though I never enable EV_READ in the bufferevent. If
993 * that's the case, bail out.
995 if (c->type != REQUEST_UNDECIDED)
998 /* max url len + \r\n */
999 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1000 log_debug("too much data received");
1001 start_reply(c, BAD_REQUEST, "bad request");
1005 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1006 if (c->req == NULL) {
1007 /* not enough data yet. */
1008 bufferevent_enable(bev, EVBUFFER_READ);
1011 c->reqlen = strlen(c->req);
1012 if (c->reqlen > 1024+2) {
1013 log_debug("URL too long");
1014 start_reply(c, BAD_REQUEST, "bad request");
1018 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1019 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1020 log_debug("IRI parse error: %s", parse_err);
1021 start_reply(c, BAD_REQUEST, "bad request");
1025 if (apply_reverse_proxy(c))
1028 /* ignore the port number */
1029 if (strcmp(c->iri.schema, "gemini") ||
1030 strcmp(decoded, c->domain)) {
1031 start_reply(c, PROXY_REFUSED, "won't proxy request");
1035 if (apply_require_ca(c) ||
1036 apply_block_return(c)||
1044 client_write(struct bufferevent *bev, void *d)
1046 struct client *c = d;
1047 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1053 case REQUEST_UNDECIDED:
1055 * Ignore spurious calls when we still don't have idea
1056 * what to do with the request.
1061 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1063 client_error(bev, EVBUFFER_ERROR, c);
1065 } else if (r == 0) {
1068 } else if (r != sizeof(buf))
1069 c->type = REQUEST_DONE;
1070 bufferevent_write(bev, buf, r);
1074 /* TODO: handle big big directories better */
1075 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1076 const char *sufx = "";
1078 encode_path(nam, sizeof(nam),
1079 c->dir[c->diroff]->d_name);
1080 if (c->dir[c->diroff]->d_type == DT_DIR)
1082 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1083 free(c->dir[c->diroff]);
1088 c->type = REQUEST_DONE;
1090 event_add(&c->bev->ev_write, NULL);
1096 * Here we depend on fastcgi or proxy connection to
1102 if (EVBUFFER_LENGTH(out) == 0)
1109 client_error(struct bufferevent *bev, short error, void *d)
1111 struct client *c = d;
1113 c->type = REQUEST_DONE;
1115 if (error & EVBUFFER_TIMEOUT) {
1116 log_debug("timeout; forcefully closing the connection");
1118 start_reply(c, BAD_REQUEST, "timeout");
1124 if (error & EVBUFFER_EOF) {
1129 log_warnx("unknown bufferevent error 0x%x", error);
1134 start_reply(struct client *c, int code, const char *meta)
1136 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1140 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1145 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1149 /* 2 digit status + space + 1024 max reply */
1153 if (c->type != REQUEST_FCGI &&
1154 c->type != REQUEST_PROXY &&
1155 !strcmp(meta, "text/gemini") &&
1156 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1157 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1164 bufferevent_write(c->bev, "\r\n", 2);
1166 if (!vhost_disable_log(c->host, c->iri.path))
1167 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1170 c->type = REQUEST_DONE;
1175 log_warnx("evbuffer_add_printf error: no memory");
1176 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1181 log_warnx("reply header overflow");
1182 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1183 start_reply(c, TEMP_FAILURE, "internal error");
1187 client_close_ev(int fd, short event, void *d)
1189 struct client *c = d;
1191 switch (tls_close(c->ctx)) {
1192 case TLS_WANT_POLLIN:
1193 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1195 case TLS_WANT_POLLOUT:
1196 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1200 connected_clients--;
1220 client_proxy_close(int fd, short event, void *d)
1222 struct tls *ctx = d;
1229 switch (tls_close(ctx)) {
1230 case TLS_WANT_POLLIN:
1231 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1233 case TLS_WANT_POLLOUT:
1234 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1243 client_close(struct client *c)
1246 * We may end up calling client_close in various situations
1247 * and for the most unexpected reasons. Therefore, we need to
1248 * ensure that everything gets properly released once we reach
1252 SPLAY_REMOVE(client_tree_id, &clients, c);
1254 if (c->cgibev != NULL) {
1255 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1256 bufferevent_free(c->cgibev);
1262 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1263 bufferevent_free(c->bev);
1266 if (c->proxyevset &&
1267 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1269 event_del(&c->proxyev);
1272 if (c->pfd != -1 && c->proxyctx != NULL) {
1273 /* shut down the proxy TLS connection */
1274 client_proxy_close(c->pfd, 0, c->proxyctx);
1278 if (c->proxybev != NULL)
1279 bufferevent_free(c->proxybev);
1281 client_close_ev(c->fd, 0, c);
1285 do_accept(int sock, short et, void *d)
1288 struct sockaddr_storage addr;
1289 struct sockaddr *saddr;
1293 saddr = (struct sockaddr*)&addr;
1295 if ((fd = accept(sock, saddr, &len)) == -1) {
1296 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1297 errno == ECONNABORTED)
1304 c = xcalloc(1, sizeof(*c));
1305 c->id = ++server_client_id;
1310 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1311 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1317 SPLAY_INSERT(client_tree_id, &clients, c);
1318 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1319 connected_clients++;
1323 client_by_id(int id)
1328 return SPLAY_FIND(client_tree_id, &clients, &find);
1332 handle_dispatch_imsg(int fd, short ev, void *d)
1334 struct imsgbuf *ibuf = d;
1338 if ((n = imsg_read(ibuf)) == -1) {
1339 if (errno == EAGAIN || errno == EWOULDBLOCK)
1345 fatalx("connection closed.");
1348 if ((n = imsg_get(ibuf, &imsg)) == -1)
1353 switch (imsg.hdr.type) {
1356 * Don't call event_loopbreak since we want to
1357 * finish handling the ongoing connections.
1365 signal_del(&siginfo);
1367 signal_del(&sigusr2);
1370 fatalx("Unknown message %d", imsg.hdr.type);
1377 handle_siginfo(int fd, short ev, void *d)
1379 log_info("%d connected clients", connected_clients);
1383 loop(int sock4, int sock6, struct imsgbuf *ibuf)
1385 SPLAY_INIT(&clients);
1389 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1390 event_add(&e4, NULL);
1394 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1395 event_add(&e6, NULL);
1399 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1400 handle_dispatch_imsg, ibuf);
1401 event_add(&imsgev, NULL);
1406 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1407 signal_add(&siginfo, NULL);
1409 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1410 signal_add(&sigusr2, NULL);
1412 sandbox_server_process();
1418 add_keypair(struct vhost *h, struct tls_config *conf)
1420 if (*h->ocsp == '\0') {
1421 if (tls_config_add_keypair_file(conf, h->cert, h->key) == -1)
1422 fatalx("failed to load the keypair (%s, %s): %s",
1423 h->cert, h->key, tls_config_error(conf));
1425 if (tls_config_add_keypair_ocsp_file(conf, h->cert, h->key,
1427 fatalx("failed to load the keypair (%s, %s, %s): %s",
1428 h->cert, h->key, h->ocsp,
1429 tls_config_error(conf));
1434 * XXX: in a ideal privsep world, this is done by the parent process
1435 * and its content sent to us.
1440 struct tls_config *tlsconf;
1443 if ((tlsconf = tls_config_new()) == NULL)
1444 fatal("tls_config_new");
1446 /* optionally accept client certs, but don't try to verify them */
1447 tls_config_verify_client_optional(tlsconf);
1448 tls_config_insecure_noverifycert(tlsconf);
1450 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
1451 fatalx("tls_config_set_protocols: %s",
1452 tls_config_error(tlsconf));
1454 h = TAILQ_FIRST(&hosts);
1456 log_info("loading %s, %s, %s", h->cert, h->key, h->ocsp);
1458 /* we need to set something, then we can add how many key we want */
1459 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
1460 fatalx("tls_config_set_keypair_file failed for (%s, %s): %s",
1461 h->cert, h->key, tls_config_error(tlsconf));
1464 if (*h->ocsp != '\0' &&
1465 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
1466 fatalx("tls_config_set_ocsp_staple_file failed for (%s): %s",
1467 h->ocsp, tls_config_error(tlsconf));
1469 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1470 add_keypair(h, tlsconf);
1472 if ((ctx = tls_server()) == NULL)
1473 fatal("tls_server failure");
1475 if (tls_configure(ctx, tlsconf) == -1)
1476 fatalx("tls_configure: %s", tls_error(ctx));
1478 tls_config_free(tlsconf);
1487 TAILQ_FOREACH(h, &hosts, vhosts) {
1488 TAILQ_FOREACH(l, &h->locations, locations) {
1489 if (*l->dir == '\0')
1491 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1493 fatal("open %s for domain %s", l->dir,
1500 server_main(struct imsgbuf *ibuf, int sock4, int sock6)
1503 * setup tls before dropping privileges: we don't want user
1504 * to put private certs inside the chroot.
1508 if (load_default_mime(&conf.mime) == -1)
1509 fatal("can't load default mime");
1510 sort_mime(&conf.mime);
1512 loop(sock4, sock6, ibuf);
1517 client_tree_cmp(struct client *a, struct client *b)
1521 else if (a->id < b->id)
1527 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)