2 * Copyright (c) 2021 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.
30 #define MIN(a, b) ((a) < (b) ? (a) : (b))
34 static struct tls *ctx;
36 static struct event e4, e6, imsgev, siginfo, sigusr2;
37 static int has_ipv6, has_siginfo;
39 int connected_clients;
41 static inline int matches(const char*, const char*);
43 static int check_path(struct client*, const char*, int*);
44 static void open_file(struct client*);
45 static void check_for_cgi(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 size_t host_nth(struct vhost*);
55 static void start_cgi(const char*, const char*, 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 cgi_read(struct bufferevent *, void *);
69 static void cgi_write(struct bufferevent *, void *);
70 static void cgi_error(struct bufferevent *, short, void *);
72 static void do_accept(int, short, void*);
74 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
75 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
76 static void handle_imsg_conn_fd(struct imsgbuf*, struct imsg*, size_t);
77 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
78 static void handle_dispatch_imsg(int, short, void *);
79 static void handle_siginfo(int, short, void*);
81 static imsg_handlerfn *handlers[] = {
82 [IMSG_QUIT] = handle_imsg_quit,
83 [IMSG_CGI_RES] = handle_imsg_cgi_res,
84 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
85 [IMSG_CONN_FD] = handle_imsg_conn_fd,
88 static uint32_t server_client_id;
90 struct client_tree_id clients;
93 matches(const char *pattern, const char *path)
97 return !fnmatch(pattern, path, 0);
101 vhost_lang(struct vhost *v, const char *path)
103 struct location *loc;
105 if (v == NULL || path == NULL)
108 loc = TAILQ_FIRST(&v->locations);
109 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
110 if (loc->lang != NULL) {
111 if (matches(loc->match, path))
116 return TAILQ_FIRST(&v->locations)->lang;
120 vhost_default_mime(struct vhost *v, const char *path)
122 struct location *loc;
123 const char *default_mime = "application/octet-stream";
125 if (v == NULL || path == NULL)
128 loc = TAILQ_FIRST(&v->locations);
129 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
130 if (loc->default_mime != NULL) {
131 if (matches(loc->match, path))
132 return loc->default_mime;
136 loc = TAILQ_FIRST(&v->locations);
137 if (loc->default_mime != NULL)
138 return loc->default_mime;
143 vhost_index(struct vhost *v, const char *path)
145 struct location *loc;
146 const char *index = "index.gmi";
148 if (v == NULL || path == NULL)
151 loc = TAILQ_FIRST(&v->locations);
152 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
153 if (loc->index != NULL) {
154 if (matches(loc->match, path))
159 loc = TAILQ_FIRST(&v->locations);
160 if (loc->index != NULL)
166 vhost_auto_index(struct vhost *v, const char *path)
168 struct location *loc;
170 if (v == NULL || path == NULL)
173 loc = TAILQ_FIRST(&v->locations);
174 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
175 if (loc->auto_index != 0) {
176 if (matches(loc->match, path))
177 return loc->auto_index == 1;
181 loc = TAILQ_FIRST(&v->locations);
182 return loc->auto_index == 1;
186 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
188 struct location *loc;
190 if (v == NULL || path == NULL)
193 loc = TAILQ_FIRST(&v->locations);
194 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
195 if (loc->block_code != 0) {
196 if (matches(loc->match, path)) {
197 *code = loc->block_code;
198 *fmt = loc->block_fmt;
204 loc = TAILQ_FIRST(&v->locations);
205 *code = loc->block_code;
206 *fmt = loc->block_fmt;
207 return loc->block_code != 0;
211 vhost_fastcgi(struct vhost *v, const char *path)
213 struct location *loc;
215 if (v == NULL || path == NULL)
218 loc = TAILQ_FIRST(&v->locations);
219 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
221 if (matches(loc->match, path))
225 loc = TAILQ_FIRST(&v->locations);
230 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
232 struct location *loc;
235 if (v == NULL || path == NULL)
238 loc = TAILQ_FIRST(&v->locations);
239 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
241 if (loc->dirfd != -1)
242 if (matches(loc->match, path)) {
249 loc = TAILQ_FIRST(&v->locations);
254 vhost_strip(struct vhost *v, const char *path)
256 struct location *loc;
258 if (v == NULL || path == NULL)
261 loc = TAILQ_FIRST(&v->locations);
262 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
263 if (loc->strip != 0) {
264 if (matches(loc->match, path))
269 loc = TAILQ_FIRST(&v->locations);
274 vhost_require_ca(struct vhost *v, const char *path)
276 struct location *loc;
278 if (v == NULL || path == NULL)
281 loc = TAILQ_FIRST(&v->locations);
282 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
283 if (loc->reqca != NULL) {
284 if (matches(loc->match, path))
289 loc = TAILQ_FIRST(&v->locations);
294 vhost_disable_log(struct vhost *v, const char *path)
296 struct location *loc;
298 if (v == NULL || path == NULL)
301 loc = TAILQ_FIRST(&v->locations);
302 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
303 if (loc->disable_log && matches(loc->match, path))
307 loc = TAILQ_FIRST(&v->locations);
308 return loc->disable_log;
312 check_path(struct client *c, const char *path, int *fd)
318 assert(path != NULL);
321 * in send_dir we add an initial / (to be redirect-friendly),
322 * but here we want to skip it
327 strip = vhost_strip(c->host, path);
328 p = strip_path(path, strip);
335 dirfd = vhost_dirfd(c->host, path, &c->loc);
336 log_debug(c, "check_path: strip=%d path=%s original=%s",
338 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
341 if (fstat(*fd, &sb) == -1) {
342 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
346 if (S_ISDIR(sb.st_mode))
347 return FILE_DIRECTORY;
349 if (sb.st_mode & S_IXUSR)
350 return FILE_EXECUTABLE;
356 open_file(struct client *c)
358 switch (check_path(c, c->iri.path, &c->pfd)) {
359 case FILE_EXECUTABLE:
360 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
361 start_cgi(c->iri.path, "", c);
368 c->type = REQUEST_FILE;
369 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
377 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
381 start_reply(c, NOT_FOUND, "not found");
391 * the inverse of this algorithm, i.e. starting from the start of the
392 * path + strlen(cgi), and checking if each component, should be
393 * faster. But it's tedious to write. This does the opposite: starts
394 * from the end and strip one component at a time, until either an
395 * executable is found or we emptied the path.
398 check_for_cgi(struct client *c)
403 strlcpy(path, c->iri.path, sizeof(path));
404 end = strchr(path, '\0');
408 * go up one level. UNIX paths are simple and POSIX
409 * dirname, with its ambiguities on if the given
410 * pointer is changed or not, gives me headaches.
412 while (*end != '/' && end > path)
420 switch (check_path(c, path, &c->pfd)) {
421 case FILE_EXECUTABLE:
422 start_cgi(path, end+1, c);
435 start_reply(c, NOT_FOUND, "not found");
440 mark_nonblock(int fd)
444 if ((flags = fcntl(fd, F_GETFL)) == -1)
445 fatal("fcntl(F_GETFL): %s", strerror(errno));
446 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
447 fatal("fcntl(F_SETFL): %s", strerror(errno));
451 handle_handshake(int fd, short ev, void *d)
453 struct client *c = d;
456 const char *servname;
457 const char *parse_err = "unknown error";
459 switch (tls_handshake(c->ctx)) {
460 case 0: /* success */
461 case -1: /* already handshaked */
463 case TLS_WANT_POLLIN:
464 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
466 case TLS_WANT_POLLOUT:
467 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
474 c->bev = bufferevent_new(fd, client_read, client_write,
477 fatal("%s: failed to allocate client buffer: %s",
478 __func__, strerror(errno));
480 event_set(&c->bev->ev_read, c->fd, EV_READ,
481 client_tls_readcb, c->bev);
482 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
483 client_tls_writecb, c->bev);
486 evbuffer_unfreeze(c->bev->input, 0);
487 evbuffer_unfreeze(c->bev->output, 1);
490 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
491 log_debug(c, "handshake: missing SNI");
495 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
496 log_info(c, "puny_decode: %s", parse_err);
500 TAILQ_FOREACH(h, &hosts, vhosts) {
501 if (matches(h->domain, c->domain))
503 TAILQ_FOREACH(a, &h->aliases, aliases) {
504 if (matches(a->alias, c->domain))
510 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
511 servname != NULL ? servname : "(null)",
513 h != NULL ? h->domain : "(null)");
517 bufferevent_enable(c->bev, EV_READ);
522 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
526 strip_path(const char *path, int strip)
531 if ((t = strchr(path, '/')) == NULL) {
532 path = strchr(path, '\0');
543 fmt_sbuf(const char *fmt, struct client *c, const char *path)
548 memset(buf, 0, sizeof(buf));
549 for (i = 0; *fmt; ++fmt) {
550 if (i == sizeof(buf)-1 || *fmt == '%') {
551 strlcat(c->sbuf, buf, sizeof(c->sbuf));
552 memset(buf, 0, sizeof(buf));
563 strlcat(c->sbuf, "%", sizeof(c->sbuf));
567 strlcat(c->sbuf, "/", sizeof(c->sbuf));
568 strlcat(c->sbuf, path, sizeof(c->sbuf));
571 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
574 snprintf(buf, sizeof(buf), "%d", conf.port);
575 strlcat(c->sbuf, buf, sizeof(c->sbuf));
576 memset(buf, 0, sizeof(buf));
579 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
582 fatal("%s: unknown fmt specifier %c",
588 strlcat(c->sbuf, buf, sizeof(c->sbuf));
591 /* 1 if a matching `block return' (and apply it), 0 otherwise */
593 apply_block_return(struct client *c)
595 const char *fmt, *path;
598 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
601 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
602 fmt_sbuf(fmt, c, path);
604 start_reply(c, code, c->sbuf);
608 static struct proxy *
609 matched_proxy(struct client *c)
616 TAILQ_FOREACH(p, &c->host->proxies, proxies) {
617 if ((proto = p->match_proto) == NULL)
619 if ((host = p->match_host) == NULL)
621 if ((port = p->match_port) == NULL)
624 if (matches(proto, c->iri.schema) &&
625 matches(host, c->domain) &&
626 matches(port, c->iri.port))
634 check_matching_certificate(X509_STORE *store, struct client *c)
639 if (!tls_peer_cert_provided(c->ctx)) {
640 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
644 cert = tls_peer_cert_chain_pem(c->ctx, &len);
645 if (!validate_against_ca(store, cert, len)) {
646 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
653 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
655 apply_reverse_proxy(struct client *c)
660 if ((p = matched_proxy(c)) == NULL)
665 if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
668 log_debug(c, "opening proxy connection for %s:%s",
671 strlcpy(r.host, p->host, sizeof(r.host));
672 strlcpy(r.port, p->port, sizeof(r.port));
674 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
680 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
682 apply_fastcgi(struct client *c)
687 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
692 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
693 f->path, f->port, f->prog);
695 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
701 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
703 apply_require_ca(struct client *c)
707 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
709 return check_matching_certificate(store, c);
713 host_nth(struct vhost *h)
718 TAILQ_FOREACH(v, &hosts, vhosts) {
728 start_cgi(const char *spath, const char *relpath, struct client *c)
730 char addr[NI_MAXHOST];
735 c->type = REQUEST_CGI;
737 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
742 fatal("getnameinfo failed");
744 memset(&req, 0, sizeof(req));
746 memcpy(req.buf, c->req, c->reqlen);
748 req.iri_schema_off = c->iri.schema - c->req;
749 req.iri_host_off = c->iri.host - c->req;
750 req.iri_port_off = c->iri.port - c->req;
751 req.iri_path_off = c->iri.path - c->req;
752 req.iri_query_off = c->iri.query - c->req;
753 req.iri_fragment_off = c->iri.fragment - c->req;
755 req.iri_portno = c->iri.port_no;
757 strlcpy(req.spath, spath, sizeof(req.spath));
758 strlcpy(req.relpath, relpath, sizeof(req.relpath));
759 strlcpy(req.addr, addr, sizeof(req.addr));
761 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
762 strlcpy(req.subject, t, sizeof(req.subject));
763 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
764 strlcpy(req.issuer, t, sizeof(req.issuer));
765 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
766 strlcpy(req.hash, t, sizeof(req.hash));
767 if ((t = tls_conn_version(c->ctx)) != NULL)
768 strlcpy(req.version, t, sizeof(req.version));
769 if ((t = tls_conn_cipher(c->ctx)) != NULL)
770 strlcpy(req.cipher, t, sizeof(req.cipher));
772 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
773 req.notbefore = tls_peer_cert_notbefore(c->ctx);
774 req.notafter = tls_peer_cert_notafter(c->ctx);
776 req.host_off = host_nth(c->host);
777 req.loc_off = c->loc;
779 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
786 open_dir(struct client *c)
792 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
794 len = strlen(c->iri.path);
795 if (len > 0 && !ends_with(c->iri.path, "/")) {
796 redirect_canonical_dir(c);
800 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
801 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
802 if (!ends_with(c->sbuf, "/"))
803 strlcat(c->sbuf, "/", sizeof(c->sbuf));
804 before_file = strchr(c->sbuf, '\0');
805 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
807 if (len >= sizeof(c->sbuf)) {
808 start_reply(c, TEMP_FAILURE, "internal server error");
812 c->iri.path = c->sbuf;
814 /* close later unless we have to generate the dir listing */
818 switch (check_path(c, c->iri.path, &c->pfd)) {
819 case FILE_EXECUTABLE:
820 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
821 start_cgi(c->iri.path, "", c);
828 c->type = REQUEST_FILE;
829 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
833 start_reply(c, TEMP_REDIRECT, c->sbuf);
839 if (!vhost_auto_index(c->host, c->iri.path)) {
840 start_reply(c, NOT_FOUND, "not found");
844 c->type = REQUEST_DIR;
846 c->dirlen = scandir_fd(dirfd, &c->dir,
847 root ? select_non_dotdot : select_non_dot,
849 if (c->dirlen == -1) {
850 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
851 c->pfd, c->host->domain, c->iri.path, strerror(errno));
852 start_reply(c, TEMP_FAILURE, "internal server error");
858 start_reply(c, SUCCESS, "text/gemini");
859 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
860 "# Index of %s\n\n", c->iri.path);
872 redirect_canonical_dir(struct client *c)
876 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
877 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
878 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
880 if (len >= sizeof(c->sbuf)) {
881 start_reply(c, TEMP_FAILURE, "internal server error");
885 start_reply(c, TEMP_REDIRECT, c->sbuf);
889 client_tls_readcb(int fd, short event, void *d)
891 struct bufferevent *bufev = d;
892 struct client *client = bufev->cbarg;
895 int what = EVBUFFER_READ;
896 int howmuch = IBUF_READ_SIZE;
897 char buf[IBUF_READ_SIZE];
899 if (event == EV_TIMEOUT) {
900 what |= EVBUFFER_TIMEOUT;
904 if (bufev->wm_read.high != 0)
905 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
907 switch (ret = tls_read(client->ctx, buf, howmuch)) {
908 case TLS_WANT_POLLIN:
909 case TLS_WANT_POLLOUT:
912 what |= EVBUFFER_ERROR;
918 what |= EVBUFFER_EOF;
922 if (evbuffer_add(bufev->input, buf, len) == -1) {
923 what |= EVBUFFER_ERROR;
927 event_add(&bufev->ev_read, NULL);
928 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
930 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
932 * here we could implement a read pressure policy.
936 if (bufev->readcb != NULL)
937 (*bufev->readcb)(bufev, bufev->cbarg);
942 event_add(&bufev->ev_read, NULL);
946 (*bufev->errorcb)(bufev, what, bufev->cbarg);
950 client_tls_writecb(int fd, short event, void *d)
952 struct bufferevent *bufev = d;
953 struct client *client = bufev->cbarg;
956 short what = EVBUFFER_WRITE;
958 if (event == EV_TIMEOUT) {
959 what |= EVBUFFER_TIMEOUT;
963 if (EVBUFFER_LENGTH(bufev->output) != 0) {
964 ret = tls_write(client->ctx,
965 EVBUFFER_DATA(bufev->output),
966 EVBUFFER_LENGTH(bufev->output));
968 case TLS_WANT_POLLIN:
969 case TLS_WANT_POLLOUT:
972 what |= EVBUFFER_ERROR;
976 evbuffer_drain(bufev->output, len);
979 if (EVBUFFER_LENGTH(bufev->output) != 0)
980 event_add(&bufev->ev_write, NULL);
982 if (bufev->writecb != NULL &&
983 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
984 (*bufev->writecb)(bufev, bufev->cbarg);
988 event_add(&bufev->ev_write, NULL);
991 log_err(client, "tls error: %s", tls_error(client->ctx));
992 (*bufev->errorcb)(bufev, what, bufev->cbarg);
996 client_read(struct bufferevent *bev, void *d)
998 struct client *c = d;
999 struct evbuffer *src = EVBUFFER_INPUT(bev);
1000 const char *parse_err = "invalid request";
1001 char decoded[DOMAIN_NAME_LEN];
1004 bufferevent_disable(bev, EVBUFFER_READ);
1007 * libevent2 can still somehow call this function, even
1008 * though I never enable EV_READ in the bufferevent. If
1009 * that's the case, bail out.
1011 if (c->type != REQUEST_UNDECIDED)
1014 /* max url len + \r\n */
1015 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
1016 log_err(c, "too much data received");
1017 start_reply(c, BAD_REQUEST, "bad request");
1021 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1022 if (c->req == NULL) {
1023 /* not enough data yet. */
1024 bufferevent_enable(bev, EVBUFFER_READ);
1027 c->reqlen = strlen(c->req);
1028 if (c->reqlen > 1024+2) {
1029 log_err(c, "URL too long");
1030 start_reply(c, BAD_REQUEST, "bad request");
1034 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1035 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1036 log_err(c, "IRI parse error: %s", parse_err);
1037 start_reply(c, BAD_REQUEST, "bad request");
1041 if (apply_reverse_proxy(c))
1044 /* ignore the port number */
1045 if (strcmp(c->iri.schema, "gemini") ||
1046 strcmp(decoded, c->domain)) {
1047 start_reply(c, PROXY_REFUSED, "won't proxy request");
1051 if (apply_require_ca(c) ||
1052 apply_block_return(c)||
1056 if (c->host->entrypoint != NULL) {
1058 start_cgi(c->host->entrypoint, c->iri.path, c);
1066 client_write(struct bufferevent *bev, void *d)
1068 struct client *c = d;
1069 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1074 case REQUEST_UNDECIDED:
1076 * Ignore spurious calls when we still don't have idea
1077 * what to do with the request.
1082 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1083 log_warn(c, "read: %s", strerror(errno));
1084 client_error(bev, EVBUFFER_ERROR, c);
1086 } else if (r == 0) {
1089 } else if (r != sizeof(buf))
1090 c->type = REQUEST_DONE;
1091 bufferevent_write(bev, buf, r);
1095 /* TODO: handle big big directories better */
1096 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1097 evbuffer_add_printf(out, "=> %s\n",
1098 c->dir[c->diroff]->d_name);
1099 free(c->dir[c->diroff]);
1104 c->type = REQUEST_DONE;
1106 event_add(&c->bev->ev_write, NULL);
1113 * Here we depend on the cgi/fastcgi or proxy
1114 * connection to provide data.
1119 if (EVBUFFER_LENGTH(out) == 0)
1126 client_error(struct bufferevent *bev, short error, void *d)
1128 struct client *c = d;
1130 c->type = REQUEST_DONE;
1132 if (error & EVBUFFER_TIMEOUT) {
1133 log_warn(c, "timeout reached, "
1134 "forcefully closing the connection");
1136 start_reply(c, BAD_REQUEST, "timeout");
1142 if (error & EVBUFFER_EOF) {
1147 log_err(c, "unknown bufferevent error %x", error);
1152 start_reply(struct client *c, int code, const char *meta)
1154 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1158 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1163 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1167 /* 2 digit status + space + 1024 max reply */
1171 if (c->type != REQUEST_CGI &&
1172 c->type != REQUEST_FCGI &&
1173 c->type != REQUEST_PROXY &&
1174 !strcmp(meta, "text/gemini") &&
1175 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1176 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1183 bufferevent_write(c->bev, "\r\n", 2);
1185 if (!vhost_disable_log(c->host, c->iri.path))
1186 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1189 c->type = REQUEST_DONE;
1194 log_err(c, "evbuffer_add_printf error: no memory");
1195 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1200 log_warn(c, "reply header overflow");
1201 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1202 start_reply(c, TEMP_FAILURE, "internal error");
1206 client_close_ev(int fd, short event, void *d)
1208 struct client *c = d;
1210 switch (tls_close(c->ctx)) {
1211 case TLS_WANT_POLLIN:
1212 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1214 case TLS_WANT_POLLOUT:
1215 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1219 connected_clients--;
1239 client_proxy_close(int fd, short event, void *d)
1241 struct tls *ctx = d;
1248 switch (tls_close(ctx)) {
1249 case TLS_WANT_POLLIN:
1250 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1252 case TLS_WANT_POLLOUT:
1253 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1262 client_close(struct client *c)
1265 * We may end up calling client_close in various situations
1266 * and for the most unexpected reasons. Therefore, we need to
1267 * ensure that everything gets properly released once we reach
1271 SPLAY_REMOVE(client_tree_id, &clients, c);
1273 if (c->cgibev != NULL) {
1274 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1275 bufferevent_free(c->cgibev);
1281 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1282 bufferevent_free(c->bev);
1285 if (c->proxyevset &&
1286 event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL)) {
1288 event_del(&c->proxyev);
1291 if (c->pfd != -1 && c->proxyctx != NULL) {
1292 /* shut down the proxy TLS connection */
1293 client_proxy_close(c->pfd, 0, c->proxyctx);
1297 if (c->proxybev != NULL)
1298 bufferevent_free(c->proxybev);
1300 client_close_ev(c->fd, 0, c);
1304 cgi_read(struct bufferevent *bev, void *d)
1306 struct client *client = d;
1307 struct evbuffer *src = EVBUFFER_INPUT(bev);
1312 /* intercept the header */
1313 if (client->code == 0) {
1314 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1315 if (header == NULL) {
1316 /* max reply + \r\n */
1317 if (EVBUFFER_LENGTH(src) > 1029) {
1318 log_warn(client, "CGI script is trying to "
1319 "send a header too long.");
1320 cgi_error(bev, EVBUFFER_READ, client);
1327 if (len < 3 || len > 1029 ||
1328 !isdigit(header[0]) ||
1329 !isdigit(header[1]) ||
1330 !isspace(header[2])) {
1332 log_warn(client, "CGI script is trying to send a "
1333 "malformed header");
1334 cgi_error(bev, EVBUFFER_READ, client);
1338 client->header = header;
1339 code = (header[0] - '0') * 10 + (header[1] - '0');
1341 if (code < 10 || code >= 70) {
1342 log_warn(client, "CGI script is trying to send an "
1343 "invalid reply code (%d)", code);
1344 cgi_error(bev, EVBUFFER_READ, client);
1348 start_reply(client, code, header + 3);
1350 if (client->code < 20 || client->code > 29) {
1351 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1356 bufferevent_write_buffer(client->bev, src);
1360 cgi_write(struct bufferevent *bev, void *d)
1363 * Never called. We don't send data to a CGI script.
1369 cgi_error(struct bufferevent *bev, short error, void *d)
1371 struct client *client = d;
1373 if (error & EVBUFFER_ERROR)
1374 log_err(client, "%s: evbuffer error (%x): %s",
1375 __func__, error, strerror(errno));
1377 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1378 bufferevent_free(bev);
1379 client->cgibev = NULL;
1384 client->type = REQUEST_DONE;
1385 if (client->code != 0)
1386 client_write(client->bev, client);
1388 start_reply(client, CGI_ERROR, "CGI error");
1392 do_accept(int sock, short et, void *d)
1395 struct sockaddr_storage addr;
1396 struct sockaddr *saddr;
1400 saddr = (struct sockaddr*)&addr;
1402 if ((fd = accept(sock, saddr, &len)) == -1) {
1403 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1404 errno == ECONNABORTED)
1406 fatal("accept: %s", strerror(errno));
1411 c = xcalloc(1, sizeof(*c));
1412 c->id = ++server_client_id;
1417 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1418 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1424 SPLAY_INSERT(client_tree_id, &clients, c);
1425 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1426 connected_clients++;
1430 client_by_id(int id)
1435 return SPLAY_FIND(client_tree_id, &clients, &find);
1439 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1443 if ((c = client_by_id(imsg->hdr.peerid)) == NULL) {
1449 if ((c->pfd = imsg->fd) == -1) {
1450 start_reply(c, TEMP_FAILURE, "internal server error");
1454 c->type = REQUEST_CGI;
1456 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1459 bufferevent_enable(c->cgibev, EV_READ);
1463 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1468 id = imsg->hdr.peerid;
1470 if ((c = client_by_id(id)) == NULL) {
1476 if ((c->pfd = imsg->fd) == -1) {
1477 start_reply(c, CGI_ERROR, "CGI error");
1481 mark_nonblock(c->pfd);
1483 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1485 if (c->cgibev == NULL) {
1486 start_reply(c, TEMP_FAILURE, "internal server error");
1490 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1495 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1500 id = imsg->hdr.peerid;
1501 if ((c = client_by_id(id)) == NULL) {
1507 if ((c->pfd = imsg->fd) == -1) {
1508 start_reply(c, PROXY_ERROR, "proxy error");
1512 mark_nonblock(c->pfd);
1514 if (proxy_init(c) == -1)
1515 start_reply(c, PROXY_ERROR, "proxy error");
1519 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1522 * don't call event_loopbreak since we want to finish to
1523 * handle the ongoing connections.
1532 signal_del(&siginfo);
1534 signal_del(&sigusr2);
1538 handle_dispatch_imsg(int fd, short ev, void *d)
1540 struct imsgbuf *ibuf = d;
1541 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1545 handle_siginfo(int fd, short ev, void *d)
1547 log_info(NULL, "%d connected clients", connected_clients);
1551 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1555 SPLAY_INIT(&clients);
1559 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1560 event_add(&e4, NULL);
1564 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1565 event_add(&e6, NULL);
1568 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1569 event_add(&imsgev, NULL);
1573 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1574 signal_add(&siginfo, NULL);
1576 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1577 signal_add(&sigusr2, NULL);
1579 sandbox_server_process();
1585 client_tree_cmp(struct client *a, struct client *b)
1589 else if (a->id < b->id)
1595 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)