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.
33 #define MIN(a, b) ((a) < (b) ? (a) : (b))
37 static struct tls *ctx;
39 static struct event e4, e6, imsgev, siginfo, sigusr2;
40 static int has_ipv6, has_siginfo;
42 int connected_clients;
44 static inline int matches(const char*, const char*);
46 static int check_path(struct client*, const char*, int*);
47 static void open_file(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 check_matching_certificate(X509_STORE *, struct client *);
53 static int apply_reverse_proxy(struct client *);
54 static int apply_fastcgi(struct client*);
55 static int apply_require_ca(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 do_accept(int, short, void*);
70 static void handle_dispatch_imsg(int, short, void *);
71 static void handle_siginfo(int, short, void*);
73 static uint32_t server_client_id;
75 struct client_tree_id clients;
78 matches(const char *pattern, const char *path)
82 return !fnmatch(pattern, path, 0);
86 vhost_lang(struct vhost *v, const char *path)
90 if (v == NULL || path == NULL)
93 loc = TAILQ_FIRST(&v->locations);
94 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
95 if (*loc->lang != '\0') {
96 if (matches(loc->match, path))
101 loc = TAILQ_FIRST(&v->locations);
102 if (*loc->lang == '\0')
108 vhost_default_mime(struct vhost *v, const char *path)
110 struct location *loc;
111 const char *default_mime = "application/octet-stream";
113 if (v == NULL || path == NULL)
116 loc = TAILQ_FIRST(&v->locations);
117 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
118 if (*loc->default_mime != '\0') {
119 if (matches(loc->match, path))
120 return loc->default_mime;
124 loc = TAILQ_FIRST(&v->locations);
125 if (*loc->default_mime != '\0')
126 return loc->default_mime;
131 vhost_index(struct vhost *v, const char *path)
133 struct location *loc;
134 const char *index = "index.gmi";
136 if (v == NULL || path == NULL)
139 loc = TAILQ_FIRST(&v->locations);
140 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
141 if (*loc->index != '\0') {
142 if (matches(loc->match, path))
147 loc = TAILQ_FIRST(&v->locations);
148 if (*loc->index != '\0')
154 vhost_auto_index(struct vhost *v, const char *path)
156 struct location *loc;
158 if (v == NULL || path == NULL)
161 loc = TAILQ_FIRST(&v->locations);
162 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
163 if (loc->auto_index != 0) {
164 if (matches(loc->match, path))
165 return loc->auto_index == 1;
169 loc = TAILQ_FIRST(&v->locations);
170 return loc->auto_index == 1;
174 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
176 struct location *loc;
178 if (v == NULL || path == NULL)
181 loc = TAILQ_FIRST(&v->locations);
182 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
183 if (loc->block_code != 0) {
184 if (matches(loc->match, path)) {
185 *code = loc->block_code;
186 *fmt = loc->block_fmt;
192 loc = TAILQ_FIRST(&v->locations);
193 *code = loc->block_code;
194 *fmt = loc->block_fmt;
195 return loc->block_code != 0;
199 vhost_fastcgi(struct vhost *v, const char *path)
201 struct location *loc;
203 if (v == NULL || path == NULL)
206 loc = TAILQ_FIRST(&v->locations);
207 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
209 if (matches(loc->match, path))
213 loc = TAILQ_FIRST(&v->locations);
218 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
220 struct location *loc;
223 if (v == NULL || path == NULL)
226 loc = TAILQ_FIRST(&v->locations);
227 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
229 if (loc->dirfd != -1)
230 if (matches(loc->match, path)) {
237 loc = TAILQ_FIRST(&v->locations);
242 vhost_strip(struct vhost *v, const char *path)
244 struct location *loc;
246 if (v == NULL || path == NULL)
249 loc = TAILQ_FIRST(&v->locations);
250 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
251 if (loc->strip != 0) {
252 if (matches(loc->match, path))
257 loc = TAILQ_FIRST(&v->locations);
262 vhost_require_ca(struct vhost *v, const char *path)
264 struct location *loc;
266 if (v == NULL || path == NULL)
269 loc = TAILQ_FIRST(&v->locations);
270 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
271 if (loc->reqca != NULL) {
272 if (matches(loc->match, path))
277 loc = TAILQ_FIRST(&v->locations);
282 vhost_disable_log(struct vhost *v, const char *path)
284 struct location *loc;
286 if (v == NULL || path == NULL)
289 loc = TAILQ_FIRST(&v->locations);
290 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
291 if (loc->disable_log && matches(loc->match, path))
295 loc = TAILQ_FIRST(&v->locations);
296 return loc->disable_log;
300 check_path(struct client *c, const char *path, int *fd)
306 assert(path != NULL);
309 * in send_dir we add an initial / (to be redirect-friendly),
310 * but here we want to skip it
315 strip = vhost_strip(c->host, path);
316 p = strip_path(path, strip);
323 dirfd = vhost_dirfd(c->host, path, &c->loc);
324 log_debug(c, "check_path: strip=%d path=%s original=%s",
326 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
328 log_info(c, "can't open %s: %s", p, strerror(errno));
332 if (fstat(*fd, &sb) == -1) {
333 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
337 if (S_ISDIR(sb.st_mode))
338 return FILE_DIRECTORY;
344 open_file(struct client *c)
346 switch (check_path(c, c->iri.path, &c->pfd)) {
348 c->type = REQUEST_FILE;
349 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
357 start_reply(c, NOT_FOUND, "not found");
367 mark_nonblock(int fd)
371 if ((flags = fcntl(fd, F_GETFL)) == -1)
372 fatal("fcntl(F_GETFL)");
373 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
374 fatal("fcntl(F_SETFL)");
378 handle_handshake(int fd, short ev, void *d)
380 struct client *c = d;
383 const char *servname;
384 const char *parse_err = "unknown error";
386 switch (tls_handshake(c->ctx)) {
387 case 0: /* success */
388 case -1: /* already handshaked */
390 case TLS_WANT_POLLIN:
391 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
393 case TLS_WANT_POLLOUT:
394 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
401 c->bev = bufferevent_new(fd, client_read, client_write,
404 fatal("%s: failed to allocate client buffer", __func__);
406 event_set(&c->bev->ev_read, c->fd, EV_READ,
407 client_tls_readcb, c->bev);
408 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
409 client_tls_writecb, c->bev);
412 evbuffer_unfreeze(c->bev->input, 0);
413 evbuffer_unfreeze(c->bev->output, 1);
416 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
417 log_debug(c, "handshake: missing SNI");
421 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
422 log_info(c, "puny_decode: %s", parse_err);
426 TAILQ_FOREACH(h, &hosts, vhosts) {
427 if (matches(h->domain, c->domain))
429 TAILQ_FOREACH(a, &h->aliases, aliases) {
430 if (matches(a->alias, c->domain))
436 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
437 servname != NULL ? servname : "(null)",
439 h != NULL ? h->domain : "(null)");
443 bufferevent_enable(c->bev, EV_READ);
448 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
452 strip_path(const char *path, int strip)
457 if ((t = strchr(path, '/')) == NULL) {
458 path = strchr(path, '\0');
469 fmt_sbuf(const char *fmt, struct client *c, const char *path)
474 memset(buf, 0, sizeof(buf));
475 for (i = 0; *fmt; ++fmt) {
476 if (i == sizeof(buf)-1 || *fmt == '%') {
477 strlcat(c->sbuf, buf, sizeof(c->sbuf));
478 memset(buf, 0, sizeof(buf));
489 strlcat(c->sbuf, "%", sizeof(c->sbuf));
493 strlcat(c->sbuf, "/", sizeof(c->sbuf));
494 strlcat(c->sbuf, path, sizeof(c->sbuf));
497 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
500 snprintf(buf, sizeof(buf), "%d", conf.port);
501 strlcat(c->sbuf, buf, sizeof(c->sbuf));
502 memset(buf, 0, sizeof(buf));
505 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
508 fatalx("%s: unknown fmt specifier %c",
514 strlcat(c->sbuf, buf, sizeof(c->sbuf));
517 /* 1 if a matching `block return' (and apply it), 0 otherwise */
519 apply_block_return(struct client *c)
521 const char *fmt, *path;
524 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
527 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
528 fmt_sbuf(fmt, c, path);
530 start_reply(c, code, c->sbuf);
534 static struct proxy *
535 matched_proxy(struct client *c)
542 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
543 if (*(proto = p->match_proto) == '\0')
545 if (*(host = p->match_host) == '\0')
547 if (*(port = p->match_port) == '\0')
550 if (matches(proto, c->iri.schema) &&
551 matches(host, c->domain) &&
552 matches(port, c->iri.port))
560 check_matching_certificate(X509_STORE *store, struct client *c)
565 if (!tls_peer_cert_provided(c->ctx)) {
566 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
570 cert = tls_peer_cert_chain_pem(c->ctx, &len);
571 if (!validate_against_ca(store, cert, len)) {
572 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
580 proxy_socket(struct client *c, const char *host, const char *port)
582 struct addrinfo hints, *res, *res0;
585 memset(&hints, 0, sizeof(hints));
586 hints.ai_family = AF_UNSPEC;
587 hints.ai_socktype = SOCK_STREAM;
589 /* XXX: asr_run? :> */
590 r = getaddrinfo(host, port, &hints, &res0);
592 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
593 host, port, gai_strerror(r));
597 for (res = res0; res; res = res->ai_next) {
598 sock = socket(res->ai_family, res->ai_socktype,
603 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
615 log_warn(c, "can't connect to %s:%s", host, port);
620 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
622 apply_reverse_proxy(struct client *c)
626 if ((p = matched_proxy(c)) == NULL)
631 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
634 log_debug(c, "opening proxy connection for %s:%s",
637 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
638 start_reply(c, PROXY_ERROR, "proxy error");
642 mark_nonblock(c->pfd);
643 if (proxy_init(c) == -1)
644 start_reply(c, PROXY_ERROR, "proxy error");
650 fcgi_open_sock(struct fcgi *f)
652 struct sockaddr_un addr;
655 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
656 log_err(NULL, "socket: %s", strerror(errno));
660 memset(&addr, 0, sizeof(addr));
661 addr.sun_family = AF_UNIX;
662 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
664 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
665 log_warn(NULL, "failed to connect to %s: %s", f->path,
675 fcgi_open_conn(struct fcgi *f)
677 struct addrinfo hints, *servinfo, *p;
680 memset(&hints, 0, sizeof(hints));
681 hints.ai_family = AF_UNSPEC;
682 hints.ai_socktype = SOCK_STREAM;
683 hints.ai_flags = AI_ADDRCONFIG;
685 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
686 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
691 for (p = servinfo; p != NULL; p = p->ai_next) {
692 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
695 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
703 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
707 freeaddrinfo(servinfo);
711 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
713 apply_fastcgi(struct client *c)
718 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
723 log_debug(c, "opening fastcgi connection for (%s,%s)",
726 if (*f->port == '\0')
727 c->pfd = fcgi_open_sock(f);
729 c->pfd = fcgi_open_conn(f);
732 start_reply(c, CGI_ERROR, "CGI error");
736 mark_nonblock(c->pfd);
738 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
740 if (c->cgibev == NULL) {
741 start_reply(c, TEMP_FAILURE, "internal server error");
745 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
751 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
753 apply_require_ca(struct client *c)
757 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
759 return check_matching_certificate(store, c);
763 open_dir(struct client *c)
769 log_debug(c, "in open_dir");
771 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
773 len = strlen(c->iri.path);
774 if (len > 0 && !ends_with(c->iri.path, "/")) {
775 redirect_canonical_dir(c);
779 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
780 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
781 if (!ends_with(c->sbuf, "/"))
782 strlcat(c->sbuf, "/", sizeof(c->sbuf));
783 before_file = strchr(c->sbuf, '\0');
784 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
786 if (len >= sizeof(c->sbuf)) {
787 start_reply(c, TEMP_FAILURE, "internal server error");
791 c->iri.path = c->sbuf;
793 /* close later unless we have to generate the dir listing */
797 switch (check_path(c, c->iri.path, &c->pfd)) {
799 c->type = REQUEST_FILE;
800 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
804 start_reply(c, TEMP_REDIRECT, c->sbuf);
810 if (!vhost_auto_index(c->host, c->iri.path)) {
811 start_reply(c, NOT_FOUND, "not found");
815 c->type = REQUEST_DIR;
817 c->dirlen = scandir_fd(dirfd, &c->dir,
818 root ? select_non_dotdot : select_non_dot,
820 if (c->dirlen == -1) {
821 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
822 c->pfd, c->host->domain, c->iri.path, strerror(errno));
823 start_reply(c, TEMP_FAILURE, "internal server error");
829 start_reply(c, SUCCESS, "text/gemini");
830 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
831 "# Index of %s\n\n", c->iri.path);
843 redirect_canonical_dir(struct client *c)
847 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
848 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
849 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
851 if (len >= sizeof(c->sbuf)) {
852 start_reply(c, TEMP_FAILURE, "internal server error");
856 start_reply(c, TEMP_REDIRECT, c->sbuf);
860 client_tls_readcb(int fd, short event, void *d)
862 struct bufferevent *bufev = d;
863 struct client *client = bufev->cbarg;
866 int what = EVBUFFER_READ;
867 int howmuch = IBUF_READ_SIZE;
868 char buf[IBUF_READ_SIZE];
870 if (event == EV_TIMEOUT) {
871 what |= EVBUFFER_TIMEOUT;
875 if (bufev->wm_read.high != 0)
876 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
878 switch (ret = tls_read(client->ctx, buf, howmuch)) {
879 case TLS_WANT_POLLIN:
880 case TLS_WANT_POLLOUT:
883 what |= EVBUFFER_ERROR;
889 what |= EVBUFFER_EOF;
893 if (evbuffer_add(bufev->input, buf, len) == -1) {
894 what |= EVBUFFER_ERROR;
898 event_add(&bufev->ev_read, NULL);
899 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
901 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
903 * here we could implement a read pressure policy.
907 if (bufev->readcb != NULL)
908 (*bufev->readcb)(bufev, bufev->cbarg);
913 event_add(&bufev->ev_read, NULL);
917 (*bufev->errorcb)(bufev, what, bufev->cbarg);
921 client_tls_writecb(int fd, short event, void *d)
923 struct bufferevent *bufev = d;
924 struct client *client = bufev->cbarg;
927 short what = EVBUFFER_WRITE;
929 if (event == EV_TIMEOUT) {
930 what |= EVBUFFER_TIMEOUT;
934 if (EVBUFFER_LENGTH(bufev->output) != 0) {
935 ret = tls_write(client->ctx,
936 EVBUFFER_DATA(bufev->output),
937 EVBUFFER_LENGTH(bufev->output));
939 case TLS_WANT_POLLIN:
940 case TLS_WANT_POLLOUT:
943 what |= EVBUFFER_ERROR;
947 evbuffer_drain(bufev->output, len);
950 if (EVBUFFER_LENGTH(bufev->output) != 0)
951 event_add(&bufev->ev_write, NULL);
953 if (bufev->writecb != NULL &&
954 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
955 (*bufev->writecb)(bufev, bufev->cbarg);
959 event_add(&bufev->ev_write, NULL);
962 log_err(client, "tls error: %s", tls_error(client->ctx));
963 (*bufev->errorcb)(bufev, what, bufev->cbarg);
967 client_read(struct bufferevent *bev, void *d)
969 struct client *c = d;
970 struct evbuffer *src = EVBUFFER_INPUT(bev);
971 const char *parse_err = "invalid request";
972 char decoded[DOMAIN_NAME_LEN];
975 bufferevent_disable(bev, EVBUFFER_READ);
978 * libevent2 can still somehow call this function, even
979 * though I never enable EV_READ in the bufferevent. If
980 * that's the case, bail out.
982 if (c->type != REQUEST_UNDECIDED)
985 /* max url len + \r\n */
986 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
987 log_err(c, "too much data received");
988 start_reply(c, BAD_REQUEST, "bad request");
992 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
993 if (c->req == NULL) {
994 /* not enough data yet. */
995 bufferevent_enable(bev, EVBUFFER_READ);
998 c->reqlen = strlen(c->req);
999 if (c->reqlen > 1024+2) {
1000 log_err(c, "URL too long");
1001 start_reply(c, BAD_REQUEST, "bad request");
1005 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1006 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1007 log_err(c, "IRI parse error: %s", parse_err);
1008 start_reply(c, BAD_REQUEST, "bad request");
1012 if (apply_reverse_proxy(c))
1015 /* ignore the port number */
1016 if (strcmp(c->iri.schema, "gemini") ||
1017 strcmp(decoded, c->domain)) {
1018 start_reply(c, PROXY_REFUSED, "won't proxy request");
1022 if (apply_require_ca(c) ||
1023 apply_block_return(c)||
1031 client_write(struct bufferevent *bev, void *d)
1033 struct client *c = d;
1034 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1040 case REQUEST_UNDECIDED:
1042 * Ignore spurious calls when we still don't have idea
1043 * what to do with the request.
1048 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1049 log_warn(c, "read: %s", strerror(errno));
1050 client_error(bev, EVBUFFER_ERROR, c);
1052 } else if (r == 0) {
1055 } else if (r != sizeof(buf))
1056 c->type = REQUEST_DONE;
1057 bufferevent_write(bev, buf, r);
1061 /* TODO: handle big big directories better */
1062 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1063 const char *sufx = "";
1065 encode_path(nam, sizeof(nam),
1066 c->dir[c->diroff]->d_name);
1067 if (c->dir[c->diroff]->d_type == DT_DIR)
1069 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1070 free(c->dir[c->diroff]);
1075 c->type = REQUEST_DONE;
1077 event_add(&c->bev->ev_write, NULL);
1083 * Here we depend on fastcgi or proxy connection to
1089 if (EVBUFFER_LENGTH(out) == 0)
1096 client_error(struct bufferevent *bev, short error, void *d)
1098 struct client *c = d;
1100 c->type = REQUEST_DONE;
1102 if (error & EVBUFFER_TIMEOUT) {
1103 log_warn(c, "timeout reached, "
1104 "forcefully closing the connection");
1106 start_reply(c, BAD_REQUEST, "timeout");
1112 if (error & EVBUFFER_EOF) {
1117 log_err(c, "unknown bufferevent error %x", error);
1122 start_reply(struct client *c, int code, const char *meta)
1124 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1128 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1133 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1137 /* 2 digit status + space + 1024 max reply */
1141 if (c->type != REQUEST_FCGI &&
1142 c->type != REQUEST_PROXY &&
1143 !strcmp(meta, "text/gemini") &&
1144 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1145 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1152 bufferevent_write(c->bev, "\r\n", 2);
1154 if (!vhost_disable_log(c->host, c->iri.path))
1155 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1158 c->type = REQUEST_DONE;
1163 log_err(c, "evbuffer_add_printf error: no memory");
1164 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1169 log_warn(c, "reply header overflow");
1170 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1171 start_reply(c, TEMP_FAILURE, "internal error");
1175 client_close_ev(int fd, short event, void *d)
1177 struct client *c = d;
1179 switch (tls_close(c->ctx)) {
1180 case TLS_WANT_POLLIN:
1181 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1183 case TLS_WANT_POLLOUT:
1184 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1188 connected_clients--;
1208 client_proxy_close(int fd, short event, void *d)
1210 struct tls *ctx = d;
1217 switch (tls_close(ctx)) {
1218 case TLS_WANT_POLLIN:
1219 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1221 case TLS_WANT_POLLOUT:
1222 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1231 client_close(struct client *c)
1234 * We may end up calling client_close in various situations
1235 * and for the most unexpected reasons. Therefore, we need to
1236 * ensure that everything gets properly released once we reach
1240 SPLAY_REMOVE(client_tree_id, &clients, c);
1242 if (c->cgibev != NULL) {
1243 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1244 bufferevent_free(c->cgibev);
1250 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1251 bufferevent_free(c->bev);
1254 if (c->proxyevset &&
1255 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1257 event_del(&c->proxyev);
1260 if (c->pfd != -1 && c->proxyctx != NULL) {
1261 /* shut down the proxy TLS connection */
1262 client_proxy_close(c->pfd, 0, c->proxyctx);
1266 if (c->proxybev != NULL)
1267 bufferevent_free(c->proxybev);
1269 client_close_ev(c->fd, 0, c);
1273 do_accept(int sock, short et, void *d)
1276 struct sockaddr_storage addr;
1277 struct sockaddr *saddr;
1281 saddr = (struct sockaddr*)&addr;
1283 if ((fd = accept(sock, saddr, &len)) == -1) {
1284 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1285 errno == ECONNABORTED)
1292 c = xcalloc(1, sizeof(*c));
1293 c->id = ++server_client_id;
1298 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1299 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1305 SPLAY_INSERT(client_tree_id, &clients, c);
1306 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1307 connected_clients++;
1311 client_by_id(int id)
1316 return SPLAY_FIND(client_tree_id, &clients, &find);
1320 handle_dispatch_imsg(int fd, short ev, void *d)
1322 struct imsgbuf *ibuf = d;
1326 if ((n = imsg_read(ibuf)) == -1) {
1327 if (errno == EAGAIN || errno == EWOULDBLOCK)
1333 fatalx("connection closed.");
1336 if ((n = imsg_get(ibuf, &imsg)) == -1)
1341 switch (imsg.hdr.type) {
1344 * Don't call event_loopbreak since we want to
1345 * finish handling the ongoing connections.
1353 signal_del(&siginfo);
1355 signal_del(&sigusr2);
1358 fatalx("Unknown message %d", imsg.hdr.type);
1365 handle_siginfo(int fd, short ev, void *d)
1367 log_info(NULL, "%d connected clients", connected_clients);
1371 loop(int sock4, int sock6, struct imsgbuf *ibuf)
1373 SPLAY_INIT(&clients);
1377 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1378 event_add(&e4, NULL);
1382 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1383 event_add(&e6, NULL);
1387 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1388 handle_dispatch_imsg, ibuf);
1389 event_add(&imsgev, NULL);
1394 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1395 signal_add(&siginfo, NULL);
1397 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1398 signal_add(&sigusr2, NULL);
1400 sandbox_server_process();
1406 add_keypair(struct vhost *h, struct tls_config *conf)
1408 if (*h->ocsp == '\0') {
1409 if (tls_config_add_keypair_file(conf, h->cert, h->key) == -1)
1410 fatalx("failed to load the keypair (%s, %s): %s",
1411 h->cert, h->key, tls_config_error(conf));
1413 if (tls_config_add_keypair_ocsp_file(conf, h->cert, h->key,
1415 fatalx("failed to load the keypair (%s, %s, %s): %s",
1416 h->cert, h->key, h->ocsp,
1417 tls_config_error(conf));
1422 * XXX: in a ideal privsep world, this is done by the parent process
1423 * and its content sent to us.
1428 struct tls_config *tlsconf;
1431 if ((tlsconf = tls_config_new()) == NULL)
1432 fatal("tls_config_new");
1434 /* optionally accept client certs, but don't try to verify them */
1435 tls_config_verify_client_optional(tlsconf);
1436 tls_config_insecure_noverifycert(tlsconf);
1438 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
1439 fatalx("tls_config_set_protocols: %s",
1440 tls_config_error(tlsconf));
1442 h = TAILQ_FIRST(&hosts);
1444 log_warn(NULL, "loading %s, %s, %s", h->cert, h->key, h->ocsp);
1446 /* we need to set something, then we can add how many key we want */
1447 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
1448 fatalx("tls_config_set_keypair_file failed for (%s, %s): %s",
1449 h->cert, h->key, tls_config_error(tlsconf));
1452 if (*h->ocsp != '\0' &&
1453 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
1454 fatalx("tls_config_set_ocsp_staple_file failed for (%s): %s",
1455 h->ocsp, tls_config_error(tlsconf));
1457 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
1458 add_keypair(h, tlsconf);
1460 if ((ctx = tls_server()) == NULL)
1461 fatal("tls_server failure");
1463 if (tls_configure(ctx, tlsconf) == -1)
1464 fatalx("tls_configure: %s", tls_error(ctx));
1466 tls_config_free(tlsconf);
1475 TAILQ_FOREACH(h, &hosts, vhosts) {
1476 TAILQ_FOREACH(l, &h->locations, locations) {
1477 if (*l->dir == '\0')
1479 l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY);
1481 fatal("open %s for domain %s", l->dir,
1488 server_main(struct imsgbuf *ibuf, int sock4, int sock6)
1491 * setup tls before dropping privileges: we don't want user
1492 * to put private certs inside the chroot.
1496 if (load_default_mime(&conf.mime) == -1)
1497 fatal("can't load default mime");
1498 sort_mime(&conf.mime);
1500 loop(sock4, sock6, ibuf);
1505 client_tree_cmp(struct client *a, struct client *b)
1509 else if (a->id < b->id)
1515 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)