2 * Copyright (c) 2021, 2022, 2023 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))
37 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
41 static struct event siginfo;
43 static struct event sigusr2;
45 int connected_clients;
48 * This function is not publicy exported because it is a hack until libtls
49 * has a proper privsep setup.
51 void tls_config_use_fake_private_key(struct tls_config *);
53 static inline int matches(const char*, const char*);
55 static int check_path(struct client*, const char*, int*);
56 static void open_file(struct client*);
57 static void handle_handshake(int, short, void*);
58 static const char *strip_path(const char*, int);
59 static void fmt_sbuf(const char*, struct client*, const char*);
60 static int apply_block_return(struct client*);
61 static int check_matching_certificate(X509_STORE *, struct client *);
62 static int apply_reverse_proxy(struct client *);
63 static int apply_fastcgi(struct client*);
64 static int apply_require_ca(struct client*);
65 static void open_dir(struct client*);
66 static void redirect_canonical_dir(struct client*);
68 static void client_tls_readcb(int, short, void *);
69 static void client_tls_writecb(int, short, void *);
71 static void client_read(struct bufferevent *, void *);
72 void client_write(struct bufferevent *, void *);
73 static void client_error(struct bufferevent *, short, void *);
75 static void client_close_ev(int, short, void *);
77 static void handle_siginfo(int, short, void*);
79 static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
80 static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
81 static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
83 static struct privsep_proc procs[] = {
84 { "parent", PROC_PARENT, server_dispatch_parent },
85 { "crypto", PROC_CRYPTO, server_dispatch_crypto },
86 { "logger", PROC_LOGGER, server_dispatch_logger },
89 static uint32_t server_client_id;
91 struct client_tree_id clients;
94 match_addr(struct address *target, struct address *source)
96 return (target->ai_flags == source->ai_flags &&
97 target->ai_family == source->ai_family &&
98 target->ai_socktype == source->ai_socktype &&
99 target->ai_protocol == source->ai_protocol &&
100 target->slen == source->slen &&
101 !memcmp(&target->ss, &source->ss, target->slen));
105 matches(const char *pattern, const char *path)
109 return !fnmatch(pattern, path, 0);
113 match_host(struct vhost *v, struct client *c)
116 struct address *addr;
118 TAILQ_FOREACH(addr, &v->addrs, addrs)
119 if (match_addr(addr, c->addr))
124 if (matches(v->domain, c->domain))
127 TAILQ_FOREACH(a, &v->aliases, aliases)
128 if (matches(a->alias, c->domain))
135 vhost_lang(struct vhost *v, const char *path)
137 struct location *loc;
139 if (v == NULL || path == NULL)
142 loc = TAILQ_FIRST(&v->locations);
143 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
144 if (*loc->lang != '\0') {
145 if (matches(loc->match, path))
150 loc = TAILQ_FIRST(&v->locations);
151 if (*loc->lang == '\0')
157 vhost_default_mime(struct vhost *v, const char *path)
159 struct location *loc;
160 const char *default_mime = "application/octet-stream";
162 if (v == NULL || path == NULL)
165 loc = TAILQ_FIRST(&v->locations);
166 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
167 if (*loc->default_mime != '\0') {
168 if (matches(loc->match, path))
169 return loc->default_mime;
173 loc = TAILQ_FIRST(&v->locations);
174 if (*loc->default_mime != '\0')
175 return loc->default_mime;
180 vhost_index(struct vhost *v, const char *path)
182 struct location *loc;
183 const char *index = "index.gmi";
185 if (v == NULL || path == NULL)
188 loc = TAILQ_FIRST(&v->locations);
189 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
190 if (*loc->index != '\0') {
191 if (matches(loc->match, path))
196 loc = TAILQ_FIRST(&v->locations);
197 if (*loc->index != '\0')
203 vhost_auto_index(struct vhost *v, const char *path)
205 struct location *loc;
207 if (v == NULL || path == NULL)
210 loc = TAILQ_FIRST(&v->locations);
211 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
212 if (loc->auto_index != 0) {
213 if (matches(loc->match, path))
214 return loc->auto_index == 1;
218 loc = TAILQ_FIRST(&v->locations);
219 return loc->auto_index == 1;
223 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
225 struct location *loc;
227 if (v == NULL || path == NULL)
230 loc = TAILQ_FIRST(&v->locations);
231 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
232 if (loc->block_code != 0) {
233 if (matches(loc->match, path)) {
234 *code = loc->block_code;
235 *fmt = loc->block_fmt;
241 loc = TAILQ_FIRST(&v->locations);
242 *code = loc->block_code;
243 *fmt = loc->block_fmt;
244 return loc->block_code != 0;
248 vhost_fastcgi(struct vhost *v, const char *path)
250 struct location *loc;
252 if (v == NULL || path == NULL)
255 loc = TAILQ_FIRST(&v->locations);
256 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
258 if (matches(loc->match, path))
262 loc = TAILQ_FIRST(&v->locations);
267 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
269 struct location *loc;
272 if (v == NULL || path == NULL)
275 loc = TAILQ_FIRST(&v->locations);
276 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
278 if (loc->dirfd != -1)
279 if (matches(loc->match, path)) {
286 loc = TAILQ_FIRST(&v->locations);
291 vhost_strip(struct vhost *v, const char *path)
293 struct location *loc;
295 if (v == NULL || path == NULL)
298 loc = TAILQ_FIRST(&v->locations);
299 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
300 if (loc->strip != 0) {
301 if (matches(loc->match, path))
306 loc = TAILQ_FIRST(&v->locations);
311 vhost_require_ca(struct vhost *v, const char *path)
313 struct location *loc;
315 if (v == NULL || path == NULL)
318 loc = TAILQ_FIRST(&v->locations);
319 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
320 if (loc->reqca != NULL) {
321 if (matches(loc->match, path))
326 loc = TAILQ_FIRST(&v->locations);
331 vhost_disable_log(struct vhost *v, const char *path)
333 struct location *loc;
335 if (v == NULL || path == NULL)
338 loc = TAILQ_FIRST(&v->locations);
339 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
340 if (loc->disable_log && matches(loc->match, path))
344 loc = TAILQ_FIRST(&v->locations);
345 return loc->disable_log;
349 check_path(struct client *c, const char *path, int *fd)
355 assert(path != NULL);
358 * in send_dir we add an initial / (to be redirect-friendly),
359 * but here we want to skip it
364 strip = vhost_strip(c->host, path);
365 p = strip_path(path, strip);
372 dirfd = vhost_dirfd(c->host, path, &c->loc);
373 log_debug("check_path: strip=%d path=%s original=%s",
375 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
377 log_info("can't open %s: %s", p, strerror(errno));
381 if (fstat(*fd, &sb) == -1) {
382 log_warn("fstat %s", path);
386 if (S_ISDIR(sb.st_mode))
387 return FILE_DIRECTORY;
393 open_file(struct client *c)
395 switch (check_path(c, c->iri.path, &c->pfd)) {
397 c->type = REQUEST_FILE;
398 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
406 start_reply(c, NOT_FOUND, "not found");
416 mark_nonblock(int fd)
420 if ((flags = fcntl(fd, F_GETFL)) == -1)
421 fatal("fcntl(F_GETFL)");
422 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
423 fatal("fcntl(F_SETFL)");
427 handle_handshake(int fd, short ev, void *d)
429 struct client *c = d;
430 struct conf *conf = c->conf;
432 const char *servname;
433 const char *parse_err = "unknown error";
435 switch (tls_handshake(c->ctx)) {
436 case 0: /* success */
439 log_warnx("tls_handshake failed: %s", tls_error(c->ctx));
442 case TLS_WANT_POLLIN:
443 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
445 case TLS_WANT_POLLOUT:
446 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
453 c->bev = bufferevent_new(fd, client_read, client_write,
456 fatal("%s: failed to allocate client buffer", __func__);
458 event_set(&c->bev->ev_read, c->fd, EV_READ,
459 client_tls_readcb, c->bev);
460 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
461 client_tls_writecb, c->bev);
464 evbuffer_unfreeze(c->bev->input, 0);
465 evbuffer_unfreeze(c->bev->output, 1);
468 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
469 log_debug("handshake: missing SNI");
473 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
474 log_info("puny_decode: %s", parse_err);
478 TAILQ_FOREACH(h, &conf->hosts, vhosts)
479 if (match_host(h, c))
482 log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
483 servname != NULL ? servname : "(null)",
485 h != NULL ? h->domain : "(null)");
489 bufferevent_enable(c->bev, EV_READ);
494 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
498 strip_path(const char *path, int strip)
503 if ((t = strchr(path, '/')) == NULL) {
504 path = strchr(path, '\0');
515 fmt_sbuf(const char *fmt, struct client *c, const char *path)
520 memset(buf, 0, sizeof(buf));
521 for (i = 0; *fmt; ++fmt) {
522 if (i == sizeof(buf)-1 || *fmt == '%') {
523 strlcat(c->sbuf, buf, sizeof(c->sbuf));
524 memset(buf, 0, sizeof(buf));
535 strlcat(c->sbuf, "%", sizeof(c->sbuf));
539 strlcat(c->sbuf, "/", sizeof(c->sbuf));
540 strlcat(c->sbuf, path, sizeof(c->sbuf));
543 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
546 snprintf(buf, sizeof(buf), "%d", c->addr->port);
547 strlcat(c->sbuf, buf, sizeof(c->sbuf));
548 memset(buf, 0, sizeof(buf));
551 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
554 fatalx("%s: unknown fmt specifier %c",
560 strlcat(c->sbuf, buf, sizeof(c->sbuf));
563 /* 1 if a matching `block return' (and apply it), 0 otherwise */
565 apply_block_return(struct client *c)
567 const char *fmt, *path;
570 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
573 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
574 fmt_sbuf(fmt, c, path);
576 start_reply(c, code, c->sbuf);
580 static struct proxy *
581 matched_proxy(struct client *c)
588 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
589 if (*(proto = p->match_proto) == '\0')
591 if (*(host = p->match_host) == '\0')
593 if (*(port = p->match_port) == '\0')
596 if (matches(proto, c->iri.schema) &&
597 matches(host, c->domain) &&
598 matches(port, c->iri.port))
606 check_matching_certificate(X509_STORE *store, struct client *c)
611 if (!tls_peer_cert_provided(c->ctx)) {
612 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
616 cert = tls_peer_cert_chain_pem(c->ctx, &len);
617 if (!validate_against_ca(store, cert, len)) {
618 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
626 proxy_socket(struct client *c, const char *host, const char *port)
628 struct addrinfo hints, *res, *res0;
629 int r, sock, save_errno;
630 const char *cause = NULL;
632 memset(&hints, 0, sizeof(hints));
633 hints.ai_family = AF_UNSPEC;
634 hints.ai_socktype = SOCK_STREAM;
636 /* XXX: asr_run? :> */
637 r = getaddrinfo(host, port, &hints, &res0);
639 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
640 host, port, gai_strerror(r));
644 for (res = res0; res; res = res->ai_next) {
645 sock = socket(res->ai_family, res->ai_socktype,
652 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
665 log_warn("can't connect to %s:%s: %s", host, port, cause);
672 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
674 apply_reverse_proxy(struct client *c)
678 if ((p = matched_proxy(c)) == NULL)
683 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
686 log_debug("opening proxy connection for %s:%s",
689 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
690 start_reply(c, PROXY_ERROR, "proxy error");
694 mark_nonblock(c->pfd);
695 if (proxy_init(c) == -1)
696 start_reply(c, PROXY_ERROR, "proxy error");
702 fcgi_open_sock(struct fcgi *f)
704 struct sockaddr_un addr;
707 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
712 memset(&addr, 0, sizeof(addr));
713 addr.sun_family = AF_UNIX;
714 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
716 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
717 log_warn("failed to connect to %s", f->path);
726 fcgi_open_conn(struct fcgi *f)
728 struct addrinfo hints, *servinfo, *p;
729 int r, sock, save_errno;
730 const char *cause = NULL;
732 memset(&hints, 0, sizeof(hints));
733 hints.ai_family = AF_UNSPEC;
734 hints.ai_socktype = SOCK_STREAM;
735 hints.ai_flags = AI_ADDRCONFIG;
737 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
738 log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
743 for (p = servinfo; p != NULL; p = p->ai_next) {
744 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
749 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
760 log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
765 freeaddrinfo(servinfo);
769 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
771 apply_fastcgi(struct client *c)
776 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
779 TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
786 log_warnx("can't find fcgi #%d", id);
790 log_debug("opening fastcgi connection for (%s,%s)",
793 if (*f->port == '\0')
794 c->pfd = fcgi_open_sock(f);
796 c->pfd = fcgi_open_conn(f);
799 start_reply(c, CGI_ERROR, "CGI error");
803 mark_nonblock(c->pfd);
805 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
807 if (c->cgibev == NULL) {
808 start_reply(c, TEMP_FAILURE, "internal server error");
812 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
818 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
820 apply_require_ca(struct client *c)
824 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
826 return check_matching_certificate(store, c);
830 open_dir(struct client *c)
836 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
838 len = strlen(c->iri.path);
839 if (len > 0 && !ends_with(c->iri.path, "/")) {
840 redirect_canonical_dir(c);
844 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
845 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
846 if (!ends_with(c->sbuf, "/"))
847 strlcat(c->sbuf, "/", sizeof(c->sbuf));
848 before_file = strchr(c->sbuf, '\0');
849 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
851 if (len >= sizeof(c->sbuf)) {
852 start_reply(c, TEMP_FAILURE, "internal server error");
856 c->iri.path = c->sbuf;
858 /* close later unless we have to generate the dir listing */
862 switch (check_path(c, c->iri.path, &c->pfd)) {
864 c->type = REQUEST_FILE;
865 start_reply(c, SUCCESS, mime(c->conf, c->host, c->iri.path));
869 start_reply(c, TEMP_REDIRECT, c->sbuf);
875 if (!vhost_auto_index(c->host, c->iri.path)) {
876 start_reply(c, NOT_FOUND, "not found");
880 c->type = REQUEST_DIR;
882 c->dirlen = scandir_fd(dirfd, &c->dir,
883 root ? select_non_dotdot : select_non_dot,
885 if (c->dirlen == -1) {
886 log_warn("scandir_fd(%d) (vhost:%s) %s",
887 c->pfd, c->host->domain, c->iri.path);
888 start_reply(c, TEMP_FAILURE, "internal server error");
894 start_reply(c, SUCCESS, "text/gemini");
895 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
896 "# Index of %s\n\n", c->iri.path);
908 redirect_canonical_dir(struct client *c)
912 r = snprintf(c->sbuf, sizeof(c->sbuf), "/%s/", c->iri.path);
913 if (r < 0 || (size_t)r >= sizeof(c->sbuf)) {
914 start_reply(c, TEMP_FAILURE, "internal server error");
918 start_reply(c, TEMP_REDIRECT, c->sbuf);
922 client_tls_readcb(int fd, short event, void *d)
924 struct bufferevent *bufev = d;
925 struct client *client = bufev->cbarg;
928 int what = EVBUFFER_READ;
929 int howmuch = IBUF_READ_SIZE;
930 char buf[IBUF_READ_SIZE];
932 if (event == EV_TIMEOUT) {
933 what |= EVBUFFER_TIMEOUT;
937 if (bufev->wm_read.high != 0)
938 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
940 switch (ret = tls_read(client->ctx, buf, howmuch)) {
941 case TLS_WANT_POLLIN:
942 case TLS_WANT_POLLOUT:
945 what |= EVBUFFER_ERROR;
951 what |= EVBUFFER_EOF;
955 if (evbuffer_add(bufev->input, buf, len) == -1) {
956 what |= EVBUFFER_ERROR;
960 event_add(&bufev->ev_read, NULL);
961 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
963 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
965 * here we could implement a read pressure policy.
969 if (bufev->readcb != NULL)
970 (*bufev->readcb)(bufev, bufev->cbarg);
975 event_add(&bufev->ev_read, NULL);
979 (*bufev->errorcb)(bufev, what, bufev->cbarg);
983 client_tls_writecb(int fd, short event, void *d)
985 struct bufferevent *bufev = d;
986 struct client *client = bufev->cbarg;
989 short what = EVBUFFER_WRITE;
991 if (event == EV_TIMEOUT) {
992 what |= EVBUFFER_TIMEOUT;
996 if (EVBUFFER_LENGTH(bufev->output) != 0) {
997 ret = tls_write(client->ctx,
998 EVBUFFER_DATA(bufev->output),
999 EVBUFFER_LENGTH(bufev->output));
1001 case TLS_WANT_POLLIN:
1002 case TLS_WANT_POLLOUT:
1005 what |= EVBUFFER_ERROR;
1009 evbuffer_drain(bufev->output, len);
1012 if (EVBUFFER_LENGTH(bufev->output) != 0)
1013 event_add(&bufev->ev_write, NULL);
1015 if (bufev->writecb != NULL &&
1016 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
1017 (*bufev->writecb)(bufev, bufev->cbarg);
1021 event_add(&bufev->ev_write, NULL);
1024 log_warnx("tls error: %s", tls_error(client->ctx));
1025 (*bufev->errorcb)(bufev, what, bufev->cbarg);
1029 client_read(struct bufferevent *bev, void *d)
1031 struct client *c = d;
1032 struct evbuffer *src = EVBUFFER_INPUT(bev);
1033 const char *parse_err = "invalid request";
1034 char decoded[DOMAIN_NAME_LEN];
1036 bufferevent_disable(bev, EVBUFFER_READ);
1039 * libevent2 can still somehow call this function, even
1040 * though I never enable EV_READ in the bufferevent. If
1041 * that's the case, bail out.
1043 if (c->type != REQUEST_UNDECIDED)
1046 /* max url len + \r\n */
1047 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1048 log_debug("too much data received");
1049 start_reply(c, BAD_REQUEST, "bad request");
1053 c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
1054 if (c->req == NULL) {
1055 /* not enough data yet. */
1056 bufferevent_enable(bev, EVBUFFER_READ);
1059 if (c->reqlen > 1024+2) {
1060 log_debug("URL too long");
1061 start_reply(c, BAD_REQUEST, "bad request");
1065 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1066 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1067 log_debug("IRI parse error: %s", parse_err);
1068 start_reply(c, BAD_REQUEST, "bad request");
1072 if (apply_reverse_proxy(c))
1075 /* ignore the port number */
1076 if (strcmp(c->iri.schema, "gemini") ||
1077 strcmp(decoded, c->domain)) {
1078 start_reply(c, PROXY_REFUSED, "won't proxy request");
1082 if (apply_require_ca(c) ||
1083 apply_block_return(c)||
1091 client_write(struct bufferevent *bev, void *d)
1093 struct client *c = d;
1094 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1100 case REQUEST_UNDECIDED:
1102 * Ignore spurious calls when we still don't have idea
1103 * what to do with the request.
1108 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1110 client_error(bev, EVBUFFER_ERROR, c);
1112 } else if (r == 0) {
1115 } else if (r != sizeof(buf))
1116 c->type = REQUEST_DONE;
1117 bufferevent_write(bev, buf, r);
1121 /* TODO: handle big big directories better */
1122 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1123 const char *sufx = "";
1125 encode_path(nam, sizeof(nam),
1126 c->dir[c->diroff]->d_name);
1127 if (c->dir[c->diroff]->d_type == DT_DIR)
1129 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1130 free(c->dir[c->diroff]);
1135 c->type = REQUEST_DONE;
1137 event_add(&c->bev->ev_write, NULL);
1143 * Here we depend on fastcgi or proxy connection to
1149 if (EVBUFFER_LENGTH(out) == 0)
1156 client_error(struct bufferevent *bev, short error, void *d)
1158 struct client *c = d;
1160 c->type = REQUEST_DONE;
1162 if (error & EVBUFFER_TIMEOUT) {
1163 log_debug("timeout; forcefully closing the connection");
1165 start_reply(c, BAD_REQUEST, "timeout");
1171 if (error & EVBUFFER_EOF) {
1176 log_warnx("unknown bufferevent error 0x%x", error);
1181 start_reply(struct client *c, int code, const char *meta)
1183 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1187 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1192 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1196 /* 2 digit status + space + 1024 max reply */
1200 if (c->type != REQUEST_FCGI &&
1201 c->type != REQUEST_PROXY &&
1202 !strcmp(meta, "text/gemini") &&
1203 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1204 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1211 bufferevent_write(c->bev, "\r\n", 2);
1213 if (!vhost_disable_log(c->host, c->iri.path))
1214 log_request(c, (char *)EVBUFFER_DATA(evb),
1215 EVBUFFER_LENGTH(evb));
1218 c->type = REQUEST_DONE;
1223 log_warnx("evbuffer_add_printf error: no memory");
1224 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1229 log_warnx("reply header overflow");
1230 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1231 start_reply(c, TEMP_FAILURE, "internal error");
1235 client_close_ev(int fd, short event, void *d)
1237 struct client *c = d;
1239 switch (tls_close(c->ctx)) {
1240 case TLS_WANT_POLLIN:
1241 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1243 case TLS_WANT_POLLOUT:
1244 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1248 connected_clients--;
1270 client_proxy_close(int fd, short event, void *d)
1272 struct tls *ctx = d;
1279 switch (tls_close(ctx)) {
1280 case TLS_WANT_POLLIN:
1281 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1283 case TLS_WANT_POLLOUT:
1284 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1293 client_close(struct client *c)
1296 * We may end up calling client_close in various situations
1297 * and for the most unexpected reasons. Therefore, we need to
1298 * ensure that everything gets properly released once we reach
1302 SPLAY_REMOVE(client_tree_id, &clients, c);
1304 if (c->cgibev != NULL) {
1305 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1306 bufferevent_free(c->cgibev);
1312 if (c->bev != NULL) {
1313 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1314 bufferevent_free(c->bev);
1317 if (c->proxyevset &&
1318 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1320 event_del(&c->proxyev);
1323 if (c->pfd != -1 && c->proxyctx != NULL) {
1324 /* shut down the proxy TLS connection */
1325 client_proxy_close(c->pfd, 0, c->proxyctx);
1329 if (c->proxybev != NULL)
1330 bufferevent_free(c->proxybev);
1332 client_close_ev(c->fd, 0, c);
1336 do_accept(int sock, short et, void *d)
1338 struct address *addr = d;
1340 struct sockaddr_storage raddr;
1341 struct sockaddr *sraddr;
1345 sraddr = (struct sockaddr *)&raddr;
1346 len = sizeof(raddr);
1347 if ((fd = accept(sock, sraddr, &len)) == -1) {
1348 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1349 errno == ECONNABORTED)
1356 c = xcalloc(1, sizeof(*c));
1357 c->conf = addr->conf;
1359 c->id = ++server_client_id;
1362 memcpy(&c->raddr, &raddr, sizeof(raddr));
1365 e = getnameinfo(sraddr, len, c->rhost, sizeof(c->rhost),
1366 c->rserv, sizeof(c->rserv), NI_NUMERICHOST | NI_NUMERICSERV);
1368 log_warnx("getnameinfo failed: %s", gai_strerror(e));
1374 if (tls_accept_socket(addr->ctx, &c->ctx, fd) == -1) {
1375 log_warnx("failed to accept socket: %s", tls_error(c->ctx));
1381 SPLAY_INSERT(client_tree_id, &clients, c);
1382 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1383 connected_clients++;
1387 client_by_id(int id)
1392 return SPLAY_FIND(client_tree_id, &clients, &find);
1396 handle_siginfo(int fd, short ev, void *d)
1398 log_info("%d connected clients", connected_clients);
1402 add_matching_kps(struct tls_config *tlsconf, struct address *addr,
1405 struct address *vaddr;
1409 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1410 TAILQ_FOREACH(vaddr, &h->addrs, addrs) {
1411 if (!match_addr(addr, vaddr))
1416 r = tls_config_set_keypair_ocsp_mem(tlsconf,
1417 h->cert, h->certlen, h->key, h->keylen,
1418 h->ocsp, h->ocsplen);
1420 r = tls_config_add_keypair_ocsp_mem(tlsconf,
1421 h->cert, h->certlen, h->key, h->keylen,
1422 h->ocsp, h->ocsplen);
1426 fatalx("failed to load keypair"
1427 " for host %s: %s", h->domain,
1428 tls_config_error(tlsconf));
1434 setup_tls(struct conf *conf)
1436 struct tls_config *tlsconf;
1437 struct address *addr;
1439 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1440 if ((tlsconf = tls_config_new()) == NULL)
1441 fatal("tls_config_new");
1443 if (conf->use_privsep_crypto)
1444 tls_config_use_fake_private_key(tlsconf);
1446 /* optionally accept client certs but don't verify */
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 add_matching_kps(tlsconf, addr, conf);
1456 tls_reset(addr->ctx);
1457 if (tls_configure(addr->ctx, tlsconf) == -1)
1458 fatalx("tls_configure: %s", tls_error(addr->ctx));
1460 tls_config_free(tlsconf);
1465 load_vhosts(struct conf *conf)
1470 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
1471 TAILQ_FOREACH(l, &h->locations, locations) {
1472 if (*l->dir == '\0')
1474 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1476 fatal("open %s for domain %s", l->dir,
1483 server(struct privsep *ps, struct privsep_proc *p)
1485 proc_run(ps, p, procs, nitems(procs), server_init, NULL);
1489 server_init(struct privsep *ps, struct privsep_proc *p, void *arg)
1493 SPLAY_INIT(&clients);
1496 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1497 signal_add(&siginfo, NULL);
1499 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1500 signal_add(&sigusr2, NULL);
1502 sandbox_server_process();
1505 * ge doesn't use the privsep crypto engine; it doesn't use
1506 * privsep at all so `ps' is NULL.
1510 if (c->use_privsep_crypto)
1511 crypto_engine_init(ps->ps_env);
1516 server_configure_done(struct conf *conf)
1518 struct address *addr;
1520 if (load_default_mime(&conf->mime) == -1)
1521 fatal("can't load default mime");
1522 sort_mime(&conf->mime);
1526 TAILQ_FOREACH(addr, &conf->addrs, addrs) {
1527 if (addr->sock != -1)
1528 event_add(&addr->evsock, NULL);
1535 server_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
1537 struct privsep *ps = p->p_ps;
1538 struct conf *conf = ps->ps_env;
1540 switch (imsg->hdr.type) {
1541 case IMSG_RECONF_START:
1542 case IMSG_RECONF_MIME:
1543 case IMSG_RECONF_PROTOS:
1544 case IMSG_RECONF_SOCK:
1545 case IMSG_RECONF_FCGI:
1546 case IMSG_RECONF_HOST:
1547 case IMSG_RECONF_CERT:
1548 case IMSG_RECONF_KEY:
1549 case IMSG_RECONF_OCSP:
1550 case IMSG_RECONF_HOST_ADDR:
1551 case IMSG_RECONF_LOC:
1552 case IMSG_RECONF_ENV:
1553 case IMSG_RECONF_ALIAS:
1554 case IMSG_RECONF_PROXY:
1555 case IMSG_RECONF_PROXY_CERT:
1556 case IMSG_RECONF_PROXY_KEY:
1557 return config_recv(conf, imsg);
1558 case IMSG_RECONF_END:
1559 if (config_recv(conf, imsg) == -1)
1561 if (server_configure_done(conf) == -1)
1572 server_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
1578 server_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
1584 client_tree_cmp(struct client *a, struct client *b)
1588 else if (a->id < b->id)
1594 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)