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 apply_reverse_proxy(struct client *);
51 static int apply_fastcgi(struct client*);
52 static int apply_require_ca(struct client*);
53 static size_t host_nth(struct vhost*);
54 static void start_cgi(const char*, const char*, struct client*);
55 static void open_dir(struct client*);
56 static void redirect_canonical_dir(struct client*);
58 static void client_tls_readcb(int, short, void *);
59 static void client_tls_writecb(int, short, void *);
61 static void client_read(struct bufferevent *, void *);
62 void client_write(struct bufferevent *, void *);
63 static void client_error(struct bufferevent *, short, void *);
65 static void client_close_ev(int, short, void *);
67 static void cgi_read(struct bufferevent *, void *);
68 static void cgi_write(struct bufferevent *, void *);
69 static void cgi_error(struct bufferevent *, short, void *);
71 static void do_accept(int, short, void*);
72 static struct client *client_by_id(int);
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_reverse_proxy(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) {
220 if (loc->proxy_host != NULL)
221 if (matches(loc->match, path))
225 loc = TAILQ_FIRST(&v->locations);
226 if (loc->proxy_host != NULL)
232 vhost_fastcgi(struct vhost *v, const char *path)
234 struct location *loc;
236 if (v == NULL || path == NULL)
239 loc = TAILQ_FIRST(&v->locations);
240 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
242 if (matches(loc->match, path))
246 loc = TAILQ_FIRST(&v->locations);
251 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
253 struct location *loc;
256 if (v == NULL || path == NULL)
259 loc = TAILQ_FIRST(&v->locations);
260 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
262 if (loc->dirfd != -1)
263 if (matches(loc->match, path)) {
270 loc = TAILQ_FIRST(&v->locations);
275 vhost_strip(struct vhost *v, const char *path)
277 struct location *loc;
279 if (v == NULL || path == NULL)
282 loc = TAILQ_FIRST(&v->locations);
283 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
284 if (loc->strip != 0) {
285 if (matches(loc->match, path))
290 loc = TAILQ_FIRST(&v->locations);
295 vhost_require_ca(struct vhost *v, const char *path)
297 struct location *loc;
299 if (v == NULL || path == NULL)
302 loc = TAILQ_FIRST(&v->locations);
303 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
304 if (loc->reqca != NULL) {
305 if (matches(loc->match, path))
310 loc = TAILQ_FIRST(&v->locations);
315 vhost_disable_log(struct vhost *v, const char *path)
317 struct location *loc;
319 if (v == NULL || path == NULL)
322 loc = TAILQ_FIRST(&v->locations);
323 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
324 if (loc->disable_log && matches(loc->match, path))
328 loc = TAILQ_FIRST(&v->locations);
329 return loc->disable_log;
333 check_path(struct client *c, const char *path, int *fd)
339 assert(path != NULL);
342 * in send_dir we add an initial / (to be redirect-friendly),
343 * but here we want to skip it
348 strip = vhost_strip(c->host, path);
349 p = strip_path(path, strip);
356 dirfd = vhost_dirfd(c->host, path, &c->loc);
357 log_debug(c, "check_path: strip=%d path=%s original=%s",
359 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
362 if (fstat(*fd, &sb) == -1) {
363 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
367 if (S_ISDIR(sb.st_mode))
368 return FILE_DIRECTORY;
370 if (sb.st_mode & S_IXUSR)
371 return FILE_EXECUTABLE;
377 open_file(struct client *c)
379 switch (check_path(c, c->iri.path, &c->pfd)) {
380 case FILE_EXECUTABLE:
381 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
382 start_cgi(c->iri.path, "", c);
389 c->type = REQUEST_FILE;
390 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
398 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
402 start_reply(c, NOT_FOUND, "not found");
412 * the inverse of this algorithm, i.e. starting from the start of the
413 * path + strlen(cgi), and checking if each component, should be
414 * faster. But it's tedious to write. This does the opposite: starts
415 * from the end and strip one component at a time, until either an
416 * executable is found or we emptied the path.
419 check_for_cgi(struct client *c)
424 strlcpy(path, c->iri.path, sizeof(path));
425 end = strchr(path, '\0');
429 * go up one level. UNIX paths are simple and POSIX
430 * dirname, with its ambiguities on if the given
431 * pointer is changed or not, gives me headaches.
433 while (*end != '/' && end > path)
441 switch (check_path(c, path, &c->pfd)) {
442 case FILE_EXECUTABLE:
443 start_cgi(path, end+1, c);
456 start_reply(c, NOT_FOUND, "not found");
461 mark_nonblock(int fd)
465 if ((flags = fcntl(fd, F_GETFL)) == -1)
466 fatal("fcntl(F_GETFL): %s", strerror(errno));
467 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
468 fatal("fcntl(F_SETFL): %s", strerror(errno));
472 handle_handshake(int fd, short ev, void *d)
474 struct client *c = d;
477 const char *servname;
478 const char *parse_err = "unknown error";
480 switch (tls_handshake(c->ctx)) {
481 case 0: /* success */
482 case -1: /* already handshaked */
484 case TLS_WANT_POLLIN:
485 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
487 case TLS_WANT_POLLOUT:
488 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
495 c->bev = bufferevent_new(fd, client_read, client_write,
498 fatal("%s: failed to allocate client buffer: %s",
499 __func__, strerror(errno));
501 event_set(&c->bev->ev_read, c->fd, EV_READ,
502 client_tls_readcb, c->bev);
503 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
504 client_tls_writecb, c->bev);
507 evbuffer_unfreeze(c->bev->input, 0);
508 evbuffer_unfreeze(c->bev->output, 1);
511 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
512 log_debug(c, "handshake: missing SNI");
516 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
517 log_info(c, "puny_decode: %s", parse_err);
521 TAILQ_FOREACH(h, &hosts, vhosts) {
522 if (matches(h->domain, c->domain))
524 TAILQ_FOREACH(a, &h->aliases, aliases) {
525 if (matches(a->alias, c->domain))
531 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
532 servname != NULL ? servname : "(null)",
534 h != NULL ? h->domain : "(null)");
538 bufferevent_enable(c->bev, EV_READ);
543 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
547 strip_path(const char *path, int strip)
552 if ((t = strchr(path, '/')) == NULL) {
553 path = strchr(path, '\0');
564 fmt_sbuf(const char *fmt, struct client *c, const char *path)
569 memset(buf, 0, sizeof(buf));
570 for (i = 0; *fmt; ++fmt) {
571 if (i == sizeof(buf)-1 || *fmt == '%') {
572 strlcat(c->sbuf, buf, sizeof(c->sbuf));
573 memset(buf, 0, sizeof(buf));
584 strlcat(c->sbuf, "%", sizeof(c->sbuf));
588 strlcat(c->sbuf, "/", sizeof(c->sbuf));
589 strlcat(c->sbuf, path, sizeof(c->sbuf));
592 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
595 snprintf(buf, sizeof(buf), "%d", conf.port);
596 strlcat(c->sbuf, buf, sizeof(c->sbuf));
597 memset(buf, 0, sizeof(buf));
600 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
603 fatal("%s: unknown fmt specifier %c",
609 strlcat(c->sbuf, buf, sizeof(c->sbuf));
612 /* 1 if a matching `block return' (and apply it), 0 otherwise */
614 apply_block_return(struct client *c)
616 const char *fmt, *path;
619 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
622 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
623 fmt_sbuf(fmt, c, path);
625 start_reply(c, code, c->sbuf);
629 /* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
631 apply_reverse_proxy(struct client *c)
633 struct location *loc;
636 if ((loc = vhost_reverse_proxy(c->host, c->iri.path)) == NULL)
639 log_debug(c, "opening proxy connection for %s:%s",
640 loc->proxy_host, loc->proxy_port);
642 strlcpy(r.host, loc->proxy_host, sizeof(r.host));
643 strlcpy(r.port, loc->proxy_port, sizeof(r.port));
645 strlcpy(c->domain, loc->proxy_host, sizeof(c->domain));
647 imsg_compose(&exibuf, IMSG_CONN_REQ, c->id, 0, -1, &r, sizeof(r));
653 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
655 apply_fastcgi(struct client *c)
660 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
665 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
666 f->path, f->port, f->prog);
668 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
674 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
676 apply_require_ca(struct client *c)
682 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
685 if (!tls_peer_cert_provided(c->ctx)) {
686 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
690 cert = tls_peer_cert_chain_pem(c->ctx, &len);
691 if (!validate_against_ca(store, cert, len)) {
692 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
700 host_nth(struct vhost *h)
705 TAILQ_FOREACH(v, &hosts, vhosts) {
715 start_cgi(const char *spath, const char *relpath, struct client *c)
717 char addr[NI_MAXHOST];
722 c->type = REQUEST_CGI;
724 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
729 fatal("getnameinfo failed");
731 memset(&req, 0, sizeof(req));
733 memcpy(req.buf, c->req, sizeof(req.buf));
735 req.iri_schema_off = c->iri.schema - c->req;
736 req.iri_host_off = c->iri.host - c->req;
737 req.iri_port_off = c->iri.port - c->req;
738 req.iri_path_off = c->iri.path - c->req;
739 req.iri_query_off = c->iri.query - c->req;
740 req.iri_fragment_off = c->iri.fragment - c->req;
742 req.iri_portno = c->iri.port_no;
744 strlcpy(req.spath, spath, sizeof(req.spath));
745 strlcpy(req.relpath, relpath, sizeof(req.relpath));
746 strlcpy(req.addr, addr, sizeof(req.addr));
748 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
749 strlcpy(req.subject, t, sizeof(req.subject));
750 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
751 strlcpy(req.issuer, t, sizeof(req.issuer));
752 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
753 strlcpy(req.hash, t, sizeof(req.hash));
754 if ((t = tls_conn_version(c->ctx)) != NULL)
755 strlcpy(req.version, t, sizeof(req.version));
756 if ((t = tls_conn_cipher(c->ctx)) != NULL)
757 strlcpy(req.cipher, t, sizeof(req.cipher));
759 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
760 req.notbefore = tls_peer_cert_notbefore(c->ctx);
761 req.notafter = tls_peer_cert_notafter(c->ctx);
763 req.host_off = host_nth(c->host);
764 req.loc_off = c->loc;
766 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
773 open_dir(struct client *c)
779 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
781 len = strlen(c->iri.path);
782 if (len > 0 && !ends_with(c->iri.path, "/")) {
783 redirect_canonical_dir(c);
787 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
788 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
789 if (!ends_with(c->sbuf, "/"))
790 strlcat(c->sbuf, "/", sizeof(c->sbuf));
791 before_file = strchr(c->sbuf, '\0');
792 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
794 if (len >= sizeof(c->sbuf)) {
795 start_reply(c, TEMP_FAILURE, "internal server error");
799 c->iri.path = c->sbuf;
801 /* close later unless we have to generate the dir listing */
805 switch (check_path(c, c->iri.path, &c->pfd)) {
806 case FILE_EXECUTABLE:
807 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
808 start_cgi(c->iri.path, "", c);
815 c->type = REQUEST_FILE;
816 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
820 start_reply(c, TEMP_REDIRECT, c->sbuf);
826 if (!vhost_auto_index(c->host, c->iri.path)) {
827 start_reply(c, NOT_FOUND, "not found");
831 c->type = REQUEST_DIR;
833 c->dirlen = scandir_fd(dirfd, &c->dir,
834 root ? select_non_dotdot : select_non_dot,
836 if (c->dirlen == -1) {
837 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
838 c->pfd, c->host->domain, c->iri.path, strerror(errno));
839 start_reply(c, TEMP_FAILURE, "internal server error");
845 start_reply(c, SUCCESS, "text/gemini");
846 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
847 "# Index of %s\n\n", c->iri.path);
859 redirect_canonical_dir(struct client *c)
863 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
864 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
865 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
867 if (len >= sizeof(c->sbuf)) {
868 start_reply(c, TEMP_FAILURE, "internal server error");
872 start_reply(c, TEMP_REDIRECT, c->sbuf);
876 client_tls_readcb(int fd, short event, void *d)
878 struct bufferevent *bufev = d;
879 struct client *client = bufev->cbarg;
882 int what = EVBUFFER_READ;
883 int howmuch = IBUF_READ_SIZE;
884 char buf[IBUF_READ_SIZE];
886 if (event == EV_TIMEOUT) {
887 what |= EVBUFFER_TIMEOUT;
891 if (bufev->wm_read.high != 0)
892 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
894 switch (ret = tls_read(client->ctx, buf, howmuch)) {
895 case TLS_WANT_POLLIN:
896 case TLS_WANT_POLLOUT:
899 what |= EVBUFFER_ERROR;
905 what |= EVBUFFER_EOF;
909 if (evbuffer_add(bufev->input, buf, len) == -1) {
910 what |= EVBUFFER_ERROR;
914 event_add(&bufev->ev_read, NULL);
915 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
917 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
919 * here we could implement a read pressure policy.
923 if (bufev->readcb != NULL)
924 (*bufev->readcb)(bufev, bufev->cbarg);
929 event_add(&bufev->ev_read, NULL);
933 (*bufev->errorcb)(bufev, what, bufev->cbarg);
937 client_tls_writecb(int fd, short event, void *d)
939 struct bufferevent *bufev = d;
940 struct client *client = bufev->cbarg;
943 short what = EVBUFFER_WRITE;
945 if (event == EV_TIMEOUT) {
946 what |= EVBUFFER_TIMEOUT;
950 if (EVBUFFER_LENGTH(bufev->output) != 0) {
951 ret = tls_write(client->ctx,
952 EVBUFFER_DATA(bufev->output),
953 EVBUFFER_LENGTH(bufev->output));
955 case TLS_WANT_POLLIN:
956 case TLS_WANT_POLLOUT:
959 what |= EVBUFFER_ERROR;
963 evbuffer_drain(bufev->output, len);
966 if (EVBUFFER_LENGTH(bufev->output) != 0)
967 event_add(&bufev->ev_write, NULL);
969 if (bufev->writecb != NULL &&
970 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
971 (*bufev->writecb)(bufev, bufev->cbarg);
975 event_add(&bufev->ev_write, NULL);
978 log_err(client, "tls error: %s", tls_error(client->ctx));
979 (*bufev->errorcb)(bufev, what, bufev->cbarg);
983 client_read(struct bufferevent *bev, void *d)
985 struct client *c = d;
986 struct evbuffer *src = EVBUFFER_INPUT(bev);
987 const char *parse_err = "invalid request";
988 char decoded[DOMAIN_NAME_LEN];
991 bufferevent_disable(bev, EVBUFFER_READ);
993 /* max url len + \r\n */
994 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
995 log_err(c, "too much data received");
996 start_reply(c, BAD_REQUEST, "bad request");
1000 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1001 if (c->req == NULL) {
1002 /* not enough data yet. */
1003 bufferevent_enable(bev, EVBUFFER_READ);
1007 if (!parse_iri(c->req, &c->iri, &parse_err) ||
1008 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
1009 log_err(c, "IRI parse error: %s", parse_err);
1010 start_reply(c, BAD_REQUEST, "bad request");
1014 if (apply_reverse_proxy(c))
1017 /* ignore the port number */
1018 if (strcmp(c->iri.schema, "gemini") ||
1019 strcmp(decoded, c->domain)) {
1020 start_reply(c, PROXY_REFUSED, "won't proxy request");
1024 if (apply_require_ca(c) ||
1025 apply_block_return(c)||
1029 if (c->host->entrypoint != NULL) {
1031 start_cgi(c->host->entrypoint, c->iri.path, c);
1039 client_write(struct bufferevent *bev, void *d)
1041 struct client *c = d;
1042 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
1047 case REQUEST_UNDECIDED:
1049 * Ignore spurious calls when we still don't have idea
1050 * what to do with the request.
1055 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1056 log_warn(c, "read: %s", strerror(errno));
1057 client_error(bev, EVBUFFER_ERROR, c);
1059 } else if (r == 0) {
1062 } else if (r != sizeof(buf))
1063 c->type = REQUEST_DONE;
1064 bufferevent_write(bev, buf, r);
1068 /* TODO: handle big big directories better */
1069 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1070 evbuffer_add_printf(out, "=> %s\n",
1071 c->dir[c->diroff]->d_name);
1072 free(c->dir[c->diroff]);
1077 c->type = REQUEST_DONE;
1079 event_add(&c->bev->ev_write, NULL);
1086 * Here we depend on on the cgi script or fastcgi
1087 * connection to provide data.
1092 if (EVBUFFER_LENGTH(out) == 0)
1099 client_error(struct bufferevent *bev, short error, void *d)
1101 struct client *c = d;
1103 c->type = REQUEST_DONE;
1105 if (error & EVBUFFER_TIMEOUT) {
1106 log_warn(c, "timeout reached, "
1107 "forcefully closing the connection");
1109 start_reply(c, BAD_REQUEST, "timeout");
1115 if (error & EVBUFFER_EOF) {
1120 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1125 start_reply(struct client *c, int code, const char *meta)
1127 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1131 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1136 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1140 /* 2 digit status + space + 1024 max reply */
1144 if (c->type != REQUEST_CGI &&
1145 c->type != REQUEST_FCGI &&
1146 c->type != REQUEST_PROXY &&
1147 !strcmp(meta, "text/gemini") &&
1148 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1149 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1156 bufferevent_write(c->bev, "\r\n", 2);
1158 if (!vhost_disable_log(c->host, c->iri.path))
1159 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1161 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1162 c->type = REQUEST_DONE;
1167 log_err(c, "evbuffer_add_printf error: no memory");
1168 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1173 log_warn(c, "reply header overflow");
1174 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1175 start_reply(c, TEMP_FAILURE, "internal error");
1179 client_close_ev(int fd, short event, void *d)
1181 struct client *c = d;
1183 switch (tls_close(c->ctx)) {
1184 case TLS_WANT_POLLIN:
1185 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1187 case TLS_WANT_POLLOUT:
1188 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1192 connected_clients--;
1212 client_proxy_close(int fd, short event, void *d)
1214 struct tls *ctx = d;
1221 switch (tls_close(ctx)) {
1222 case TLS_WANT_POLLIN:
1223 event_once(fd, EV_READ, client_proxy_close, d, NULL);
1225 case TLS_WANT_POLLOUT:
1226 event_once(fd, EV_WRITE, client_proxy_close, d, NULL);
1235 client_close(struct client *c)
1238 * We may end up calling client_close in various situations
1239 * and for the most unexpected reasons. Therefore, we need to
1240 * ensure that everything is properly released once we reach
1244 SPLAY_REMOVE(client_tree_id, &clients, c);
1246 if (c->cgibev != NULL) {
1247 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1248 bufferevent_free(c->cgibev);
1254 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1255 bufferevent_free(c->bev);
1258 if (c->proxybev != NULL) {
1259 if (event_pending(&c->proxyev, EV_READ|EV_WRITE, NULL))
1260 event_del(&c->proxyev);
1263 client_proxy_close(c->pfd, 0, c->proxyctx);
1267 bufferevent_free(c->proxybev);
1270 client_close_ev(c->fd, 0, c);
1274 cgi_read(struct bufferevent *bev, void *d)
1276 struct client *client = d;
1277 struct evbuffer *src = EVBUFFER_INPUT(bev);
1282 /* intercept the header */
1283 if (client->code == 0) {
1284 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1285 if (header == NULL) {
1286 /* max reply + \r\n */
1287 if (EVBUFFER_LENGTH(src) > 1026) {
1288 log_warn(client, "CGI script is trying to "
1289 "send a header too long.");
1290 cgi_error(bev, EVBUFFER_READ, client);
1297 if (len < 3 || len > 1029 ||
1298 !isdigit(header[0]) ||
1299 !isdigit(header[1]) ||
1300 !isspace(header[2])) {
1302 log_warn(client, "CGI script is trying to send a "
1303 "malformed header");
1304 cgi_error(bev, EVBUFFER_READ, client);
1308 client->header = header;
1309 code = (header[0] - '0') * 10 + (header[1] - '0');
1311 if (code < 10 || code >= 70) {
1312 log_warn(client, "CGI script is trying to send an "
1313 "invalid reply code (%d)", code);
1314 cgi_error(bev, EVBUFFER_READ, client);
1318 start_reply(client, code, header + 3);
1320 if (client->code < 20 || client->code > 29) {
1321 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1326 bufferevent_write_buffer(client->bev, src);
1330 cgi_write(struct bufferevent *bev, void *d)
1333 * Never called. We don't send data to a CGI script.
1339 cgi_error(struct bufferevent *bev, short error, void *d)
1341 struct client *client = d;
1343 if (error & EVBUFFER_ERROR)
1344 log_err(client, "%s: evbuffer error (%x): %s",
1345 __func__, error, strerror(errno));
1347 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1348 bufferevent_free(bev);
1349 client->cgibev = NULL;
1354 client->type = REQUEST_DONE;
1355 if (client->code != 0)
1356 client_write(client->bev, client);
1358 start_reply(client, CGI_ERROR, "CGI error");
1362 do_accept(int sock, short et, void *d)
1365 struct sockaddr_storage addr;
1366 struct sockaddr *saddr;
1370 saddr = (struct sockaddr*)&addr;
1372 if ((fd = accept(sock, saddr, &len)) == -1) {
1373 if (errno == EWOULDBLOCK || errno == EAGAIN ||
1374 errno == ECONNABORTED)
1376 fatal("accept: %s", strerror(errno));
1381 c = xcalloc(1, sizeof(*c));
1382 c->id = ++server_client_id;
1387 if (tls_accept_socket(ctx, &c->ctx, fd) == -1) {
1388 log_warn(c, "failed to accept socket: %s", tls_error(c->ctx));
1394 SPLAY_INSERT(client_tree_id, &clients, c);
1395 event_once(c->fd, EV_READ|EV_WRITE, handle_handshake, c, NULL);
1396 connected_clients++;
1399 static struct client *
1400 client_by_id(int id)
1404 if ((c = try_client_by_id(id)) == NULL)
1405 fatal("in client_by_id: invalid id %d", id);
1410 try_client_by_id(int id)
1415 return SPLAY_FIND(client_tree_id, &clients, &find);
1419 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1423 c = client_by_id(imsg->hdr.peerid);
1425 if ((c->pfd = imsg->fd) == -1) {
1426 start_reply(c, TEMP_FAILURE, "internal server error");
1430 c->type = REQUEST_CGI;
1432 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1435 bufferevent_enable(c->cgibev, EV_READ);
1439 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1444 id = imsg->hdr.peerid;
1446 if ((c = try_client_by_id(id)) == NULL) {
1452 if ((c->pfd = imsg->fd) == -1) {
1453 start_reply(c, CGI_ERROR, "CGI error");
1457 mark_nonblock(c->pfd);
1459 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1461 if (c->cgibev == NULL) {
1462 start_reply(c, TEMP_FAILURE, "internal server error");
1466 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1471 handle_imsg_conn_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1476 id = imsg->hdr.peerid;
1477 if ((c = try_client_by_id(id)) == NULL) {
1483 if ((c->pfd = imsg->fd) == -1) {
1484 start_reply(c, PROXY_ERROR, "proxy error");
1488 mark_nonblock(c->pfd);
1490 if (proxy_init(c) == -1)
1491 start_reply(c, PROXY_ERROR, "proxy error");
1495 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1498 * don't call event_loopbreak since we want to finish to
1499 * handle the ongoing connections.
1508 signal_del(&siginfo);
1510 signal_del(&sigusr2);
1514 handle_dispatch_imsg(int fd, short ev, void *d)
1516 struct imsgbuf *ibuf = d;
1517 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1521 handle_siginfo(int fd, short ev, void *d)
1523 log_info(NULL, "%d connected clients", connected_clients);
1527 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1531 SPLAY_INIT(&clients);
1535 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1536 event_add(&e4, NULL);
1540 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1541 event_add(&e6, NULL);
1544 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1545 event_add(&imsgev, NULL);
1549 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1550 signal_add(&siginfo, NULL);
1552 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1553 signal_add(&sigusr2, NULL);
1555 sandbox_server_process();
1561 client_tree_cmp(struct client *a, struct client *b)
1565 else if (a->id < b->id)
1571 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)