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.
33 struct client clients[MAX_USERS];
37 struct event e4, e6, sighup, siginfo, sigusr2;
38 int has_ipv6, has_siginfo;
40 int connected_clients;
42 static inline int matches(const char*, const char*);
44 static inline void reschedule_read(int, struct client*, statefn);
45 static inline void reschedule_write(int, struct client*, statefn);
47 static int check_path(struct client*, const char*, int*);
48 static void open_file(struct client*);
49 static void load_file(struct client*);
50 static void check_for_cgi(struct client*);
51 static void handle_handshake(int, short, void*);
52 static char *strip_path(char*, int);
53 static void fmt_sbuf(const char*, struct client*, const char*);
54 static int apply_block_return(struct client*);
55 static int apply_require_ca(struct client*);
56 static void handle_open_conn(int, short, void*);
57 static void start_reply(struct client*, int, const char*);
58 static void handle_start_reply(int, short, void*);
59 static void start_cgi(const char*, const char*, struct client*);
60 static void send_file(int, short, void*);
61 static void open_dir(struct client*);
62 static void redirect_canonical_dir(struct client*);
63 static void enter_handle_dirlist(int, short, void*);
64 static void handle_dirlist(int, short, void*);
65 static int read_next_dir_entry(struct client*);
66 static void send_directory_listing(int, short, void*);
67 static void handle_cgi_reply(int, short, void*);
68 static void handle_cgi(int, short, void*);
69 static void close_conn(int, short, void*);
70 static void do_accept(int, short, void*);
71 static void handle_sighup(int, short, void*);
74 matches(const char *pattern, const char *path)
78 return !fnmatch(pattern, path, 0);
82 reschedule_read(int fd, struct client *c, statefn fn)
84 event_once(fd, EV_READ, fn, c, NULL);
88 reschedule_write(int fd, struct client *c, statefn fn)
90 event_once(fd, EV_WRITE, fn, c, NULL);
94 vhost_lang(struct vhost *v, const char *path)
98 if (v == NULL || path == NULL)
101 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
102 if (loc->lang != NULL) {
103 if (matches(loc->match, path))
108 return v->locations[0].lang;
112 vhost_default_mime(struct vhost *v, const char *path)
114 struct location *loc;
115 const char *default_mime = "application/octet-stream";
117 if (v == NULL || path == NULL)
120 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
121 if (loc->default_mime != NULL) {
122 if (matches(loc->match, path))
123 return loc->default_mime;
127 if (v->locations[0].default_mime != NULL)
128 return v->locations[0].default_mime;
133 vhost_index(struct vhost *v, const char *path)
135 struct location *loc;
136 const char *index = "index.gmi";
138 if (v == NULL || path == NULL)
141 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
142 if (loc->index != NULL) {
143 if (matches(loc->match, path))
148 if (v->locations[0].index != NULL)
149 return v->locations[0].index;
154 vhost_auto_index(struct vhost *v, const char *path)
156 struct location *loc;
158 if (v == NULL || path == NULL)
161 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
162 if (loc->auto_index != 0) {
163 if (matches(loc->match, path))
164 return loc->auto_index == 1;
168 return v->locations[0].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 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
180 if (loc->block_code != 0) {
181 if (matches(loc->match, path)) {
182 *code = loc->block_code;
183 *fmt = loc->block_fmt;
189 *code = v->locations[0].block_code;
190 *fmt = v->locations[0].block_fmt;
191 return v->locations[0].block_code != 0;
195 vhost_strip(struct vhost *v, const char *path)
197 struct location *loc;
199 if (v == NULL || path == NULL)
202 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
203 if (loc->strip != 0) {
204 if (matches(loc->match, path))
209 return v->locations[0].strip;
213 vhost_require_ca(struct vhost *v, const char *path)
215 struct location *loc;
217 if (v == NULL || path == NULL)
220 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
221 if (loc->reqca != NULL) {
222 if (matches(loc->match, path))
227 return v->locations[0].reqca;
231 check_path(struct client *c, const char *path, int *fd)
237 assert(path != NULL);
241 else if (*path == '/')
242 /* in send_dir we add an initial / (to be
243 * redirect-friendly), but here we want to skip it */
248 flags = O_RDONLY | O_NOFOLLOW;
250 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
253 if (fstat(*fd, &sb) == -1) {
254 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
258 if (S_ISDIR(sb.st_mode))
259 return FILE_DIRECTORY;
261 if (sb.st_mode & S_IXUSR)
262 return FILE_EXECUTABLE;
268 open_file(struct client *c)
270 switch (check_path(c, c->iri.path, &c->pfd)) {
271 case FILE_EXECUTABLE:
272 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
273 start_cgi(c->iri.path, "", c);
288 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
292 start_reply(c, NOT_FOUND, "not found");
302 load_file(struct client *c)
304 if ((c->len = filesize(c->pfd)) == -1) {
305 log_err(c, "failed to get file size for %s: %s",
306 c->iri.path, strerror(errno));
307 start_reply(c, TEMP_FAILURE, "internal server error");
311 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
312 c->pfd, 0)) == MAP_FAILED) {
313 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
314 start_reply(c, TEMP_FAILURE, "internal server error");
319 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
323 * the inverse of this algorithm, i.e. starting from the start of the
324 * path + strlen(cgi), and checking if each component, should be
325 * faster. But it's tedious to write. This does the opposite: starts
326 * from the end and strip one component at a time, until either an
327 * executable is found or we emptied the path.
330 check_for_cgi(struct client *c)
335 strlcpy(path, c->iri.path, sizeof(path));
336 end = strchr(path, '\0');
339 /* go up one level. UNIX paths are simple and POSIX
340 * dirname, with its ambiguities on if the given path
341 * is changed or not, gives me headaches. */
346 switch (check_path(c, path, &c->pfd)) {
347 case FILE_EXECUTABLE:
348 start_cgi(path, end+1, c);
361 start_reply(c, NOT_FOUND, "not found");
366 mark_nonblock(int fd)
370 if ((flags = fcntl(fd, F_GETFL)) == -1)
371 fatal("fcntl(F_GETFL): %s", strerror(errno));
372 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
373 fatal("fcntl(F_SETFL): %s", strerror(errno));
377 handle_handshake(int fd, short ev, void *d)
379 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 reschedule_read(fd, c, &handle_handshake);
391 case TLS_WANT_POLLOUT:
392 reschedule_write(fd, c, &handle_handshake);
399 servname = tls_conn_servername(c->ctx);
400 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
401 log_info(c, "puny_decode: %s", parse_err);
405 for (h = hosts; h->domain != NULL; ++h) {
406 if (!fnmatch(h->domain, c->domain, 0))
410 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
411 servname != NULL ? servname : "(null)",
413 h->domain != NULL ? h->domain : "(null)");
415 if (h->domain != NULL) {
417 handle_open_conn(fd, ev, c);
422 if (servname != NULL)
423 strncpy(c->req, servname, sizeof(c->req));
425 strncpy(c->req, "null", sizeof(c->req));
427 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
431 strip_path(char *path, int strip)
436 if ((t = strchr(path, '/')) == NULL) {
437 path = strchr(path, '\0');
448 fmt_sbuf(const char *fmt, struct client *c, const char *path)
453 memset(buf, 0, sizeof(buf));
454 for (i = 0; *fmt; ++fmt) {
455 if (i == sizeof(buf)-1 || *fmt == '%') {
456 strlcat(c->sbuf, buf, sizeof(c->sbuf));
457 memset(buf, 0, sizeof(buf));
468 strlcat(c->sbuf, "%", sizeof(c->sbuf));
471 strlcat(c->sbuf, path, sizeof(c->sbuf));
474 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
477 snprintf(buf, sizeof(buf), "%d", conf.port);
478 strlcat(c->sbuf, buf, sizeof(c->sbuf));
479 memset(buf, 0, sizeof(buf));
482 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
485 fatal("%s: unknown fmt specifier %c",
491 strlcat(c->sbuf, buf, sizeof(c->sbuf));
494 /* 1 if a matching `block return' (and apply it), 0 otherwise */
496 apply_block_return(struct client *c)
498 const char *fmt, *path;
501 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
504 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
505 fmt_sbuf(fmt, c, path);
507 start_reply(c, code, c->sbuf);
511 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
513 apply_require_ca(struct client *c)
519 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
522 if (!tls_peer_cert_provided(c->ctx)) {
523 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
527 cert = tls_peer_cert_chain_pem(c->ctx, &len);
528 if (!validate_against_ca(store, cert, len)) {
529 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
537 handle_open_conn(int fd, short ev, void *d)
539 struct client *c = d;
540 const char *parse_err = "invalid request";
541 char decoded[DOMAIN_NAME_LEN];
543 bzero(c->req, sizeof(c->req));
544 bzero(&c->iri, sizeof(c->iri));
546 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
548 log_err(c, "tls_read: %s", tls_error(c->ctx));
549 close_conn(fd, ev, c);
552 case TLS_WANT_POLLIN:
553 reschedule_read(fd, c, &handle_open_conn);
556 case TLS_WANT_POLLOUT:
557 reschedule_write(fd, c, &handle_open_conn);
561 if (!trim_req_iri(c->req, &parse_err)
562 || !parse_iri(c->req, &c->iri, &parse_err)
563 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
564 log_info(c, "iri parse error: %s", parse_err);
565 start_reply(c, BAD_REQUEST, "invalid request");
569 if (c->iri.port_no != conf.port
570 || strcmp(c->iri.schema, "gemini")
571 || strcmp(decoded, c->domain)) {
572 start_reply(c, PROXY_REFUSED, "won't proxy request");
576 if (apply_require_ca(c))
579 if (apply_block_return(c))
582 if (c->host->entrypoint != NULL) {
583 start_cgi(c->host->entrypoint, c->iri.path, c);
591 start_reply(struct client *c, int code, const char *meta)
595 handle_start_reply(c->fd, 0, c);
599 handle_start_reply(int fd, short ev, void *d)
601 struct client *c = d;
602 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
606 lang = vhost_lang(c->host, c->iri.path);
608 snprintf(buf, sizeof(buf), "%d ", c->code);
609 strlcat(buf, c->meta, sizeof(buf));
610 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
611 strlcat(buf, "; lang=", sizeof(buf));
612 strlcat(buf, lang, sizeof(buf));
615 len = strlcat(buf, "\r\n", sizeof(buf));
616 assert(len < sizeof(buf));
618 switch (tls_write(c->ctx, buf, len)) {
620 close_conn(fd, ev, c);
622 case TLS_WANT_POLLIN:
623 reschedule_read(fd, c, &handle_start_reply);
625 case TLS_WANT_POLLOUT:
626 reschedule_write(fd, c, &handle_start_reply);
630 log_request(c, buf, sizeof(buf));
632 if (c->code != SUCCESS)
633 close_conn(fd, ev, c);
639 start_cgi(const char *spath, const char *relpath, struct client *c)
641 char addr[NI_MAXHOST];
644 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
651 if (!send_iri(exfd, &c->iri)
652 || !send_string(exfd, spath)
653 || !send_string(exfd, relpath)
654 || !send_string(exfd, addr)
655 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
656 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
657 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
658 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
659 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
660 || !send_vhost(exfd, c->host))
664 if ((c->pfd = recv_fd(exfd)) == -1) {
665 start_reply(c, TEMP_FAILURE, "internal server error");
669 reschedule_read(c->pfd, c, &handle_cgi_reply);
673 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
674 fatal("cannot talk to the executor process");
678 send_file(int fd, short ev, void *d)
680 struct client *c = d;
683 len = (c->buf + c->len) - c->i;
686 switch (ret = tls_write(c->ctx, c->i, len)) {
688 log_err(c, "tls_write: %s", tls_error(c->ctx));
689 close_conn(fd, ev, c);
692 case TLS_WANT_POLLIN:
693 reschedule_read(fd, c, &send_file);
696 case TLS_WANT_POLLOUT:
697 reschedule_write(fd, c, &send_file);
707 close_conn(fd, ev, c);
711 open_dir(struct client *c)
717 len = strlen(c->iri.path);
718 if (len > 0 && !ends_with(c->iri.path, "/")) {
719 redirect_canonical_dir(c);
723 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
724 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
725 if (!ends_with(c->sbuf, "/"))
726 strlcat(c->sbuf, "/", sizeof(c->sbuf));
727 before_file = strchr(c->sbuf, '\0');
728 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
730 if (len >= sizeof(c->sbuf)) {
731 start_reply(c, TEMP_FAILURE, "internal server error");
735 c->iri.path = c->sbuf;
737 /* close later unless we have to generate the dir listing */
741 switch (check_path(c, c->iri.path, &c->pfd)) {
742 case FILE_EXECUTABLE:
743 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
744 start_cgi(c->iri.path, "", c);
755 start_reply(c, TEMP_REDIRECT, c->sbuf);
761 if (!vhost_auto_index(c->host, c->iri.path)) {
762 start_reply(c, NOT_FOUND, "not found");
767 c->next = enter_handle_dirlist;
769 if ((c->dir = fdopendir(c->pfd)) == NULL) {
770 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
771 c->pfd, c->host->domain, c->iri.path, strerror(errno));
772 start_reply(c, TEMP_FAILURE, "internal server error");
777 start_reply(c, SUCCESS, "text/gemini");
789 redirect_canonical_dir(struct client *c)
793 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
794 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
795 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
797 if (len >= sizeof(c->sbuf)) {
798 start_reply(c, TEMP_FAILURE, "internal server error");
802 start_reply(c, TEMP_REDIRECT, c->sbuf);
806 enter_handle_dirlist(int fd, short ev, void *d)
808 struct client *c = d;
812 strlcpy(b, c->iri.path, sizeof(b));
813 l = snprintf(c->sbuf, sizeof(c->sbuf),
814 "# Index of %s\n\n", b);
815 if (l >= sizeof(c->sbuf)) {
816 /* this is impossible, given that we have enough space
817 * in c->sbuf to hold the ancilliary string plus the
818 * full path; but it wouldn't read nice without some
819 * error checking, and I'd like to avoid a strlen. */
820 close_conn(fd, ev, c);
825 handle_dirlist(fd, ev, c);
829 handle_dirlist(int fd, short ev, void *d)
831 struct client *c = d;
835 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
837 close_conn(fd, ev, c);
839 case TLS_WANT_POLLOUT:
840 reschedule_read(fd, c, &handle_dirlist);
842 case TLS_WANT_POLLIN:
843 reschedule_write(fd, c, &handle_dirlist);
851 send_directory_listing(fd, ev, c);
855 read_next_dir_entry(struct client *c)
861 if ((d = readdir(c->dir)) == NULL) {
863 log_err(c, "readdir: %s", strerror(errno));
866 } while (!strcmp(d->d_name, "."));
868 /* XXX: url escape */
869 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
870 d->d_name, d->d_name);
871 c->len = strlen(c->sbuf);
878 send_directory_listing(int fd, short ev, void *d)
880 struct client *c = d;
885 if (!read_next_dir_entry(c))
890 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
894 case TLS_WANT_POLLOUT:
895 reschedule_read(fd, c, &send_directory_listing);
898 case TLS_WANT_POLLIN:
899 reschedule_write(fd, c, &send_directory_listing);
911 close_conn(fd, ev, d);
914 /* accumulate the meta line from the cgi script. */
916 handle_cgi_reply(int fd, short ev, void *d)
918 struct client *c = d;
924 buf = c->sbuf + c->len;
925 len = sizeof(c->sbuf) - c->len;
927 r = read(c->pfd, buf, len);
928 if (r == 0 || r == -1) {
929 start_reply(c, CGI_ERROR, "CGI error");
935 /* TODO: error if the CGI script don't reply correctly */
936 e = strchr(c->sbuf, '\n');
937 if (e != NULL || c->len == sizeof(c->sbuf)) {
938 log_request(c, c->sbuf, c->len);
941 handle_cgi(fd, ev, c);
945 reschedule_read(fd, c, &handle_cgi_reply);
949 handle_cgi(int fd, short ev, void *d)
951 struct client *c = d;
956 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
960 if (errno == EAGAIN || errno == EWOULDBLOCK) {
961 reschedule_read(c->pfd, c, &handle_cgi);
972 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
976 case TLS_WANT_POLLOUT:
977 reschedule_read(c->fd, c, &handle_cgi);
980 case TLS_WANT_POLLIN:
981 reschedule_write(c->fd, c, &handle_cgi);
993 close_conn(c->fd, ev, d);
997 close_conn(int fd, short ev, void *d)
999 struct client *c = d;
1001 switch (tls_close(c->ctx)) {
1002 case TLS_WANT_POLLIN:
1003 reschedule_read(fd, c, &close_conn);
1005 case TLS_WANT_POLLOUT:
1006 reschedule_read(fd, c, &close_conn);
1010 connected_clients--;
1015 if (c->buf != MAP_FAILED)
1016 munmap(c->buf, c->len);
1029 do_accept(int sock, short et, void *d)
1032 struct server *s = d;
1033 struct sockaddr_storage addr;
1034 struct sockaddr *saddr;
1041 saddr = (struct sockaddr*)&addr;
1043 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
1044 if (errno == EWOULDBLOCK || errno == EAGAIN)
1046 fatal("accept: %s", strerror(errno));
1049 for (i = 0; i < MAX_USERS; ++i) {
1052 memset(c, 0, sizeof(*c));
1053 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1054 break; /* goodbye fd! */
1058 c->buf = MAP_FAILED;
1062 reschedule_read(fd, c, &handle_handshake);
1063 connected_clients++;
1072 handle_sighup(int fd, short ev, void *d)
1081 signal_del(&siginfo);
1082 signal_del(&sigusr2);
1083 signal_del(&sighup);
1087 handle_siginfo(int fd, short ev, void *d)
1093 log_info(NULL, "%d connected clients", connected_clients);
1097 loop(struct tls *ctx, int sock4, int sock6)
1099 struct server server;
1104 memset(&server, 0, sizeof(server));
1105 for (i = 0; i < MAX_USERS; ++i)
1106 server.clients[i].fd = -1;
1108 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1109 event_add(&e4, NULL);
1113 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1114 event_add(&e6, NULL);
1117 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1118 signal_add(&sighup, NULL);
1122 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1123 signal_add(&siginfo, NULL);
1125 signal_set(&sigusr2, SIGINFO, &handle_siginfo, NULL);
1126 signal_add(&sigusr2, NULL);