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_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
69 static void handle_dispatch_imsg(int, short, void *);
70 static void handle_siginfo(int, short, void*);
72 static imsg_handlerfn *handlers[] = {
73 [IMSG_QUIT] = handle_imsg_quit,
76 static uint32_t server_client_id;
78 struct client_tree_id clients;
81 matches(const char *pattern, const char *path)
85 return !fnmatch(pattern, path, 0);
89 vhost_lang(struct vhost *v, const char *path)
93 if (v == NULL || path == NULL)
96 loc = TAILQ_FIRST(&v->locations);
97 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
98 if (loc->lang != NULL) {
99 if (matches(loc->match, path))
104 return TAILQ_FIRST(&v->locations)->lang;
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 != NULL) {
119 if (matches(loc->match, path))
120 return loc->default_mime;
124 loc = TAILQ_FIRST(&v->locations);
125 if (loc->default_mime != NULL)
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 != NULL) {
142 if (matches(loc->match, path))
147 loc = TAILQ_FIRST(&v->locations);
148 if (loc->index != NULL)
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): %s", strerror(errno));
373 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
374 fatal("fcntl(F_SETFL): %s", strerror(errno));
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: %s",
405 __func__, strerror(errno));
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(c, "handshake: missing SNI");
422 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
423 log_info(c, "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(c, "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 fatal("%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) == NULL)
546 if ((host = p->match_host) == NULL)
548 if ((port = p->match_port) == NULL)
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;
586 memset(&hints, 0, sizeof(hints));
587 hints.ai_family = AF_UNSPEC;
588 hints.ai_socktype = SOCK_STREAM;
590 /* XXX: asr_run? :> */
591 r = getaddrinfo(host, port, &hints, &res0);
593 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
594 host, port, gai_strerror(r));
598 for (res = res0; res; res = res->ai_next) {
599 sock = socket(res->ai_family, res->ai_socktype,
604 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
616 log_warn(c, "can't connect to %s:%s", host, port);
621 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
623 apply_reverse_proxy(struct client *c)
627 if ((p = matched_proxy(c)) == NULL)
632 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
635 log_debug(c, "opening proxy connection for %s:%s",
638 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
639 start_reply(c, PROXY_ERROR, "proxy error");
643 mark_nonblock(c->pfd);
644 if (proxy_init(c) == -1)
645 start_reply(c, PROXY_ERROR, "proxy error");
651 fcgi_open_sock(struct fcgi *f)
653 struct sockaddr_un addr;
656 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
657 log_err(NULL, "socket: %s", strerror(errno));
661 memset(&addr, 0, sizeof(addr));
662 addr.sun_family = AF_UNIX;
663 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
665 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
666 log_warn(NULL, "failed to connect to %s: %s", f->path,
676 fcgi_open_conn(struct fcgi *f)
678 struct addrinfo hints, *servinfo, *p;
681 memset(&hints, 0, sizeof(hints));
682 hints.ai_family = AF_UNSPEC;
683 hints.ai_socktype = SOCK_STREAM;
684 hints.ai_flags = AI_ADDRCONFIG;
686 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
687 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
692 for (p = servinfo; p != NULL; p = p->ai_next) {
693 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
696 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
704 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
708 freeaddrinfo(servinfo);
712 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
714 apply_fastcgi(struct client *c)
719 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
724 log_debug(c, "opening fastcgi connection for (%s,%s)",
728 c->pfd = fcgi_open_sock(f);
730 c->pfd = fcgi_open_conn(f);
733 start_reply(c, CGI_ERROR, "CGI error");
737 mark_nonblock(c->pfd);
739 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
741 if (c->cgibev == NULL) {
742 start_reply(c, TEMP_FAILURE, "internal server error");
746 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
752 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
754 apply_require_ca(struct client *c)
758 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
760 return check_matching_certificate(store, c);
764 open_dir(struct client *c)
770 log_debug(c, "in open_dir");
772 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
774 len = strlen(c->iri.path);
775 if (len > 0 && !ends_with(c->iri.path, "/")) {
776 redirect_canonical_dir(c);
780 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
781 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
782 if (!ends_with(c->sbuf, "/"))
783 strlcat(c->sbuf, "/", sizeof(c->sbuf));
784 before_file = strchr(c->sbuf, '\0');
785 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
787 if (len >= sizeof(c->sbuf)) {
788 start_reply(c, TEMP_FAILURE, "internal server error");
792 c->iri.path = c->sbuf;
794 /* close later unless we have to generate the dir listing */
798 switch (check_path(c, c->iri.path, &c->pfd)) {
800 c->type = REQUEST_FILE;
801 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
805 start_reply(c, TEMP_REDIRECT, c->sbuf);
811 if (!vhost_auto_index(c->host, c->iri.path)) {
812 start_reply(c, NOT_FOUND, "not found");
816 c->type = REQUEST_DIR;
818 c->dirlen = scandir_fd(dirfd, &c->dir,
819 root ? select_non_dotdot : select_non_dot,
821 if (c->dirlen == -1) {
822 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
823 c->pfd, c->host->domain, c->iri.path, strerror(errno));
824 start_reply(c, TEMP_FAILURE, "internal server error");
830 start_reply(c, SUCCESS, "text/gemini");
831 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
832 "# Index of %s\n\n", c->iri.path);
844 redirect_canonical_dir(struct client *c)
848 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
849 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
850 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
852 if (len >= sizeof(c->sbuf)) {
853 start_reply(c, TEMP_FAILURE, "internal server error");
857 start_reply(c, TEMP_REDIRECT, c->sbuf);
861 client_tls_readcb(int fd, short event, void *d)
863 struct bufferevent *bufev = d;
864 struct client *client = bufev->cbarg;
867 int what = EVBUFFER_READ;
868 int howmuch = IBUF_READ_SIZE;
869 char buf[IBUF_READ_SIZE];
871 if (event == EV_TIMEOUT) {
872 what |= EVBUFFER_TIMEOUT;
876 if (bufev->wm_read.high != 0)
877 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
879 switch (ret = tls_read(client->ctx, buf, howmuch)) {
880 case TLS_WANT_POLLIN:
881 case TLS_WANT_POLLOUT:
884 what |= EVBUFFER_ERROR;
890 what |= EVBUFFER_EOF;
894 if (evbuffer_add(bufev->input, buf, len) == -1) {
895 what |= EVBUFFER_ERROR;
899 event_add(&bufev->ev_read, NULL);
900 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
902 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
904 * here we could implement a read pressure policy.
908 if (bufev->readcb != NULL)
909 (*bufev->readcb)(bufev, bufev->cbarg);
914 event_add(&bufev->ev_read, NULL);
918 (*bufev->errorcb)(bufev, what, bufev->cbarg);
922 client_tls_writecb(int fd, short event, void *d)
924 struct bufferevent *bufev = d;
925 struct client *client = bufev->cbarg;
928 short what = EVBUFFER_WRITE;
930 if (event == EV_TIMEOUT) {
931 what |= EVBUFFER_TIMEOUT;
935 if (EVBUFFER_LENGTH(bufev->output) != 0) {
936 ret = tls_write(client->ctx,
937 EVBUFFER_DATA(bufev->output),
938 EVBUFFER_LENGTH(bufev->output));
940 case TLS_WANT_POLLIN:
941 case TLS_WANT_POLLOUT:
944 what |= EVBUFFER_ERROR;
948 evbuffer_drain(bufev->output, len);
951 if (EVBUFFER_LENGTH(bufev->output) != 0)
952 event_add(&bufev->ev_write, NULL);
954 if (bufev->writecb != NULL &&
955 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
956 (*bufev->writecb)(bufev, bufev->cbarg);
960 event_add(&bufev->ev_write, NULL);
963 log_err(client, "tls error: %s", tls_error(client->ctx));
964 (*bufev->errorcb)(bufev, what, bufev->cbarg);
968 client_read(struct bufferevent *bev, void *d)
970 struct client *c = d;
971 struct evbuffer *src = EVBUFFER_INPUT(bev);
972 const char *parse_err = "invalid request";
973 char decoded[DOMAIN_NAME_LEN];
976 bufferevent_disable(bev, EVBUFFER_READ);
979 * libevent2 can still somehow call this function, even
980 * though I never enable EV_READ in the bufferevent. If
981 * that's the case, bail out.
983 if (c->type != REQUEST_UNDECIDED)
986 /* max url len + \r\n */
987 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
988 log_err(c, "too much data received");
989 start_reply(c, BAD_REQUEST, "bad request");
993 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
994 if (c->req == NULL) {
995 /* not enough data yet. */
996 bufferevent_enable(bev, EVBUFFER_READ);
999 c->reqlen = strlen(c->req);
1000 if (c->reqlen > 1024+2) {
1001 log_err(c, "URL too long");
1002 start_reply(c, BAD_REQUEST, "bad request");
1006 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1007 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1008 log_err(c, "IRI parse error: %s", parse_err);
1009 start_reply(c, BAD_REQUEST, "bad request");
1013 if (apply_reverse_proxy(c))
1016 /* ignore the port number */
1017 if (strcmp(c->iri.schema, "gemini") ||
1018 strcmp(decoded, c->domain)) {
1019 start_reply(c, PROXY_REFUSED, "won't proxy request");
1023 if (apply_require_ca(c) ||
1024 apply_block_return(c)||
1032 client_write(struct bufferevent *bev, void *d)
1034 struct client *c = d;
1035 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1041 case REQUEST_UNDECIDED:
1043 * Ignore spurious calls when we still don't have idea
1044 * what to do with the request.
1049 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1050 log_warn(c, "read: %s", strerror(errno));
1051 client_error(bev, EVBUFFER_ERROR, c);
1053 } else if (r == 0) {
1056 } else if (r != sizeof(buf))
1057 c->type = REQUEST_DONE;
1058 bufferevent_write(bev, buf, r);
1062 /* TODO: handle big big directories better */
1063 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1064 const char *sufx = "";
1066 encode_path(nam, sizeof(nam),
1067 c->dir[c->diroff]->d_name);
1068 if (c->dir[c->diroff]->d_type == DT_DIR)
1070 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1071 free(c->dir[c->diroff]);
1076 c->type = REQUEST_DONE;
1078 event_add(&c->bev->ev_write, NULL);
1084 * Here we depend on fastcgi or proxy connection to
1090 if (EVBUFFER_LENGTH(out) == 0)
1097 client_error(struct bufferevent *bev, short error, void *d)
1099 struct client *c = d;
1101 c->type = REQUEST_DONE;
1103 if (error & EVBUFFER_TIMEOUT) {
1104 log_warn(c, "timeout reached, "
1105 "forcefully closing the connection");
1107 start_reply(c, BAD_REQUEST, "timeout");
1113 if (error & EVBUFFER_EOF) {
1118 log_err(c, "unknown bufferevent error %x", error);
1123 start_reply(struct client *c, int code, const char *meta)
1125 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1129 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1134 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1138 /* 2 digit status + space + 1024 max reply */
1142 if (c->type != REQUEST_FCGI &&
1143 c->type != REQUEST_PROXY &&
1144 !strcmp(meta, "text/gemini") &&
1145 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1146 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1153 bufferevent_write(c->bev, "\r\n", 2);
1155 if (!vhost_disable_log(c->host, c->iri.path))
1156 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1159 c->type = REQUEST_DONE;
1164 log_err(c, "evbuffer_add_printf error: no memory");
1165 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1170 log_warn(c, "reply header overflow");
1171 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1172 start_reply(c, TEMP_FAILURE, "internal error");
1176 client_close_ev(int fd, short event, void *d)
1178 struct client *c = d;
1180 switch (tls_close(c->ctx)) {
1181 case TLS_WANT_POLLIN:
1182 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1184 case TLS_WANT_POLLOUT:
1185 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1189 connected_clients--;
1209 client_proxy_close(int fd, short event, void *d)
1211 struct tls *ctx = d;
1218 switch (tls_close(ctx)) {
1219 case TLS_WANT_POLLIN:
1220 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1222 case TLS_WANT_POLLOUT:
1223 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1232 client_close(struct client *c)
1235 * We may end up calling client_close in various situations
1236 * and for the most unexpected reasons. Therefore, we need to
1237 * ensure that everything gets properly released once we reach
1241 SPLAY_REMOVE(client_tree_id, &clients, c);
1243 if (c->cgibev != NULL) {
1244 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1245 bufferevent_free(c->cgibev);
1251 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1252 bufferevent_free(c->bev);
1255 if (c->proxyevset &&
1256 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1258 event_del(&c->proxyev);
1261 if (c->pfd != -1 && c->proxyctx != NULL) {
1262 /* shut down the proxy TLS connection */
1263 client_proxy_close(c->pfd, 0, c->proxyctx);
1267 if (c->proxybev != NULL)
1268 bufferevent_free(c->proxybev);
1270 client_close_ev(c->fd, 0, c);
1274 do_accept(int sock, short et, void *d)
1277 struct sockaddr_storage addr;
1278 struct sockaddr *saddr;
1282 saddr = (struct sockaddr*)&addr;
1284 if ((fd = accept(sock, saddr, &len)) == -1) {
1285 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1286 errno == ECONNABORTED)
1288 fatal("accept: %s", strerror(errno));
1293 c = xcalloc(1, sizeof(*c));
1294 c->id = ++server_client_id;
1299 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1300 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1306 SPLAY_INSERT(client_tree_id, &clients, c);
1307 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1308 connected_clients++;
1312 client_by_id(int id)
1317 return SPLAY_FIND(client_tree_id, &clients, &find);
1321 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1324 * don't call event_loopbreak since we want to finish to
1325 * handle the ongoing connections.
1334 signal_del(&siginfo);
1336 signal_del(&sigusr2);
1340 handle_dispatch_imsg(int fd, short ev, void *d)
1342 struct imsgbuf *ibuf = d;
1343 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1347 handle_siginfo(int fd, short ev, void *d)
1349 log_info(NULL, "%d connected clients", connected_clients);
1353 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1357 SPLAY_INIT(&clients);
1361 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1362 event_add(&e4, NULL);
1366 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1367 event_add(&e6, NULL);
1371 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1372 handle_dispatch_imsg, ibuf);
1373 event_add(&imsgev, NULL);
1378 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1379 signal_add(&siginfo, NULL);
1381 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1382 signal_add(&sigusr2, NULL);
1384 sandbox_server_process(conf.can_open_sockets);
1390 client_tree_cmp(struct client *a, struct client *b)
1394 else if (a->id < b->id)
1400 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)