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 != '\0') {
94 if (matches(loc->match, path))
99 loc = TAILQ_FIRST(&v->locations);
100 if (*loc->lang == '\0')
106 vhost_default_mime(struct vhost *v, const char *path)
108 struct location *loc;
109 const char *default_mime = "application/octet-stream";
111 if (v == NULL || path == NULL)
114 loc = TAILQ_FIRST(&v->locations);
115 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
116 if (*loc->default_mime != '\0') {
117 if (matches(loc->match, path))
118 return loc->default_mime;
122 loc = TAILQ_FIRST(&v->locations);
123 if (*loc->default_mime != '\0')
124 return loc->default_mime;
129 vhost_index(struct vhost *v, const char *path)
131 struct location *loc;
132 const char *index = "index.gmi";
134 if (v == NULL || path == NULL)
137 loc = TAILQ_FIRST(&v->locations);
138 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
139 if (*loc->index != '\0') {
140 if (matches(loc->match, path))
145 loc = TAILQ_FIRST(&v->locations);
146 if (*loc->index != '\0')
152 vhost_auto_index(struct vhost *v, const char *path)
154 struct location *loc;
156 if (v == NULL || path == NULL)
159 loc = TAILQ_FIRST(&v->locations);
160 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
161 if (loc->auto_index != 0) {
162 if (matches(loc->match, path))
163 return loc->auto_index == 1;
167 loc = TAILQ_FIRST(&v->locations);
168 return loc->auto_index == 1;
172 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
174 struct location *loc;
176 if (v == NULL || path == NULL)
179 loc = TAILQ_FIRST(&v->locations);
180 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
181 if (loc->block_code != 0) {
182 if (matches(loc->match, path)) {
183 *code = loc->block_code;
184 *fmt = loc->block_fmt;
190 loc = TAILQ_FIRST(&v->locations);
191 *code = loc->block_code;
192 *fmt = loc->block_fmt;
193 return loc->block_code != 0;
197 vhost_fastcgi(struct vhost *v, const char *path)
199 struct location *loc;
201 if (v == NULL || path == NULL)
204 loc = TAILQ_FIRST(&v->locations);
205 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
207 if (matches(loc->match, path))
211 loc = TAILQ_FIRST(&v->locations);
216 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
218 struct location *loc;
221 if (v == NULL || path == NULL)
224 loc = TAILQ_FIRST(&v->locations);
225 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
227 if (loc->dirfd != -1)
228 if (matches(loc->match, path)) {
235 loc = TAILQ_FIRST(&v->locations);
240 vhost_strip(struct vhost *v, const char *path)
242 struct location *loc;
244 if (v == NULL || path == NULL)
247 loc = TAILQ_FIRST(&v->locations);
248 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
249 if (loc->strip != 0) {
250 if (matches(loc->match, path))
255 loc = TAILQ_FIRST(&v->locations);
260 vhost_require_ca(struct vhost *v, const char *path)
262 struct location *loc;
264 if (v == NULL || path == NULL)
267 loc = TAILQ_FIRST(&v->locations);
268 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
269 if (loc->reqca != NULL) {
270 if (matches(loc->match, path))
275 loc = TAILQ_FIRST(&v->locations);
280 vhost_disable_log(struct vhost *v, const char *path)
282 struct location *loc;
284 if (v == NULL || path == NULL)
287 loc = TAILQ_FIRST(&v->locations);
288 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
289 if (loc->disable_log && matches(loc->match, path))
293 loc = TAILQ_FIRST(&v->locations);
294 return loc->disable_log;
298 check_path(struct client *c, const char *path, int *fd)
304 assert(path != NULL);
307 * in send_dir we add an initial / (to be redirect-friendly),
308 * but here we want to skip it
313 strip = vhost_strip(c->host, path);
314 p = strip_path(path, strip);
321 dirfd = vhost_dirfd(c->host, path, &c->loc);
322 log_debug(c, "check_path: strip=%d path=%s original=%s",
324 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1) {
326 log_info(c, "can't open %s: %s", p, strerror(errno));
330 if (fstat(*fd, &sb) == -1) {
331 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
335 if (S_ISDIR(sb.st_mode))
336 return FILE_DIRECTORY;
342 open_file(struct client *c)
344 switch (check_path(c, c->iri.path, &c->pfd)) {
346 c->type = REQUEST_FILE;
347 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
355 start_reply(c, NOT_FOUND, "not found");
365 mark_nonblock(int fd)
369 if ((flags = fcntl(fd, F_GETFL)) == -1)
370 fatal("fcntl(F_GETFL): %s", strerror(errno));
371 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
372 fatal("fcntl(F_SETFL): %s", strerror(errno));
376 handle_handshake(int fd, short ev, void *d)
378 struct client *c = d;
381 const char *servname;
382 const char *parse_err = "unknown error";
384 switch (tls_handshake(c->ctx)) {
385 case 0: /* success */
386 case -1: /* already handshaked */
388 case TLS_WANT_POLLIN:
389 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
391 case TLS_WANT_POLLOUT:
392 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
399 c->bev = bufferevent_new(fd, client_read, client_write,
402 fatal("%s: failed to allocate client buffer: %s",
403 __func__, strerror(errno));
405 event_set(&c->bev->ev_read, c->fd, EV_READ,
406 client_tls_readcb, c->bev);
407 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
408 client_tls_writecb, c->bev);
411 evbuffer_unfreeze(c->bev->input, 0);
412 evbuffer_unfreeze(c->bev->output, 1);
415 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
416 log_debug(c, "handshake: missing SNI");
420 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
421 log_info(c, "puny_decode: %s", parse_err);
425 TAILQ_FOREACH(h, &hosts, vhosts) {
426 if (matches(h->domain, c->domain))
428 TAILQ_FOREACH(a, &h->aliases, aliases) {
429 if (matches(a->alias, c->domain))
435 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
436 servname != NULL ? servname : "(null)",
438 h != NULL ? h->domain : "(null)");
442 bufferevent_enable(c->bev, EV_READ);
447 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
451 strip_path(const char *path, int strip)
456 if ((t = strchr(path, '/')) == NULL) {
457 path = strchr(path, '\0');
468 fmt_sbuf(const char *fmt, struct client *c, const char *path)
473 memset(buf, 0, sizeof(buf));
474 for (i = 0; *fmt; ++fmt) {
475 if (i == sizeof(buf)-1 || *fmt == '%') {
476 strlcat(c->sbuf, buf, sizeof(c->sbuf));
477 memset(buf, 0, sizeof(buf));
488 strlcat(c->sbuf, "%", sizeof(c->sbuf));
492 strlcat(c->sbuf, "/", sizeof(c->sbuf));
493 strlcat(c->sbuf, path, sizeof(c->sbuf));
496 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
499 snprintf(buf, sizeof(buf), "%d", conf.port);
500 strlcat(c->sbuf, buf, sizeof(c->sbuf));
501 memset(buf, 0, sizeof(buf));
504 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
507 fatal("%s: unknown fmt specifier %c",
513 strlcat(c->sbuf, buf, sizeof(c->sbuf));
516 /* 1 if a matching `block return' (and apply it), 0 otherwise */
518 apply_block_return(struct client *c)
520 const char *fmt, *path;
523 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
526 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
527 fmt_sbuf(fmt, c, path);
529 start_reply(c, code, c->sbuf);
533 static struct proxy *
534 matched_proxy(struct client *c)
541 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
542 if (*(proto = p->match_proto) == '\0')
544 if (*(host = p->match_host) == '\0')
546 if (*(port = p->match_port) == '\0')
549 if (matches(proto, c->iri.schema) &&
550 matches(host, c->domain) &&
551 matches(port, c->iri.port))
559 check_matching_certificate(X509_STORE *store, struct client *c)
564 if (!tls_peer_cert_provided(c->ctx)) {
565 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
569 cert = tls_peer_cert_chain_pem(c->ctx, &len);
570 if (!validate_against_ca(store, cert, len)) {
571 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
579 proxy_socket(struct client *c, const char *host, const char *port)
581 struct addrinfo hints, *res, *res0;
584 memset(&hints, 0, sizeof(hints));
585 hints.ai_family = AF_UNSPEC;
586 hints.ai_socktype = SOCK_STREAM;
588 /* XXX: asr_run? :> */
589 r = getaddrinfo(host, port, &hints, &res0);
591 log_warn(c, "getaddrinfo(\"%s\", \"%s\"): %s",
592 host, port, gai_strerror(r));
596 for (res = res0; res; res = res->ai_next) {
597 sock = socket(res->ai_family, res->ai_socktype,
602 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
614 log_warn(c, "can't connect to %s:%s", host, port);
619 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
621 apply_reverse_proxy(struct client *c)
625 if ((p = matched_proxy(c)) == NULL)
630 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
633 log_debug(c, "opening proxy connection for %s:%s",
636 if ((c->pfd = proxy_socket(c, p->host, p->port)) == -1) {
637 start_reply(c, PROXY_ERROR, "proxy error");
641 mark_nonblock(c->pfd);
642 if (proxy_init(c) == -1)
643 start_reply(c, PROXY_ERROR, "proxy error");
649 fcgi_open_sock(struct fcgi *f)
651 struct sockaddr_un addr;
654 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
655 log_err(NULL, "socket: %s", strerror(errno));
659 memset(&addr, 0, sizeof(addr));
660 addr.sun_family = AF_UNIX;
661 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
663 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
664 log_warn(NULL, "failed to connect to %s: %s", f->path,
674 fcgi_open_conn(struct fcgi *f)
676 struct addrinfo hints, *servinfo, *p;
679 memset(&hints, 0, sizeof(hints));
680 hints.ai_family = AF_UNSPEC;
681 hints.ai_socktype = SOCK_STREAM;
682 hints.ai_flags = AI_ADDRCONFIG;
684 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
685 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
690 for (p = servinfo; p != NULL; p = p->ai_next) {
691 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
694 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
702 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
706 freeaddrinfo(servinfo);
710 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
712 apply_fastcgi(struct client *c)
717 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
722 log_debug(c, "opening fastcgi connection for (%s,%s)",
725 if (*f->port != '\0')
726 c->pfd = fcgi_open_sock(f);
728 c->pfd = fcgi_open_conn(f);
731 start_reply(c, CGI_ERROR, "CGI error");
735 mark_nonblock(c->pfd);
737 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
739 if (c->cgibev == NULL) {
740 start_reply(c, TEMP_FAILURE, "internal server error");
744 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
750 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
752 apply_require_ca(struct client *c)
756 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
758 return check_matching_certificate(store, c);
762 open_dir(struct client *c)
768 log_debug(c, "in open_dir");
770 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
772 len = strlen(c->iri.path);
773 if (len > 0 && !ends_with(c->iri.path, "/")) {
774 redirect_canonical_dir(c);
778 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
779 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
780 if (!ends_with(c->sbuf, "/"))
781 strlcat(c->sbuf, "/", sizeof(c->sbuf));
782 before_file = strchr(c->sbuf, '\0');
783 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
785 if (len >= sizeof(c->sbuf)) {
786 start_reply(c, TEMP_FAILURE, "internal server error");
790 c->iri.path = c->sbuf;
792 /* close later unless we have to generate the dir listing */
796 switch (check_path(c, c->iri.path, &c->pfd)) {
798 c->type = REQUEST_FILE;
799 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
803 start_reply(c, TEMP_REDIRECT, c->sbuf);
809 if (!vhost_auto_index(c->host, c->iri.path)) {
810 start_reply(c, NOT_FOUND, "not found");
814 c->type = REQUEST_DIR;
816 c->dirlen = scandir_fd(dirfd, &c->dir,
817 root ? select_non_dotdot : select_non_dot,
819 if (c->dirlen == -1) {
820 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
821 c->pfd, c->host->domain, c->iri.path, strerror(errno));
822 start_reply(c, TEMP_FAILURE, "internal server error");
828 start_reply(c, SUCCESS, "text/gemini");
829 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
830 "# Index of %s\n\n", c->iri.path);
842 redirect_canonical_dir(struct client *c)
846 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
847 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
848 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
850 if (len >= sizeof(c->sbuf)) {
851 start_reply(c, TEMP_FAILURE, "internal server error");
855 start_reply(c, TEMP_REDIRECT, c->sbuf);
859 client_tls_readcb(int fd, short event, void *d)
861 struct bufferevent *bufev = d;
862 struct client *client = bufev->cbarg;
865 int what = EVBUFFER_READ;
866 int howmuch = IBUF_READ_SIZE;
867 char buf[IBUF_READ_SIZE];
869 if (event == EV_TIMEOUT) {
870 what |= EVBUFFER_TIMEOUT;
874 if (bufev->wm_read.high != 0)
875 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
877 switch (ret = tls_read(client->ctx, buf, howmuch)) {
878 case TLS_WANT_POLLIN:
879 case TLS_WANT_POLLOUT:
882 what |= EVBUFFER_ERROR;
888 what |= EVBUFFER_EOF;
892 if (evbuffer_add(bufev->input, buf, len) == -1) {
893 what |= EVBUFFER_ERROR;
897 event_add(&bufev->ev_read, NULL);
898 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
900 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
902 * here we could implement a read pressure policy.
906 if (bufev->readcb != NULL)
907 (*bufev->readcb)(bufev, bufev->cbarg);
912 event_add(&bufev->ev_read, NULL);
916 (*bufev->errorcb)(bufev, what, bufev->cbarg);
920 client_tls_writecb(int fd, short event, void *d)
922 struct bufferevent *bufev = d;
923 struct client *client = bufev->cbarg;
926 short what = EVBUFFER_WRITE;
928 if (event == EV_TIMEOUT) {
929 what |= EVBUFFER_TIMEOUT;
933 if (EVBUFFER_LENGTH(bufev->output) != 0) {
934 ret = tls_write(client->ctx,
935 EVBUFFER_DATA(bufev->output),
936 EVBUFFER_LENGTH(bufev->output));
938 case TLS_WANT_POLLIN:
939 case TLS_WANT_POLLOUT:
942 what |= EVBUFFER_ERROR;
946 evbuffer_drain(bufev->output, len);
949 if (EVBUFFER_LENGTH(bufev->output) != 0)
950 event_add(&bufev->ev_write, NULL);
952 if (bufev->writecb != NULL &&
953 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
954 (*bufev->writecb)(bufev, bufev->cbarg);
958 event_add(&bufev->ev_write, NULL);
961 log_err(client, "tls error: %s", tls_error(client->ctx));
962 (*bufev->errorcb)(bufev, what, bufev->cbarg);
966 client_read(struct bufferevent *bev, void *d)
968 struct client *c = d;
969 struct evbuffer *src = EVBUFFER_INPUT(bev);
970 const char *parse_err = "invalid request";
971 char decoded[DOMAIN_NAME_LEN];
974 bufferevent_disable(bev, EVBUFFER_READ);
977 * libevent2 can still somehow call this function, even
978 * though I never enable EV_READ in the bufferevent. If
979 * that's the case, bail out.
981 if (c->type != REQUEST_UNDECIDED)
984 /* max url len + \r\n */
985 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
986 log_err(c, "too much data received");
987 start_reply(c, BAD_REQUEST, "bad request");
991 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
992 if (c->req == NULL) {
993 /* not enough data yet. */
994 bufferevent_enable(bev, EVBUFFER_READ);
997 c->reqlen = strlen(c->req);
998 if (c->reqlen > 1024+2) {
999 log_err(c, "URL too long");
1000 start_reply(c, BAD_REQUEST, "bad request");
1004 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1005 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1006 log_err(c, "IRI parse error: %s", parse_err);
1007 start_reply(c, BAD_REQUEST, "bad request");
1011 if (apply_reverse_proxy(c))
1014 /* ignore the port number */
1015 if (strcmp(c->iri.schema, "gemini") ||
1016 strcmp(decoded, c->domain)) {
1017 start_reply(c, PROXY_REFUSED, "won't proxy request");
1021 if (apply_require_ca(c) ||
1022 apply_block_return(c)||
1030 client_write(struct bufferevent *bev, void *d)
1032 struct client *c = d;
1033 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1039 case REQUEST_UNDECIDED:
1041 * Ignore spurious calls when we still don't have idea
1042 * what to do with the request.
1047 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1048 log_warn(c, "read: %s", strerror(errno));
1049 client_error(bev, EVBUFFER_ERROR, c);
1051 } else if (r == 0) {
1054 } else if (r != sizeof(buf))
1055 c->type = REQUEST_DONE;
1056 bufferevent_write(bev, buf, r);
1060 /* TODO: handle big big directories better */
1061 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1062 const char *sufx = "";
1064 encode_path(nam, sizeof(nam),
1065 c->dir[c->diroff]->d_name);
1066 if (c->dir[c->diroff]->d_type == DT_DIR)
1068 evbuffer_add_printf(out, "=> ./%s%s\n", nam, sufx);
1069 free(c->dir[c->diroff]);
1074 c->type = REQUEST_DONE;
1076 event_add(&c->bev->ev_write, NULL);
1082 * Here we depend on fastcgi or proxy connection to
1088 if (EVBUFFER_LENGTH(out) == 0)
1095 client_error(struct bufferevent *bev, short error, void *d)
1097 struct client *c = d;
1099 c->type = REQUEST_DONE;
1101 if (error & EVBUFFER_TIMEOUT) {
1102 log_warn(c, "timeout reached, "
1103 "forcefully closing the connection");
1105 start_reply(c, BAD_REQUEST, "timeout");
1111 if (error & EVBUFFER_EOF) {
1116 log_err(c, "unknown bufferevent error %x", error);
1121 start_reply(struct client *c, int code, const char *meta)
1123 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1127 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1132 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1136 /* 2 digit status + space + 1024 max reply */
1140 if (c->type != REQUEST_FCGI &&
1141 c->type != REQUEST_PROXY &&
1142 !strcmp(meta, "text/gemini") &&
1143 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1144 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1151 bufferevent_write(c->bev, "\r\n", 2);
1153 if (!vhost_disable_log(c->host, c->iri.path))
1154 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1157 c->type = REQUEST_DONE;
1162 log_err(c, "evbuffer_add_printf error: no memory");
1163 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1168 log_warn(c, "reply header overflow");
1169 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1170 start_reply(c, TEMP_FAILURE, "internal error");
1174 client_close_ev(int fd, short event, void *d)
1176 struct client *c = d;
1178 switch (tls_close(c->ctx)) {
1179 case TLS_WANT_POLLIN:
1180 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1182 case TLS_WANT_POLLOUT:
1183 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1187 connected_clients--;
1207 client_proxy_close(int fd, short event, void *d)
1209 struct tls *ctx = d;
1216 switch (tls_close(ctx)) {
1217 case TLS_WANT_POLLIN:
1218 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1220 case TLS_WANT_POLLOUT:
1221 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1230 client_close(struct client *c)
1233 * We may end up calling client_close in various situations
1234 * and for the most unexpected reasons. Therefore, we need to
1235 * ensure that everything gets properly released once we reach
1239 SPLAY_REMOVE(client_tree_id, &clients, c);
1241 if (c->cgibev != NULL) {
1242 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1243 bufferevent_free(c->cgibev);
1249 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1250 bufferevent_free(c->bev);
1253 if (c->proxyevset &&
1254 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1256 event_del(&c->proxyev);
1259 if (c->pfd != -1 && c->proxyctx != NULL) {
1260 /* shut down the proxy TLS connection */
1261 client_proxy_close(c->pfd, 0, c->proxyctx);
1265 if (c->proxybev != NULL)
1266 bufferevent_free(c->proxybev);
1268 client_close_ev(c->fd, 0, c);
1272 do_accept(int sock, short et, void *d)
1275 struct sockaddr_storage addr;
1276 struct sockaddr *saddr;
1280 saddr = (struct sockaddr*)&addr;
1282 if ((fd = accept(sock, saddr, &len)) == -1) {
1283 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1284 errno == ECONNABORTED)
1286 fatal("accept: %s", strerror(errno));
1291 c = xcalloc(1, sizeof(*c));
1292 c->id = ++server_client_id;
1297 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1298 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1304 SPLAY_INSERT(client_tree_id, &clients, c);
1305 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1306 connected_clients++;
1310 client_by_id(int id)
1315 return SPLAY_FIND(client_tree_id, &clients, &find);
1319 handle_dispatch_imsg(int fd, short ev, void *d)
1321 struct imsgbuf *ibuf = d;
1325 if ((n = imsg_read(ibuf)) == -1) {
1326 if (errno == EAGAIN || errno == EWOULDBLOCK)
1332 fatal("connection closed."); /* XXX: fatalx */
1335 if ((n = imsg_get(ibuf, &imsg)) == -1)
1340 switch (imsg.hdr.type) {
1343 * Don't call event_loopbreak since we want to
1344 * finish handling the ongoing connections.
1352 signal_del(&siginfo);
1354 signal_del(&sigusr2);
1358 fatal("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(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1375 SPLAY_INIT(&clients);
1379 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1380 event_add(&e4, NULL);
1384 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1385 event_add(&e6, NULL);
1389 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
1390 handle_dispatch_imsg, ibuf);
1391 event_add(&imsgev, NULL);
1396 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1397 signal_add(&siginfo, NULL);
1399 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1400 signal_add(&sigusr2, NULL);
1402 sandbox_server_process(conf.can_open_sockets);
1408 client_tree_cmp(struct client *a, struct client *b)
1412 else if (a->id < b->id)
1418 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)