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_fastcgi(struct client*);
51 static int apply_require_ca(struct client*);
52 static size_t host_nth(struct vhost*);
53 static void start_cgi(const char*, const char*, 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 cgi_read(struct bufferevent *, void *);
67 static void cgi_write(struct bufferevent *, void *);
68 static void cgi_error(struct bufferevent *, short, void *);
70 static void do_accept(int, short, void*);
71 static struct client *client_by_id(int);
73 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
74 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
75 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
76 static void handle_dispatch_imsg(int, short, void *);
77 static void handle_siginfo(int, short, void*);
79 static imsg_handlerfn *handlers[] = {
80 [IMSG_QUIT] = handle_imsg_quit,
81 [IMSG_CGI_RES] = handle_imsg_cgi_res,
82 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
85 static uint32_t server_client_id;
87 struct client_tree_id clients;
90 matches(const char *pattern, const char *path)
94 return !fnmatch(pattern, path, 0);
98 vhost_lang(struct vhost *v, const char *path)
100 struct location *loc;
102 if (v == NULL || path == NULL)
105 loc = TAILQ_FIRST(&v->locations);
106 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
107 if (loc->lang != NULL) {
108 if (matches(loc->match, path))
113 return TAILQ_FIRST(&v->locations)->lang;
117 vhost_default_mime(struct vhost *v, const char *path)
119 struct location *loc;
120 const char *default_mime = "application/octet-stream";
122 if (v == NULL || path == NULL)
125 loc = TAILQ_FIRST(&v->locations);
126 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
127 if (loc->default_mime != NULL) {
128 if (matches(loc->match, path))
129 return loc->default_mime;
133 loc = TAILQ_FIRST(&v->locations);
134 if (loc->default_mime != NULL)
135 return loc->default_mime;
140 vhost_index(struct vhost *v, const char *path)
142 struct location *loc;
143 const char *index = "index.gmi";
145 if (v == NULL || path == NULL)
148 loc = TAILQ_FIRST(&v->locations);
149 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
150 if (loc->index != NULL) {
151 if (matches(loc->match, path))
156 loc = TAILQ_FIRST(&v->locations);
157 if (loc->index != NULL)
163 vhost_auto_index(struct vhost *v, const char *path)
165 struct location *loc;
167 if (v == NULL || path == NULL)
170 loc = TAILQ_FIRST(&v->locations);
171 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
172 if (loc->auto_index != 0) {
173 if (matches(loc->match, path))
174 return loc->auto_index == 1;
178 loc = TAILQ_FIRST(&v->locations);
179 return loc->auto_index == 1;
183 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
185 struct location *loc;
187 if (v == NULL || path == NULL)
190 loc = TAILQ_FIRST(&v->locations);
191 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
192 if (loc->block_code != 0) {
193 if (matches(loc->match, path)) {
194 *code = loc->block_code;
195 *fmt = loc->block_fmt;
201 loc = TAILQ_FIRST(&v->locations);
202 *code = loc->block_code;
203 *fmt = loc->block_fmt;
204 return loc->block_code != 0;
208 vhost_fastcgi(struct vhost *v, const char *path)
210 struct location *loc;
212 if (v == NULL || path == NULL)
215 loc = TAILQ_FIRST(&v->locations);
216 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
218 if (matches(loc->match, path))
222 loc = TAILQ_FIRST(&v->locations);
227 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
229 struct location *loc;
232 if (v == NULL || path == NULL)
235 loc = TAILQ_FIRST(&v->locations);
236 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
238 if (loc->dirfd != -1)
239 if (matches(loc->match, path)) {
246 loc = TAILQ_FIRST(&v->locations);
251 vhost_strip(struct vhost *v, const char *path)
253 struct location *loc;
255 if (v == NULL || path == NULL)
258 loc = TAILQ_FIRST(&v->locations);
259 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
260 if (loc->strip != 0) {
261 if (matches(loc->match, path))
266 loc = TAILQ_FIRST(&v->locations);
271 vhost_require_ca(struct vhost *v, const char *path)
273 struct location *loc;
275 if (v == NULL || path == NULL)
278 loc = TAILQ_FIRST(&v->locations);
279 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
280 if (loc->reqca != NULL) {
281 if (matches(loc->match, path))
286 loc = TAILQ_FIRST(&v->locations);
291 vhost_disable_log(struct vhost *v, const char *path)
293 struct location *loc;
295 if (v == NULL || path == NULL)
298 loc = TAILQ_FIRST(&v->locations);
299 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
300 if (loc->disable_log && matches(loc->match, path))
304 loc = TAILQ_FIRST(&v->locations);
305 return loc->disable_log;
309 check_path(struct client *c, const char *path, int *fd)
315 assert(path != NULL);
318 * in send_dir we add an initial / (to be redirect-friendly),
319 * but here we want to skip it
324 strip = vhost_strip(c->host, path);
325 p = strip_path(path, strip);
332 dirfd = vhost_dirfd(c->host, path, &c->loc);
333 log_debug(c, "check_path: strip=%d path=%s original=%s",
335 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
338 if (fstat(*fd, &sb) == -1) {
339 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
343 if (S_ISDIR(sb.st_mode))
344 return FILE_DIRECTORY;
346 if (sb.st_mode & S_IXUSR)
347 return FILE_EXECUTABLE;
353 open_file(struct client *c)
355 switch (check_path(c, c->iri.path, &c->pfd)) {
356 case FILE_EXECUTABLE:
357 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
358 start_cgi(c->iri.path, "", c);
365 c->type = REQUEST_FILE;
366 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
374 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
378 start_reply(c, NOT_FOUND, "not found");
388 * the inverse of this algorithm, i.e. starting from the start of the
389 * path + strlen(cgi), and checking if each component, should be
390 * faster. But it's tedious to write. This does the opposite: starts
391 * from the end and strip one component at a time, until either an
392 * executable is found or we emptied the path.
395 check_for_cgi(struct client *c)
400 strlcpy(path, c->iri.path, sizeof(path));
401 end = strchr(path, '\0');
405 * go up one level. UNIX paths are simple and POSIX
406 * dirname, with its ambiguities on if the given
407 * pointer is changed or not, gives me headaches.
409 while (*end != '/' && end > path)
417 switch (check_path(c, path, &c->pfd)) {
418 case FILE_EXECUTABLE:
419 start_cgi(path, end+1, c);
432 start_reply(c, NOT_FOUND, "not found");
437 mark_nonblock(int fd)
441 if ((flags = fcntl(fd, F_GETFL)) == -1)
442 fatal("fcntl(F_GETFL): %s", strerror(errno));
443 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
444 fatal("fcntl(F_SETFL): %s", strerror(errno));
448 handle_handshake(int fd, short ev, void *d)
450 struct client *c = d;
453 const char *servname;
454 const char *parse_err = "unknown error";
456 switch (tls_handshake(c->ctx)) {
457 case 0: /* success */
458 case -1: /* already handshaked */
460 case TLS_WANT_POLLIN:
461 event_once(c->fd, EV_READ, handle_handshake, c, NULL);
463 case TLS_WANT_POLLOUT:
464 event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
471 c->bev = bufferevent_new(fd, client_read, client_write,
474 fatal("%s: failed to allocate client buffer: %s",
475 __func__, strerror(errno));
477 event_set(&c->bev->ev_read, c->fd, EV_READ,
478 client_tls_readcb, c->bev);
479 event_set(&c->bev->ev_write, c->fd, EV_WRITE,
480 client_tls_writecb, c->bev);
483 evbuffer_unfreeze(c->bev->input, 0);
484 evbuffer_unfreeze(c->bev->output, 1);
487 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
488 log_debug(c, "handshake: missing SNI");
492 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
493 log_info(c, "puny_decode: %s", parse_err);
497 TAILQ_FOREACH(h, &hosts, vhosts) {
498 if (matches(h->domain, c->domain))
500 TAILQ_FOREACH(a, &h->aliases, aliases) {
501 if (matches(a->alias, c->domain))
507 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
508 servname != NULL ? servname : "(null)",
510 h != NULL ? h->domain : "(null)");
514 bufferevent_enable(c->bev, EV_READ);
519 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
523 strip_path(const char *path, int strip)
528 if ((t = strchr(path, '/')) == NULL) {
529 path = strchr(path, '\0');
540 fmt_sbuf(const char *fmt, struct client *c, const char *path)
545 memset(buf, 0, sizeof(buf));
546 for (i = 0; *fmt; ++fmt) {
547 if (i == sizeof(buf)-1 || *fmt == '%') {
548 strlcat(c->sbuf, buf, sizeof(c->sbuf));
549 memset(buf, 0, sizeof(buf));
560 strlcat(c->sbuf, "%", sizeof(c->sbuf));
564 strlcat(c->sbuf, "/", sizeof(c->sbuf));
565 strlcat(c->sbuf, path, sizeof(c->sbuf));
568 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
571 snprintf(buf, sizeof(buf), "%d", conf.port);
572 strlcat(c->sbuf, buf, sizeof(c->sbuf));
573 memset(buf, 0, sizeof(buf));
576 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
579 fatal("%s: unknown fmt specifier %c",
585 strlcat(c->sbuf, buf, sizeof(c->sbuf));
588 /* 1 if a matching `block return' (and apply it), 0 otherwise */
590 apply_block_return(struct client *c)
592 const char *fmt, *path;
595 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
598 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
599 fmt_sbuf(fmt, c, path);
601 start_reply(c, code, c->sbuf);
605 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
607 apply_fastcgi(struct client *c)
612 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
617 log_debug(c, "opening fastcgi connection for (%s,%s,%s)",
618 f->path, f->port, f->prog);
620 imsg_compose(&exibuf, IMSG_FCGI_REQ, c->id, 0, -1,
626 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
628 apply_require_ca(struct client *c)
634 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
637 if (!tls_peer_cert_provided(c->ctx)) {
638 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
642 cert = tls_peer_cert_chain_pem(c->ctx, &len);
643 if (!validate_against_ca(store, cert, len)) {
644 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
652 host_nth(struct vhost *h)
657 TAILQ_FOREACH(v, &hosts, vhosts) {
667 start_cgi(const char *spath, const char *relpath, struct client *c)
669 char addr[NI_MAXHOST];
674 c->type = REQUEST_CGI;
676 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
681 fatal("getnameinfo failed");
683 memset(&req, 0, sizeof(req));
685 memcpy(req.buf, c->req, sizeof(req.buf));
687 req.iri_schema_off = c->iri.schema - c->req;
688 req.iri_host_off = c->iri.host - c->req;
689 req.iri_port_off = c->iri.port - c->req;
690 req.iri_path_off = c->iri.path - c->req;
691 req.iri_query_off = c->iri.query - c->req;
692 req.iri_fragment_off = c->iri.fragment - c->req;
694 req.iri_portno = c->iri.port_no;
696 strlcpy(req.spath, spath, sizeof(req.spath));
697 strlcpy(req.relpath, relpath, sizeof(req.relpath));
698 strlcpy(req.addr, addr, sizeof(req.addr));
700 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
701 strlcpy(req.subject, t, sizeof(req.subject));
702 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
703 strlcpy(req.issuer, t, sizeof(req.issuer));
704 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
705 strlcpy(req.hash, t, sizeof(req.hash));
706 if ((t = tls_conn_version(c->ctx)) != NULL)
707 strlcpy(req.version, t, sizeof(req.version));
708 if ((t = tls_conn_cipher(c->ctx)) != NULL)
709 strlcpy(req.cipher, t, sizeof(req.cipher));
711 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
712 req.notbefore = tls_peer_cert_notbefore(c->ctx);
713 req.notafter = tls_peer_cert_notafter(c->ctx);
715 req.host_off = host_nth(c->host);
716 req.loc_off = c->loc;
718 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
725 open_dir(struct client *c)
731 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
733 len = strlen(c->iri.path);
734 if (len > 0 && !ends_with(c->iri.path, "/")) {
735 redirect_canonical_dir(c);
739 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
740 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
741 if (!ends_with(c->sbuf, "/"))
742 strlcat(c->sbuf, "/", sizeof(c->sbuf));
743 before_file = strchr(c->sbuf, '\0');
744 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
746 if (len >= sizeof(c->sbuf)) {
747 start_reply(c, TEMP_FAILURE, "internal server error");
751 c->iri.path = c->sbuf;
753 /* close later unless we have to generate the dir listing */
757 switch (check_path(c, c->iri.path, &c->pfd)) {
758 case FILE_EXECUTABLE:
759 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
760 start_cgi(c->iri.path, "", c);
767 c->type = REQUEST_FILE;
768 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
772 start_reply(c, TEMP_REDIRECT, c->sbuf);
778 if (!vhost_auto_index(c->host, c->iri.path)) {
779 start_reply(c, NOT_FOUND, "not found");
783 c->type = REQUEST_DIR;
785 c->dirlen = scandir_fd(dirfd, &c->dir,
786 root ? select_non_dotdot : select_non_dot,
788 if (c->dirlen == -1) {
789 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
790 c->pfd, c->host->domain, c->iri.path, strerror(errno));
791 start_reply(c, TEMP_FAILURE, "internal server error");
797 start_reply(c, SUCCESS, "text/gemini");
798 evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
799 "# Index of %s\n\n", c->iri.path);
811 redirect_canonical_dir(struct client *c)
815 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
816 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
817 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
819 if (len >= sizeof(c->sbuf)) {
820 start_reply(c, TEMP_FAILURE, "internal server error");
824 start_reply(c, TEMP_REDIRECT, c->sbuf);
828 client_tls_readcb(int fd, short event, void *d)
830 struct bufferevent *bufev = d;
831 struct client *client = bufev->cbarg;
834 int what = EVBUFFER_READ;
835 int howmuch = IBUF_READ_SIZE;
836 char buf[IBUF_READ_SIZE];
838 if (event == EV_TIMEOUT) {
839 what |= EVBUFFER_TIMEOUT;
843 if (bufev->wm_read.high != 0)
844 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
846 switch (ret = tls_read(client->ctx, buf, howmuch)) {
847 case TLS_WANT_POLLIN:
848 case TLS_WANT_POLLOUT:
851 what |= EVBUFFER_ERROR;
857 what |= EVBUFFER_EOF;
861 if (evbuffer_add(bufev->input, buf, len) == -1) {
862 what |= EVBUFFER_ERROR;
866 event_add(&bufev->ev_read, NULL);
867 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
869 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
871 * here we could implement a read pressure policy.
875 if (bufev->readcb != NULL)
876 (*bufev->readcb)(bufev, bufev->cbarg);
881 event_add(&bufev->ev_read, NULL);
885 (*bufev->errorcb)(bufev, what, bufev->cbarg);
889 client_tls_writecb(int fd, short event, void *d)
891 struct bufferevent *bufev = d;
892 struct client *client = bufev->cbarg;
895 short what = EVBUFFER_WRITE;
897 if (event == EV_TIMEOUT) {
898 what |= EVBUFFER_TIMEOUT;
902 if (EVBUFFER_LENGTH(bufev->output) != 0) {
903 ret = tls_write(client->ctx,
904 EVBUFFER_DATA(bufev->output),
905 EVBUFFER_LENGTH(bufev->output));
907 case TLS_WANT_POLLIN:
908 case TLS_WANT_POLLOUT:
911 what |= EVBUFFER_ERROR;
915 evbuffer_drain(bufev->output, len);
918 if (EVBUFFER_LENGTH(bufev->output) != 0)
919 event_add(&bufev->ev_write, NULL);
921 if (bufev->writecb != NULL &&
922 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
923 (*bufev->writecb)(bufev, bufev->cbarg);
927 event_add(&bufev->ev_write, NULL);
930 log_err(client, "tls error: %s", tls_error(client->ctx));
931 (*bufev->errorcb)(bufev, what, bufev->cbarg);
935 client_read(struct bufferevent *bev, void *d)
937 struct client *c = d;
938 struct evbuffer *src = EVBUFFER_INPUT(bev);
939 const char *parse_err = "invalid request";
940 char decoded[DOMAIN_NAME_LEN];
943 bufferevent_disable(bev, EVBUFFER_READ);
945 /* max url len + \r\n */
946 if (EVBUFFER_LENGTH(src) > 1024 + 2) {
947 log_err(c, "too much data received");
948 start_reply(c, BAD_REQUEST, "bad request");
952 c->req = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
953 if (c->req == NULL) {
954 /* not enough data yet. */
955 bufferevent_enable(bev, EVBUFFER_READ);
959 if (!parse_iri(c->req, &c->iri, &parse_err) ||
960 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
961 log_err(c, "IRI parse error: %s", parse_err);
962 start_reply(c, BAD_REQUEST, "bad request");
966 /* ignore the port number */
967 if (strcmp(c->iri.schema, "gemini") ||
968 strcmp(decoded, c->domain)) {
969 start_reply(c, PROXY_REFUSED, "won't proxy request");
973 if (apply_require_ca(c) ||
974 apply_block_return(c)||
978 if (c->host->entrypoint != NULL) {
980 start_cgi(c->host->entrypoint, c->iri.path, c);
988 client_write(struct bufferevent *bev, void *d)
990 struct client *c = d;
991 struct evbuffer *out = EVBUFFER_OUTPUT(bev);
996 case REQUEST_UNDECIDED:
998 * Ignore spurious calls when we still don't have idea
999 * what to do with the request.
1004 if ((r = read(c->pfd, buf, sizeof(buf))) == -1) {
1005 log_warn(c, "read: %s", strerror(errno));
1006 client_error(bev, EVBUFFER_ERROR, c);
1008 } else if (r == 0) {
1011 } else if (r != sizeof(buf))
1012 c->type = REQUEST_DONE;
1013 bufferevent_write(bev, buf, r);
1017 /* TODO: handle big big directories better */
1018 for (c->diroff = 0; c->diroff < c->dirlen; ++c->diroff) {
1019 evbuffer_add_printf(out, "=> %s\n",
1020 c->dir[c->diroff]->d_name);
1021 free(c->dir[c->diroff]);
1026 c->type = REQUEST_DONE;
1028 event_add(&c->bev->ev_write, NULL);
1034 * Here we depend on on the cgi script or fastcgi
1035 * connection to provide data.
1040 if (EVBUFFER_LENGTH(out) == 0)
1047 client_error(struct bufferevent *bev, short error, void *d)
1049 struct client *c = d;
1051 c->type = REQUEST_DONE;
1053 if (error & EVBUFFER_TIMEOUT) {
1054 log_warn(c, "timeout reached, "
1055 "forcefully closing the connection");
1057 start_reply(c, BAD_REQUEST, "timeout");
1063 if (error & EVBUFFER_EOF) {
1068 log_err(c, "unknown bufferevent error: %s", strerror(errno));
1073 start_reply(struct client *c, int code, const char *meta)
1075 struct evbuffer *evb = EVBUFFER_OUTPUT(c->bev);
1079 bufferevent_enable(c->bev, EVBUFFER_WRITE);
1084 r = evbuffer_add_printf(evb, "%d %s", code, meta);
1088 /* 2 digit status + space + 1024 max reply */
1092 if (c->type != REQUEST_CGI &&
1093 c->type != REQUEST_FCGI &&
1094 !strcmp(meta, "text/gemini") &&
1095 (lang = vhost_lang(c->host, c->iri.path)) != NULL) {
1096 rr = evbuffer_add_printf(evb, ";lang=%s", lang);
1103 bufferevent_write(c->bev, "\r\n", 2);
1105 if (!vhost_disable_log(c->host, c->iri.path))
1106 log_request(c, EVBUFFER_DATA(evb), EVBUFFER_LENGTH(evb));
1108 if (code != 20 && IS_INTERNAL_REQUEST(c->type))
1109 c->type = REQUEST_DONE;
1114 log_err(c, "evbuffer_add_printf error: no memory");
1115 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1120 log_warn(c, "reply header overflow");
1121 evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
1122 start_reply(c, TEMP_FAILURE, "internal error");
1126 client_close_ev(int fd, short event, void *d)
1128 struct client *c = d;
1130 switch (tls_close(c->ctx)) {
1131 case TLS_WANT_POLLIN:
1132 event_once(c->fd, EV_READ, client_close_ev, c, NULL);
1134 case TLS_WANT_POLLOUT:
1135 event_once(c->fd, EV_WRITE, client_close_ev, c, NULL);
1139 connected_clients--;
1159 client_close(struct client *c)
1162 * We may end up calling client_close in various situations
1163 * and for the most unexpected reasons. Therefore, we need to
1164 * ensure that everything is properly released once we reach
1168 SPLAY_REMOVE(client_tree_id, &clients, c);
1170 if (c->cgibev != NULL) {
1171 bufferevent_disable(c->cgibev, EVBUFFER_READ|EVBUFFER_WRITE);
1172 bufferevent_free(c->cgibev);
1178 bufferevent_disable(c->bev, EVBUFFER_READ|EVBUFFER_WRITE);
1179 bufferevent_free(c->bev);
1182 client_close_ev(c->fd, 0, c);
1186 cgi_read(struct bufferevent *bev, void *d)
1188 struct client *client = d;
1189 struct evbuffer *src = EVBUFFER_INPUT(bev);
1194 /* intercept the header */
1195 if (client->code == 0) {
1196 header = evbuffer_readln(src, &len, EVBUFFER_EOL_CRLF_STRICT);
1197 if (header == NULL) {
1198 /* max reply + \r\n */
1199 if (EVBUFFER_LENGTH(src) > 1026) {
1200 log_warn(client, "CGI script is trying to "
1201 "send a header too long.");
1202 cgi_error(bev, EVBUFFER_READ, client);
1209 if (len < 3 || len > 1029 ||
1210 !isdigit(header[0]) ||
1211 !isdigit(header[1]) ||
1212 !isspace(header[2])) {
1214 log_warn(client, "CGI script is trying to send a "
1215 "malformed header");
1216 cgi_error(bev, EVBUFFER_READ, client);
1220 client->header = header;
1221 code = (header[0] - '0') * 10 + (header[1] - '0');
1223 if (code < 10 || code >= 70) {
1224 log_warn(client, "CGI script is trying to send an "
1225 "invalid reply code (%d)", code);
1226 cgi_error(bev, EVBUFFER_READ, client);
1230 start_reply(client, code, header + 3);
1232 if (client->code < 20 || client->code > 29) {
1233 cgi_error(client->cgibev, EVBUFFER_EOF, client);
1238 bufferevent_write_buffer(client->bev, src);
1242 cgi_write(struct bufferevent *bev, void *d)
1245 * Never called. We don't send data to a CGI script.
1251 cgi_error(struct bufferevent *bev, short error, void *d)
1253 struct client *client = d;
1255 if (error & EVBUFFER_ERROR)
1256 log_err(client, "%s: evbuffer error (%x): %s",
1257 __func__, error, strerror(errno));
1259 bufferevent_disable(bev, EVBUFFER_READ|EVBUFFER_WRITE);
1260 bufferevent_free(bev);
1261 client->cgibev = NULL;
1266 client->type = REQUEST_DONE;
1267 if (client->code != 0)
1268 client_write(client->bev, client);
1270 start_reply(client, CGI_ERROR, "CGI error");
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++;
1311 static struct client *
1312 client_by_id(int id)
1316 if ((c = try_client_by_id(id)) == NULL)
1317 fatal("in client_by_id: invalid id %d", id);
1322 try_client_by_id(int id)
1327 return SPLAY_FIND(client_tree_id, &clients, &find);
1331 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1335 c = client_by_id(imsg->hdr.peerid);
1337 if ((c->pfd = imsg->fd) == -1) {
1338 start_reply(c, TEMP_FAILURE, "internal server error");
1342 c->type = REQUEST_CGI;
1344 c->cgibev = bufferevent_new(c->pfd, cgi_read, cgi_write,
1347 bufferevent_enable(c->cgibev, EV_READ);
1351 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1356 id = imsg->hdr.peerid;
1358 if ((c = try_client_by_id(id)) == NULL) {
1364 if ((c->pfd = imsg->fd) == -1) {
1365 start_reply(c, CGI_ERROR, "CGI error");
1369 mark_nonblock(c->pfd);
1371 c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
1373 if (c->cgibev == NULL) {
1374 start_reply(c, TEMP_FAILURE, "internal server error");
1378 bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
1383 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1386 * don't call event_loopbreak since we want to finish to
1387 * handle the ongoing connections.
1396 signal_del(&siginfo);
1398 signal_del(&sigusr2);
1402 handle_dispatch_imsg(int fd, short ev, void *d)
1404 struct imsgbuf *ibuf = d;
1405 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1409 handle_siginfo(int fd, short ev, void *d)
1411 log_info(NULL, "%d connected clients", connected_clients);
1415 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1419 SPLAY_INIT(&clients);
1423 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1424 event_add(&e4, NULL);
1428 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1429 event_add(&e6, NULL);
1432 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1433 event_add(&imsgev, NULL);
1437 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1438 signal_add(&siginfo, NULL);
1440 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1441 signal_add(&sigusr2, NULL);
1443 sandbox_server_process();
1449 client_tree_cmp(struct client *a, struct client *b)
1453 else if (a->id < b->id)
1459 SPLAY_GENERATE(client_tree_id, client, entry, client_tree_cmp)