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.
31 #define MIN(a, b) ((a) < (b) ? (a) : (b))
35 static struct tls *ctx;
37 static struct event e4, e6, imsgev, siginfo, sigusr2;
38 static int has_ipv6, has_siginfo;
40 int connected_clients;
42 static inline int matches(const char*, const char*);
44 static int check_path(struct client*, const char*, int*);
45 static void open_file(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 check_matching_certificate(X509_STORE *, struct client *);
51 static int apply_reverse_proxy(struct client *);
52 static int apply_fastcgi(struct client*);
53 static int apply_require_ca(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 do_accept(int, short, void*);
68 static void handle_dispatch_imsg(int, short, void *);
69 static void handle_siginfo(int, short, void*);
71 static uint32_t server_client_id;
73 struct client_tree_id clients;
76 matches(const char *pattern, const char *path)
80 return !fnmatch(pattern, path, 0);
84 vhost_lang(struct vhost *v, const char *path)
88 if (v == NULL || path == NULL)
91 loc = TAILQ_FIRST(&v->locations);
92 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
93 if (loc->lang != NULL) {
94 if (matches(loc->match, path))
99 return TAILQ_FIRST(&v->locations)->lang;
103 vhost_default_mime(struct vhost *v, const char *path)
105 struct location *loc;
106 const char *default_mime = "application/octet-stream";
108 if (v == NULL || path == NULL)
111 loc = TAILQ_FIRST(&v->locations);
112 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
113 if (loc->default_mime != NULL) {
114 if (matches(loc->match, path))
115 return loc->default_mime;
119 loc = TAILQ_FIRST(&v->locations);
120 if (loc->default_mime != NULL)
121 return loc->default_mime;
126 vhost_index(struct vhost *v, const char *path)
128 struct location *loc;
129 const char *index = "index.gmi";
131 if (v == NULL || path == NULL)
134 loc = TAILQ_FIRST(&v->locations);
135 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
136 if (loc->index != NULL) {
137 if (matches(loc->match, path))
142 loc = TAILQ_FIRST(&v->locations);
143 if (loc->index != NULL)
149 vhost_auto_index(struct vhost *v, const char *path)
151 struct location *loc;
153 if (v == NULL || path == NULL)
156 loc = TAILQ_FIRST(&v->locations);
157 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
158 if (loc->auto_index != 0) {
159 if (matches(loc->match, path))
160 return loc->auto_index == 1;
164 loc = TAILQ_FIRST(&v->locations);
165 return loc->auto_index == 1;
169 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
171 struct location *loc;
173 if (v == NULL || path == NULL)
176 loc = TAILQ_FIRST(&v->locations);
177 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
178 if (loc->block_code != 0) {
179 if (matches(loc->match, path)) {
180 *code = loc->block_code;
181 *fmt = loc->block_fmt;
187 loc = TAILQ_FIRST(&v->locations);
188 *code = loc->block_code;
189 *fmt = loc->block_fmt;
190 return loc->block_code != 0;
194 vhost_fastcgi(struct vhost *v, const char *path)
196 struct location *loc;
198 if (v == NULL || path == NULL)
201 loc = TAILQ_FIRST(&v->locations);
202 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
204 if (matches(loc->match, path))
208 loc = TAILQ_FIRST(&v->locations);
213 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
215 struct location *loc;
218 if (v == NULL || path == NULL)
221 loc = TAILQ_FIRST(&v->locations);
222 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
224 if (loc->dirfd != -1)
225 if (matches(loc->match, path)) {
232 loc = TAILQ_FIRST(&v->locations);
237 vhost_strip(struct vhost *v, const char *path)
239 struct location *loc;
241 if (v == NULL || path == NULL)
244 loc = TAILQ_FIRST(&v->locations);
245 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
246 if (loc->strip != 0) {
247 if (matches(loc->match, path))
252 loc = TAILQ_FIRST(&v->locations);
257 vhost_require_ca(struct vhost *v, const char *path)
259 struct location *loc;
261 if (v == NULL || path == NULL)
264 loc = TAILQ_FIRST(&v->locations);
265 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
266 if (loc->reqca != NULL) {
267 if (matches(loc->match, path))
272 loc = TAILQ_FIRST(&v->locations);
277 vhost_disable_log(struct vhost *v, const char *path)
279 struct location *loc;
281 if (v == NULL || path == NULL)
284 loc = TAILQ_FIRST(&v->locations);
285 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
286 if (loc->disable_log && matches(loc->match, path))
290 loc = TAILQ_FIRST(&v->locations);
291 return loc->disable_log;
295 check_path(struct client *c, const char *path, int *fd)
301 assert(path != NULL);
304 * in send_dir we add an initial / (to be redirect-friendly),
305 * but here we want to skip it
310 strip = vhost_strip(c->host, path);
311 p = strip_path(path, strip);
318 dirfd = vhost_dirfd(c->host, path, &c->loc);
319 log_debug(c, "check_path: strip=%d path=%s original=%s",
321 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
323 log_info(c, "can't open %s: %s", p, strerror(errno));
327 if (fstat(*fd, &sb) == -1) {
328 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
332 if (S_ISDIR(sb.st_mode))
333 return FILE_DIRECTORY;
339 open_file(struct client *c)
341 switch (check_path(c, c->iri.path, &c->pfd)) {
343 c->type = REQUEST_FILE;
344 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
352 start_reply(c, NOT_FOUND, "not found");
362 mark_nonblock(int fd)
366 if ((flags = fcntl(fd, F_GETFL)) == -1)
367 fatal("fcntl(F_GETFL): %s", strerror(errno));
368 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
369 fatal("fcntl(F_SETFL): %s", strerror(errno));
373 handle_handshake(int fd, short ev, void *d)
375 struct client *c = d;
378 const char *servname;
379 const char *parse_err = "unknown error";
381 switch (tls_handshake(c->ctx)) {
382 case 0: /* success */
383 case -1: /* already handshaked */
385 case TLS_WANT_POLLIN:
386 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
388 case TLS_WANT_POLLOUT:
389 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
396 c->bev = bufferevent_new(fd, client_read, client_write,
399 fatal("%s: failed to allocate client buffer: %s",
400 __func__, strerror(errno));
402 event_set(&c->bev->ev_read, c->fd, EV_READ,
403 client_tls_readcb, c->bev);
404 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
405 client_tls_writecb, c->bev);
408 evbuffer_unfreeze(c->bev->input, 0);
409 evbuffer_unfreeze(c->bev->output, 1);
412 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
413 log_debug(c, "handshake: missing SNI");
417 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
418 log_info(c, "puny_decode: %s", parse_err);
422 TAILQ_FOREACH(h, &hosts, vhosts) {
423 if (matches(h->domain, c->domain))
425 TAILQ_FOREACH(a, &h->aliases, aliases) {
426 if (matches(a->alias, c->domain))
432 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
433 servname != NULL ? servname : "(null)",
435 h != NULL ? h->domain : "(null)");
439 bufferevent_enable(c->bev, EV_READ);
444 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
448 strip_path(const char *path, int strip)
453 if ((t = strchr(path, '/')) == NULL) {
454 path = strchr(path, '\0');
465 fmt_sbuf(const char *fmt, struct client *c, const char *path)
470 memset(buf, 0, sizeof(buf));
471 for (i = 0; *fmt; ++fmt) {
472 if (i == sizeof(buf)-1 || *fmt == '%') {
473 strlcat(c->sbuf, buf, sizeof(c->sbuf));
474 memset(buf, 0, sizeof(buf));
485 strlcat(c->sbuf, "%", sizeof(c->sbuf));
489 strlcat(c->sbuf, "/", sizeof(c->sbuf));
490 strlcat(c->sbuf, path, sizeof(c->sbuf));
493 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
496 snprintf(buf, sizeof(buf), "%d", conf.port);
497 strlcat(c->sbuf, buf, sizeof(c->sbuf));
498 memset(buf, 0, sizeof(buf));
501 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
504 fatal("%s: unknown fmt specifier %c",
510 strlcat(c->sbuf, buf, sizeof(c->sbuf));
513 /* 1 if a matching `block return' (and apply it), 0 otherwise */
515 apply_block_return(struct client *c)
517 const char *fmt, *path;
520 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
523 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
524 fmt_sbuf(fmt, c, path);
526 start_reply(c, code, c->sbuf);
530 static struct proxy *
531 matched_proxy(struct client *c)
538 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
539 if ((proto = p->match_proto) == NULL)
541 if ((host = p->match_host) == NULL)
543 if ((port = p->match_port) == NULL)
546 if (matches(proto, c->iri.schema) &&
547 matches(host, c->domain) &&
548 matches(port, c->iri.port))
556 check_matching_certificate(X509_STORE *store, struct client *c)
561 if (!tls_peer_cert_provided(c->ctx)) {
562 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
566 cert = tls_peer_cert_chain_pem(c->ctx, &len);
567 if (!validate_against_ca(store, cert, len)) {
568 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
576 proxy_socket(struct client *c, const char *host, const char *port)
578 struct addrinfo hints, *res, *res0;
581 memset(&hints, 0, sizeof(hints));
582 hints.ai_family = AF_UNSPEC;
583 hints.ai_socktype = SOCK_STREAM;
585 /* XXX: asr_run? :> */
586 r = getaddrinfo(host, port, &hints, &res0);
588 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
589 host, port, gai_strerror(r));
593 for (res = res0; res; res = res->ai_next) {
594 sock = socket(res->ai_family, res->ai_socktype,
599 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
611 log_warn(c, "can't connect to %s:%s", host, port);
616 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
618 apply_reverse_proxy(struct client *c)
622 if ((p = matched_proxy(c)) == NULL)
627 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
630 log_debug(c, "opening proxy connection for %s:%s",
633 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
634 start_reply(c, PROXY_ERROR, "proxy error");
638 mark_nonblock(c->pfd);
639 if (proxy_init(c) == -1)
640 start_reply(c, PROXY_ERROR, "proxy error");
646 fcgi_open_sock(struct fcgi *f)
648 struct sockaddr_un addr;
651 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
652 log_err(NULL, "socket: %s", strerror(errno));
656 memset(&addr, 0, sizeof(addr));
657 addr.sun_family = AF_UNIX;
658 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
660 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
661 log_warn(NULL, "failed to connect to %s: %s", f->path,
671 fcgi_open_conn(struct fcgi *f)
673 struct addrinfo hints, *servinfo, *p;
676 memset(&hints, 0, sizeof(hints));
677 hints.ai_family = AF_UNSPEC;
678 hints.ai_socktype = SOCK_STREAM;
679 hints.ai_flags = AI_ADDRCONFIG;
681 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
682 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
687 for (p = servinfo; p != NULL; p = p->ai_next) {
688 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
691 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
699 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
703 freeaddrinfo(servinfo);
707 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
709 apply_fastcgi(struct client *c)
714 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
719 log_debug(c, "opening fastcgi connection for (%s,%s)",
723 c->pfd = fcgi_open_sock(f);
725 c->pfd = fcgi_open_conn(f);
728 start_reply(c, CGI_ERROR, "CGI error");
732 mark_nonblock(c->pfd);
734 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
736 if (c->cgibev == NULL) {
737 start_reply(c, TEMP_FAILURE, "internal server error");
741 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
747 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
749 apply_require_ca(struct client *c)
753 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
755 return check_matching_certificate(store, c);
759 open_dir(struct client *c)
765 log_debug(c, "in open_dir");
767 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
769 len = strlen(c->iri.path);
770 if (len > 0 && !ends_with(c->iri.path, "/")) {
771 redirect_canonical_dir(c);
775 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
776 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
777 if (!ends_with(c->sbuf, "/"))
778 strlcat(c->sbuf, "/", sizeof(c->sbuf));
779 before_file = strchr(c->sbuf, '\0');
780 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
782 if (len >= sizeof(c->sbuf)) {
783 start_reply(c, TEMP_FAILURE, "internal server error");
787 c->iri.path = c->sbuf;
789 /* close later unless we have to generate the dir listing */
793 switch (check_path(c, c->iri.path, &c->pfd)) {
795 c->type = REQUEST_FILE;
796 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
800 start_reply(c, TEMP_REDIRECT, c->sbuf);
806 if (!vhost_auto_index(c->host, c->iri.path)) {
807 start_reply(c, NOT_FOUND, "not found");
811 c->type = REQUEST_DIR;
813 c->dirlen = scandir_fd(dirfd, &c->dir,
814 root ? select_non_dotdot : select_non_dot,
816 if (c->dirlen == -1) {
817 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
818 c->pfd, c->host->domain, c->iri.path, strerror(errno));
819 start_reply(c, TEMP_FAILURE, "internal server error");
825 start_reply(c, SUCCESS, "text/gemini");
826 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
827 "# Index of %s\n\n", c->iri.path);
839 redirect_canonical_dir(struct client *c)
843 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
844 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
845 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
847 if (len >= sizeof(c->sbuf)) {
848 start_reply(c, TEMP_FAILURE, "internal server error");
852 start_reply(c, TEMP_REDIRECT, c->sbuf);
856 client_tls_readcb(int fd, short event, void *d)
858 struct bufferevent *bufev = d;
859 struct client *client = bufev->cbarg;
862 int what = EVBUFFER_READ;
863 int howmuch = IBUF_READ_SIZE;
864 char buf[IBUF_READ_SIZE];
866 if (event == EV_TIMEOUT) {
867 what |= EVBUFFER_TIMEOUT;
871 if (bufev->wm_read.high != 0)
872 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
874 switch (ret = tls_read(client->ctx, buf, howmuch)) {
875 case TLS_WANT_POLLIN:
876 case TLS_WANT_POLLOUT:
879 what |= EVBUFFER_ERROR;
885 what |= EVBUFFER_EOF;
889 if (evbuffer_add(bufev->input, buf, len) == -1) {
890 what |= EVBUFFER_ERROR;
894 event_add(&bufev->ev_read, NULL);
895 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
897 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
899 * here we could implement a read pressure policy.
903 if (bufev->readcb != NULL)
904 (*bufev->readcb)(bufev, bufev->cbarg);
909 event_add(&bufev->ev_read, NULL);
913 (*bufev->errorcb)(bufev, what, bufev->cbarg);
917 client_tls_writecb(int fd, short event, void *d)
919 struct bufferevent *bufev = d;
920 struct client *client = bufev->cbarg;
923 short what = EVBUFFER_WRITE;
925 if (event == EV_TIMEOUT) {
926 what |= EVBUFFER_TIMEOUT;
930 if (EVBUFFER_LENGTH(bufev->output) != 0) {
931 ret = tls_write(client->ctx,
932 EVBUFFER_DATA(bufev->output),
933 EVBUFFER_LENGTH(bufev->output));
935 case TLS_WANT_POLLIN:
936 case TLS_WANT_POLLOUT:
939 what |= EVBUFFER_ERROR;
943 evbuffer_drain(bufev->output, len);
946 if (EVBUFFER_LENGTH(bufev->output) != 0)
947 event_add(&bufev->ev_write, NULL);
949 if (bufev->writecb != NULL &&
950 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
951 (*bufev->writecb)(bufev, bufev->cbarg);
955 event_add(&bufev->ev_write, NULL);
958 log_err(client, "tls error: %s", tls_error(client->ctx));
959 (*bufev->errorcb)(bufev, what, bufev->cbarg);
963 client_read(struct bufferevent *bev, void *d)
965 struct client *c = d;
966 struct evbuffer *src = EVBUFFER_INPUT(bev);
967 const char *parse_err = "invalid request";
968 char decoded[DOMAIN_NAME_LEN];
971 bufferevent_disable(bev, EVBUFFER_READ);
974 * libevent2 can still somehow call this function, even
975 * though I never enable EV_READ in the bufferevent. If
976 * that's the case, bail out.
978 if (c->type != REQUEST_UNDECIDED)
981 /* max url len + \r\n */
982 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
983 log_err(c, "too much data received");
984 start_reply(c, BAD_REQUEST, "bad request");
988 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
989 if (c->req == NULL) {
990 /* not enough data yet. */
991 bufferevent_enable(bev, EVBUFFER_READ);
994 c->reqlen = strlen(c->req);
995 if (c->reqlen > 1024+2) {
996 log_err(c, "URL too long");
997 start_reply(c, BAD_REQUEST, "bad request");
1001 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1002 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1003 log_err(c, "IRI parse error: %s", parse_err);
1004 start_reply(c, BAD_REQUEST, "bad request");
1008 if (apply_reverse_proxy(c))
1011 /* ignore the port number */
1012 if (strcmp(c->iri.schema, "gemini") ||
1013 strcmp(decoded, c->domain)) {
1014 start_reply(c, PROXY_REFUSED, "won't proxy request");
1018 if (apply_require_ca(c) ||
1019 apply_block_return(c)||
1027 client_write(struct bufferevent *bev, void *d)
1029 struct client *c = d;
1030 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1036 case REQUEST_UNDECIDED:
1038 * Ignore spurious calls when we still don't have idea
1039 * what to do with the request.
1044 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1045 log_warn(c, "read: %s", strerror(errno));
1046 client_error(bev, EVBUFFER_ERROR, c);
1048 } else if (r == 0) {
1051 } else if (r != sizeof(buf))
1052 c->type = REQUEST_DONE;
1053 bufferevent_write(bev, buf, r);
1057 /* TODO: handle big big directories better */
1058 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1059 const char *sufx = "";
1061 encode_path(nam, sizeof(nam),
1062 c->dir[c->diroff]->d_name);
1063 if (c->dir[c->diroff]->d_type == DT_DIR)
1065 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1066 free(c->dir[c->diroff]);
1071 c->type = REQUEST_DONE;
1073 event_add(&c->bev->ev_write, NULL);
1079 * Here we depend on fastcgi or proxy connection to
1085 if (EVBUFFER_LENGTH(out) == 0)
1092 client_error(struct bufferevent *bev, short error, void *d)
1094 struct client *c = d;
1096 c->type = REQUEST_DONE;
1098 if (error & EVBUFFER_TIMEOUT) {
1099 log_warn(c, "timeout reached, "
1100 "forcefully closing the connection");
1102 start_reply(c, BAD_REQUEST, "timeout");
1108 if (error & EVBUFFER_EOF) {
1113 log_err(c, "unknown bufferevent error %x", error);
1118 start_reply(struct client *c, int code, const char *meta)
1120 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1124 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1129 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1133 /* 2 digit status + space + 1024 max reply */
1137 if (c->type != REQUEST_FCGI &&
1138 c->type != REQUEST_PROXY &&
1139 !strcmp(meta, "text/gemini") &&
1140 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1141 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1148 bufferevent_write(c->bev, "\r\n", 2);
1150 if (!vhost_disable_log(c->host, c->iri.path))
1151 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1154 c->type = REQUEST_DONE;
1159 log_err(c, "evbuffer_add_printf error: no memory");
1160 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1165 log_warn(c, "reply header overflow");
1166 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1167 start_reply(c, TEMP_FAILURE, "internal error");
1171 client_close_ev(int fd, short event, void *d)
1173 struct client *c = d;
1175 switch (tls_close(c->ctx)) {
1176 case TLS_WANT_POLLIN:
1177 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1179 case TLS_WANT_POLLOUT:
1180 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1184 connected_clients--;
1204 client_proxy_close(int fd, short event, void *d)
1206 struct tls *ctx = d;
1213 switch (tls_close(ctx)) {
1214 case TLS_WANT_POLLIN:
1215 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1217 case TLS_WANT_POLLOUT:
1218 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1227 client_close(struct client *c)
1230 * We may end up calling client_close in various situations
1231 * and for the most unexpected reasons. Therefore, we need to
1232 * ensure that everything gets properly released once we reach
1236 SPLAY_REMOVE(client_tree_id, &clients, c);
1238 if (c->cgibev != NULL) {
1239 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1240 bufferevent_free(c->cgibev);
1246 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1247 bufferevent_free(c->bev);
1250 if (c->proxyevset &&
1251 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1253 event_del(&c->proxyev);
1256 if (c->pfd != -1 && c->proxyctx != NULL) {
1257 /* shut down the proxy TLS connection */
1258 client_proxy_close(c->pfd, 0, c->proxyctx);
1262 if (c->proxybev != NULL)
1263 bufferevent_free(c->proxybev);
1265 client_close_ev(c->fd, 0, c);
1269 do_accept(int sock, short et, void *d)
1272 struct sockaddr_storage addr;
1273 struct sockaddr *saddr;
1277 saddr = (struct sockaddr*)&addr;
1279 if ((fd = accept(sock, saddr, &len)) == -1) {
1280 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1281 errno == ECONNABORTED)
1283 fatal("accept: %s", strerror(errno));
1288 c = xcalloc(1, sizeof(*c));
1289 c->id = ++server_client_id;
1294 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1295 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1301 SPLAY_INSERT(client_tree_id, &clients, c);
1302 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1303 connected_clients++;
1307 client_by_id(int id)
1312 return SPLAY_FIND(client_tree_id, &clients, &find);
1316 handle_dispatch_imsg(int fd, short ev, void *d)
1318 struct imsgbuf *ibuf = d;
1322 if ((n = imsg_read(ibuf)) == -1) {
1323 if (errno == EAGAIN || errno == EWOULDBLOCK)
1329 fatal("connection closed."); /* XXX: fatalx */
1332 if ((n = imsg_get(ibuf, &imsg)) == -1)
1337 switch (imsg.hdr.type) {
1340 * Don't call event_loopbreak since we want to
1341 * finish handling the ongoing connections.
1349 signal_del(&siginfo);
1351 signal_del(&sigusr2);
1355 fatal("Unknown message %d", imsg.hdr.type);
1362 handle_siginfo(int fd, short ev, void *d)
1364 log_info(NULL, "%d connected clients", connected_clients);
1368 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1372 SPLAY_INIT(&clients);
1376 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1377 event_add(&e4, NULL);
1381 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1382 event_add(&e6, NULL);
1386 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1387 handle_dispatch_imsg, ibuf);
1388 event_add(&imsgev, NULL);
1393 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1394 signal_add(&siginfo, NULL);
1396 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1397 signal_add(&sigusr2, NULL);
1399 sandbox_server_process(conf.can_open_sockets);
1405 client_tree_cmp(struct client *a, struct client *b)
1409 else if (a->id < b->id)
1415 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)