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.
32 struct client clients[MAX_USERS];
36 static struct event e4, e6, sighup, siginfo, sigusr2;
37 static int has_ipv6, has_siginfo;
39 int connected_clients;
41 static inline int matches(const char*, const char*);
43 static inline void reschedule_read(int, struct client*, statefn);
44 static inline void reschedule_write(int, struct client*, statefn);
46 static int check_path(struct client*, const char*, int*);
47 static void open_file(struct client*);
48 static void check_for_cgi(struct client*);
49 static void handle_handshake(int, short, void*);
50 static char *strip_path(char*, int);
51 static void fmt_sbuf(const char*, struct client*, const char*);
52 static int apply_block_return(struct client*);
53 static int apply_require_ca(struct client*);
54 static void handle_open_conn(int, short, void*);
55 static void start_reply(struct client*, int, const char*);
56 static void handle_start_reply(int, short, void*);
57 static void start_cgi(const char*, const char*, struct client*);
58 static void open_dir(struct client*);
59 static void redirect_canonical_dir(struct client*);
60 static void enter_handle_dirlist(int, short, void*);
61 static void handle_dirlist(int, short, void*);
62 static int read_next_dir_entry(struct client*);
63 static void send_directory_listing(int, short, void*);
64 static void handle_cgi_reply(int, short, void*);
65 static void handle_copy(int, short, void*);
66 static void close_conn(int, short, void*);
67 static void do_accept(int, short, void*);
68 static void handle_sighup(int, short, void*);
71 matches(const char *pattern, const char *path)
75 return !fnmatch(pattern, path, 0);
79 reschedule_read(int fd, struct client *c, statefn fn)
81 event_once(fd, EV_READ, fn, c, NULL);
85 reschedule_write(int fd, struct client *c, statefn fn)
87 event_once(fd, EV_WRITE, fn, c, NULL);
91 vhost_lang(struct vhost *v, const char *path)
95 if (v == NULL || path == NULL)
98 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
99 if (loc->lang != NULL) {
100 if (matches(loc->match, path))
105 return v->locations[0].lang;
109 vhost_default_mime(struct vhost *v, const char *path)
111 struct location *loc;
112 const char *default_mime = "application/octet-stream";
114 if (v == NULL || path == NULL)
117 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
118 if (loc->default_mime != NULL) {
119 if (matches(loc->match, path))
120 return loc->default_mime;
124 if (v->locations[0].default_mime != NULL)
125 return v->locations[0].default_mime;
130 vhost_index(struct vhost *v, const char *path)
132 struct location *loc;
133 const char *index = "index.gmi";
135 if (v == NULL || path == NULL)
138 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
139 if (loc->index != NULL) {
140 if (matches(loc->match, path))
145 if (v->locations[0].index != NULL)
146 return v->locations[0].index;
151 vhost_auto_index(struct vhost *v, const char *path)
153 struct location *loc;
155 if (v == NULL || path == NULL)
158 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
159 if (loc->auto_index != 0) {
160 if (matches(loc->match, path))
161 return loc->auto_index == 1;
165 return v->locations[0].auto_index == 1;
169 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
171 struct location *loc;
173 if (v == NULL || path == NULL)
176 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
177 if (loc->block_code != 0) {
178 if (matches(loc->match, path)) {
179 *code = loc->block_code;
180 *fmt = loc->block_fmt;
186 *code = v->locations[0].block_code;
187 *fmt = v->locations[0].block_fmt;
188 return v->locations[0].block_code != 0;
192 vhost_strip(struct vhost *v, const char *path)
194 struct location *loc;
196 if (v == NULL || path == NULL)
199 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
200 if (loc->strip != 0) {
201 if (matches(loc->match, path))
206 return v->locations[0].strip;
210 vhost_require_ca(struct vhost *v, const char *path)
212 struct location *loc;
214 if (v == NULL || path == NULL)
217 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
218 if (loc->reqca != NULL) {
219 if (matches(loc->match, path))
224 return v->locations[0].reqca;
228 vhost_disable_log(struct vhost *v, const char *path)
230 struct location *loc;
232 if (v == NULL || path == NULL)
235 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
236 if (loc->disable_log && matches(loc->match, path))
240 return v->locations[0].disable_log;
244 check_path(struct client *c, const char *path, int *fd)
250 assert(path != NULL);
254 else if (*path == '/')
255 /* in send_dir we add an initial / (to be
256 * redirect-friendly), but here we want to skip it */
261 flags = O_RDONLY | O_NOFOLLOW;
263 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
266 if (fstat(*fd, &sb) == -1) {
267 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
271 if (S_ISDIR(sb.st_mode))
272 return FILE_DIRECTORY;
274 if (sb.st_mode & S_IXUSR)
275 return FILE_EXECUTABLE;
281 open_file(struct client *c)
283 switch (check_path(c, c->iri.path, &c->pfd)) {
284 case FILE_EXECUTABLE:
285 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
286 start_cgi(c->iri.path, "", c);
293 c->next = handle_copy;
294 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
302 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
306 start_reply(c, NOT_FOUND, "not found");
316 * the inverse of this algorithm, i.e. starting from the start of the
317 * path + strlen(cgi), and checking if each component, should be
318 * faster. But it's tedious to write. This does the opposite: starts
319 * from the end and strip one component at a time, until either an
320 * executable is found or we emptied the path.
323 check_for_cgi(struct client *c)
328 strlcpy(path, c->iri.path, sizeof(path));
329 end = strchr(path, '\0');
332 /* go up one level. UNIX paths are simple and POSIX
333 * dirname, with its ambiguities on if the given path
334 * is changed or not, gives me headaches. */
339 switch (check_path(c, path, &c->pfd)) {
340 case FILE_EXECUTABLE:
341 start_cgi(path, end+1, c);
354 start_reply(c, NOT_FOUND, "not found");
359 mark_nonblock(int fd)
363 if ((flags = fcntl(fd, F_GETFL)) == -1)
364 fatal("fcntl(F_GETFL): %s", strerror(errno));
365 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
366 fatal("fcntl(F_SETFL): %s", strerror(errno));
370 handle_handshake(int fd, short ev, void *d)
372 struct client *c = d;
374 const char *servname;
375 const char *parse_err = "unknown error";
377 switch (tls_handshake(c->ctx)) {
378 case 0: /* success */
379 case -1: /* already handshaked */
381 case TLS_WANT_POLLIN:
382 reschedule_read(fd, c, &handle_handshake);
384 case TLS_WANT_POLLOUT:
385 reschedule_write(fd, c, &handle_handshake);
392 servname = tls_conn_servername(c->ctx);
393 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
394 log_info(c, "puny_decode: %s", parse_err);
398 for (h = hosts; h->domain != NULL; ++h) {
399 if (matches(h->domain, c->domain))
403 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
404 servname != NULL ? servname : "(null)",
406 h->domain != NULL ? h->domain : "(null)");
408 if (h->domain != NULL) {
410 handle_open_conn(fd, ev, c);
415 if (servname != NULL)
416 strncpy(c->req, servname, sizeof(c->req));
418 strncpy(c->req, "null", sizeof(c->req));
420 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
424 strip_path(char *path, int strip)
429 if ((t = strchr(path, '/')) == NULL) {
430 path = strchr(path, '\0');
441 fmt_sbuf(const char *fmt, struct client *c, const char *path)
446 memset(buf, 0, sizeof(buf));
447 for (i = 0; *fmt; ++fmt) {
448 if (i == sizeof(buf)-1 || *fmt == '%') {
449 strlcat(c->sbuf, buf, sizeof(c->sbuf));
450 memset(buf, 0, sizeof(buf));
461 strlcat(c->sbuf, "%", sizeof(c->sbuf));
464 strlcat(c->sbuf, path, sizeof(c->sbuf));
467 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
470 snprintf(buf, sizeof(buf), "%d", conf.port);
471 strlcat(c->sbuf, buf, sizeof(c->sbuf));
472 memset(buf, 0, sizeof(buf));
475 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
478 fatal("%s: unknown fmt specifier %c",
484 strlcat(c->sbuf, buf, sizeof(c->sbuf));
487 /* 1 if a matching `block return' (and apply it), 0 otherwise */
489 apply_block_return(struct client *c)
491 const char *fmt, *path;
494 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
497 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
498 fmt_sbuf(fmt, c, path);
500 start_reply(c, code, c->sbuf);
504 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
506 apply_require_ca(struct client *c)
512 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
515 if (!tls_peer_cert_provided(c->ctx)) {
516 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
520 cert = tls_peer_cert_chain_pem(c->ctx, &len);
521 if (!validate_against_ca(store, cert, len)) {
522 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
530 handle_open_conn(int fd, short ev, void *d)
532 struct client *c = d;
533 const char *parse_err = "invalid request";
534 char decoded[DOMAIN_NAME_LEN];
536 bzero(c->req, sizeof(c->req));
537 bzero(&c->iri, sizeof(c->iri));
539 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
541 log_err(c, "tls_read: %s", tls_error(c->ctx));
542 close_conn(fd, ev, c);
545 case TLS_WANT_POLLIN:
546 reschedule_read(fd, c, &handle_open_conn);
549 case TLS_WANT_POLLOUT:
550 reschedule_write(fd, c, &handle_open_conn);
554 if (!trim_req_iri(c->req, &parse_err)
555 || !parse_iri(c->req, &c->iri, &parse_err)
556 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
557 log_info(c, "iri parse error: %s", parse_err);
558 start_reply(c, BAD_REQUEST, "invalid request");
562 if (c->iri.port_no != conf.port
563 || strcmp(c->iri.schema, "gemini")
564 || strcmp(decoded, c->domain)) {
565 start_reply(c, PROXY_REFUSED, "won't proxy request");
569 if (apply_require_ca(c))
572 if (apply_block_return(c))
575 if (c->host->entrypoint != NULL) {
576 start_cgi(c->host->entrypoint, c->iri.path, c);
584 start_reply(struct client *c, int code, const char *meta)
588 handle_start_reply(c->fd, 0, c);
592 handle_start_reply(int fd, short ev, void *d)
594 struct client *c = d;
595 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
599 lang = vhost_lang(c->host, c->iri.path);
601 snprintf(buf, sizeof(buf), "%d ", c->code);
602 strlcat(buf, c->meta, sizeof(buf));
603 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
604 strlcat(buf, "; lang=", sizeof(buf));
605 strlcat(buf, lang, sizeof(buf));
608 len = strlcat(buf, "\r\n", sizeof(buf));
609 assert(len < sizeof(buf));
611 switch (tls_write(c->ctx, buf, len)) {
613 close_conn(fd, ev, c);
615 case TLS_WANT_POLLIN:
616 reschedule_read(fd, c, &handle_start_reply);
618 case TLS_WANT_POLLOUT:
619 reschedule_write(fd, c, &handle_start_reply);
623 if (!vhost_disable_log(c->host, c->iri.path))
624 log_request(c, buf, sizeof(buf));
626 if (c->code != SUCCESS)
627 close_conn(fd, ev, c);
633 start_cgi(const char *spath, const char *relpath, struct client *c)
635 char addr[NI_MAXHOST];
638 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
645 if (!send_iri(exfd, &c->iri)
646 || !send_string(exfd, spath)
647 || !send_string(exfd, relpath)
648 || !send_string(exfd, addr)
649 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
650 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
651 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
652 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
653 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
654 || !send_vhost(exfd, c->host))
658 if ((c->pfd = recv_fd(exfd)) == -1) {
659 start_reply(c, TEMP_FAILURE, "internal server error");
663 reschedule_read(c->pfd, c, &handle_cgi_reply);
667 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
668 fatal("cannot talk to the executor process");
672 open_dir(struct client *c)
678 len = strlen(c->iri.path);
679 if (len > 0 && !ends_with(c->iri.path, "/")) {
680 redirect_canonical_dir(c);
684 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
685 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
686 if (!ends_with(c->sbuf, "/"))
687 strlcat(c->sbuf, "/", sizeof(c->sbuf));
688 before_file = strchr(c->sbuf, '\0');
689 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
691 if (len >= sizeof(c->sbuf)) {
692 start_reply(c, TEMP_FAILURE, "internal server error");
696 c->iri.path = c->sbuf;
698 /* close later unless we have to generate the dir listing */
702 switch (check_path(c, c->iri.path, &c->pfd)) {
703 case FILE_EXECUTABLE:
704 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
705 start_cgi(c->iri.path, "", c);
712 c->next = handle_copy;
713 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
717 start_reply(c, TEMP_REDIRECT, c->sbuf);
723 if (!vhost_auto_index(c->host, c->iri.path)) {
724 start_reply(c, NOT_FOUND, "not found");
729 c->next = enter_handle_dirlist;
731 if ((c->dir = fdopendir(c->pfd)) == NULL) {
732 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
733 c->pfd, c->host->domain, c->iri.path, strerror(errno));
734 start_reply(c, TEMP_FAILURE, "internal server error");
739 start_reply(c, SUCCESS, "text/gemini");
751 redirect_canonical_dir(struct client *c)
755 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
756 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
757 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
759 if (len >= sizeof(c->sbuf)) {
760 start_reply(c, TEMP_FAILURE, "internal server error");
764 start_reply(c, TEMP_REDIRECT, c->sbuf);
768 enter_handle_dirlist(int fd, short ev, void *d)
770 struct client *c = d;
774 strlcpy(b, c->iri.path, sizeof(b));
775 l = snprintf(c->sbuf, sizeof(c->sbuf),
776 "# Index of %s\n\n", b);
777 if (l >= sizeof(c->sbuf)) {
778 /* this is impossible, given that we have enough space
779 * in c->sbuf to hold the ancilliary string plus the
780 * full path; but it wouldn't read nice without some
781 * error checking, and I'd like to avoid a strlen. */
782 close_conn(fd, ev, c);
787 handle_dirlist(fd, ev, c);
791 handle_dirlist(int fd, short ev, void *d)
793 struct client *c = d;
797 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
799 close_conn(fd, ev, c);
801 case TLS_WANT_POLLOUT:
802 reschedule_read(fd, c, &handle_dirlist);
804 case TLS_WANT_POLLIN:
805 reschedule_write(fd, c, &handle_dirlist);
813 send_directory_listing(fd, ev, c);
817 read_next_dir_entry(struct client *c)
823 if ((d = readdir(c->dir)) == NULL) {
825 log_err(c, "readdir: %s", strerror(errno));
828 } while (!strcmp(d->d_name, "."));
830 /* XXX: url escape */
831 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
832 d->d_name, d->d_name);
833 c->len = strlen(c->sbuf);
840 send_directory_listing(int fd, short ev, void *d)
842 struct client *c = d;
847 if (!read_next_dir_entry(c))
852 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
856 case TLS_WANT_POLLOUT:
857 reschedule_read(fd, c, &send_directory_listing);
860 case TLS_WANT_POLLIN:
861 reschedule_write(fd, c, &send_directory_listing);
873 close_conn(fd, ev, d);
876 /* accumulate the meta line from the cgi script. */
878 handle_cgi_reply(int fd, short ev, void *d)
880 struct client *c = d;
886 buf = c->sbuf + c->len;
887 len = sizeof(c->sbuf) - c->len;
889 r = read(c->pfd, buf, len);
890 if (r == 0 || r == -1) {
891 start_reply(c, CGI_ERROR, "CGI error");
897 /* TODO: error if the CGI script don't reply correctly */
898 e = strchr(c->sbuf, '\n');
899 if (e != NULL || c->len == sizeof(c->sbuf)) {
900 log_request(c, c->sbuf, c->len);
903 handle_copy(fd, ev, c);
907 reschedule_read(fd, c, &handle_cgi_reply);
911 handle_copy(int fd, short ev, void *d)
913 struct client *c = d;
918 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
922 case TLS_WANT_POLLOUT:
923 reschedule_write(c->fd, c, &handle_copy);
926 case TLS_WANT_POLLIN:
927 reschedule_read(c->fd, c, &handle_copy);
937 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
941 if (errno == EAGAIN || errno == EWOULDBLOCK) {
942 reschedule_read(c->pfd, c, &handle_copy);
953 close_conn(c->fd, ev, d);
957 close_conn(int fd, short ev, void *d)
959 struct client *c = d;
961 switch (tls_close(c->ctx)) {
962 case TLS_WANT_POLLIN:
963 reschedule_read(fd, c, &close_conn);
965 case TLS_WANT_POLLOUT:
966 reschedule_read(fd, c, &close_conn);
986 do_accept(int sock, short et, void *d)
989 struct server *s = d;
990 struct sockaddr_storage addr;
991 struct sockaddr *saddr;
998 saddr = (struct sockaddr*)&addr;
1000 if ((fd = accept(sock, saddr, &len)) == -1) {
1001 if (errno == EWOULDBLOCK || errno == EAGAIN)
1003 fatal("accept: %s", strerror(errno));
1008 for (i = 0; i < MAX_USERS; ++i) {
1011 memset(c, 0, sizeof(*c));
1012 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1013 break; /* goodbye fd! */
1020 reschedule_read(fd, c, &handle_handshake);
1021 connected_clients++;
1030 handle_sighup(int fd, short ev, void *d)
1039 signal_del(&siginfo);
1040 signal_del(&sigusr2);
1041 signal_del(&sighup);
1045 handle_siginfo(int fd, short ev, void *d)
1051 log_info(NULL, "%d connected clients", connected_clients);
1055 loop(struct tls *ctx, int sock4, int sock6)
1057 struct server server;
1062 memset(&server, 0, sizeof(server));
1063 for (i = 0; i < MAX_USERS; ++i)
1064 server.clients[i].fd = -1;
1066 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1067 event_add(&e4, NULL);
1071 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1072 event_add(&e6, NULL);
1075 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1076 signal_add(&sighup, NULL);
1080 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1081 signal_add(&siginfo, NULL);
1083 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1084 signal_add(&sigusr2, NULL);