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 struct event e4, e6, sighup, siginfo, sigusr2;
37 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 check_path(struct client *c, const char *path, int *fd)
234 assert(path != NULL);
238 else if (*path == '/')
239 /* in send_dir we add an initial / (to be
240 * redirect-friendly), but here we want to skip it */
245 flags = O_RDONLY | O_NOFOLLOW;
247 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
250 if (fstat(*fd, &sb) == -1) {
251 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
255 if (S_ISDIR(sb.st_mode))
256 return FILE_DIRECTORY;
258 if (sb.st_mode & S_IXUSR)
259 return FILE_EXECUTABLE;
265 open_file(struct client *c)
267 switch (check_path(c, c->iri.path, &c->pfd)) {
268 case FILE_EXECUTABLE:
269 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
270 start_cgi(c->iri.path, "", c);
277 c->next = handle_copy;
278 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
286 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
290 start_reply(c, NOT_FOUND, "not found");
300 * the inverse of this algorithm, i.e. starting from the start of the
301 * path + strlen(cgi), and checking if each component, should be
302 * faster. But it's tedious to write. This does the opposite: starts
303 * from the end and strip one component at a time, until either an
304 * executable is found or we emptied the path.
307 check_for_cgi(struct client *c)
312 strlcpy(path, c->iri.path, sizeof(path));
313 end = strchr(path, '\0');
316 /* go up one level. UNIX paths are simple and POSIX
317 * dirname, with its ambiguities on if the given path
318 * is changed or not, gives me headaches. */
323 switch (check_path(c, path, &c->pfd)) {
324 case FILE_EXECUTABLE:
325 start_cgi(path, end+1, c);
338 start_reply(c, NOT_FOUND, "not found");
343 mark_nonblock(int fd)
347 if ((flags = fcntl(fd, F_GETFL)) == -1)
348 fatal("fcntl(F_GETFL): %s", strerror(errno));
349 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
350 fatal("fcntl(F_SETFL): %s", strerror(errno));
354 handle_handshake(int fd, short ev, void *d)
356 struct client *c = d;
358 const char *servname;
359 const char *parse_err = "unknown error";
361 switch (tls_handshake(c->ctx)) {
362 case 0: /* success */
363 case -1: /* already handshaked */
365 case TLS_WANT_POLLIN:
366 reschedule_read(fd, c, &handle_handshake);
368 case TLS_WANT_POLLOUT:
369 reschedule_write(fd, c, &handle_handshake);
376 servname = tls_conn_servername(c->ctx);
377 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
378 log_info(c, "puny_decode: %s", parse_err);
382 for (h = hosts; h->domain != NULL; ++h) {
383 if (!fnmatch(h->domain, c->domain, 0))
387 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
388 servname != NULL ? servname : "(null)",
390 h->domain != NULL ? h->domain : "(null)");
392 if (h->domain != NULL) {
394 handle_open_conn(fd, ev, c);
399 if (servname != NULL)
400 strncpy(c->req, servname, sizeof(c->req));
402 strncpy(c->req, "null", sizeof(c->req));
404 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
408 strip_path(char *path, int strip)
413 if ((t = strchr(path, '/')) == NULL) {
414 path = strchr(path, '\0');
425 fmt_sbuf(const char *fmt, struct client *c, const char *path)
430 memset(buf, 0, sizeof(buf));
431 for (i = 0; *fmt; ++fmt) {
432 if (i == sizeof(buf)-1 || *fmt == '%') {
433 strlcat(c->sbuf, buf, sizeof(c->sbuf));
434 memset(buf, 0, sizeof(buf));
445 strlcat(c->sbuf, "%", sizeof(c->sbuf));
448 strlcat(c->sbuf, path, sizeof(c->sbuf));
451 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
454 snprintf(buf, sizeof(buf), "%d", conf.port);
455 strlcat(c->sbuf, buf, sizeof(c->sbuf));
456 memset(buf, 0, sizeof(buf));
459 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
462 fatal("%s: unknown fmt specifier %c",
468 strlcat(c->sbuf, buf, sizeof(c->sbuf));
471 /* 1 if a matching `block return' (and apply it), 0 otherwise */
473 apply_block_return(struct client *c)
475 const char *fmt, *path;
478 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
481 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
482 fmt_sbuf(fmt, c, path);
484 start_reply(c, code, c->sbuf);
488 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
490 apply_require_ca(struct client *c)
496 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
499 if (!tls_peer_cert_provided(c->ctx)) {
500 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
504 cert = tls_peer_cert_chain_pem(c->ctx, &len);
505 if (!validate_against_ca(store, cert, len)) {
506 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
514 handle_open_conn(int fd, short ev, void *d)
516 struct client *c = d;
517 const char *parse_err = "invalid request";
518 char decoded[DOMAIN_NAME_LEN];
520 bzero(c->req, sizeof(c->req));
521 bzero(&c->iri, sizeof(c->iri));
523 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
525 log_err(c, "tls_read: %s", tls_error(c->ctx));
526 close_conn(fd, ev, c);
529 case TLS_WANT_POLLIN:
530 reschedule_read(fd, c, &handle_open_conn);
533 case TLS_WANT_POLLOUT:
534 reschedule_write(fd, c, &handle_open_conn);
538 if (!trim_req_iri(c->req, &parse_err)
539 || !parse_iri(c->req, &c->iri, &parse_err)
540 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
541 log_info(c, "iri parse error: %s", parse_err);
542 start_reply(c, BAD_REQUEST, "invalid request");
546 if (c->iri.port_no != conf.port
547 || strcmp(c->iri.schema, "gemini")
548 || strcmp(decoded, c->domain)) {
549 start_reply(c, PROXY_REFUSED, "won't proxy request");
553 if (apply_require_ca(c))
556 if (apply_block_return(c))
559 if (c->host->entrypoint != NULL) {
560 start_cgi(c->host->entrypoint, c->iri.path, c);
568 start_reply(struct client *c, int code, const char *meta)
572 handle_start_reply(c->fd, 0, c);
576 handle_start_reply(int fd, short ev, void *d)
578 struct client *c = d;
579 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
583 lang = vhost_lang(c->host, c->iri.path);
585 snprintf(buf, sizeof(buf), "%d ", c->code);
586 strlcat(buf, c->meta, sizeof(buf));
587 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
588 strlcat(buf, "; lang=", sizeof(buf));
589 strlcat(buf, lang, sizeof(buf));
592 len = strlcat(buf, "\r\n", sizeof(buf));
593 assert(len < sizeof(buf));
595 switch (tls_write(c->ctx, buf, len)) {
597 close_conn(fd, ev, c);
599 case TLS_WANT_POLLIN:
600 reschedule_read(fd, c, &handle_start_reply);
602 case TLS_WANT_POLLOUT:
603 reschedule_write(fd, c, &handle_start_reply);
607 log_request(c, buf, sizeof(buf));
609 if (c->code != SUCCESS)
610 close_conn(fd, ev, c);
616 start_cgi(const char *spath, const char *relpath, struct client *c)
618 char addr[NI_MAXHOST];
621 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
628 if (!send_iri(exfd, &c->iri)
629 || !send_string(exfd, spath)
630 || !send_string(exfd, relpath)
631 || !send_string(exfd, addr)
632 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
633 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
634 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
635 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
636 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
637 || !send_vhost(exfd, c->host))
641 if ((c->pfd = recv_fd(exfd)) == -1) {
642 start_reply(c, TEMP_FAILURE, "internal server error");
646 reschedule_read(c->pfd, c, &handle_cgi_reply);
650 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
651 fatal("cannot talk to the executor process");
655 open_dir(struct client *c)
661 len = strlen(c->iri.path);
662 if (len > 0 && !ends_with(c->iri.path, "/")) {
663 redirect_canonical_dir(c);
667 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
668 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
669 if (!ends_with(c->sbuf, "/"))
670 strlcat(c->sbuf, "/", sizeof(c->sbuf));
671 before_file = strchr(c->sbuf, '\0');
672 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
674 if (len >= sizeof(c->sbuf)) {
675 start_reply(c, TEMP_FAILURE, "internal server error");
679 c->iri.path = c->sbuf;
681 /* close later unless we have to generate the dir listing */
685 switch (check_path(c, c->iri.path, &c->pfd)) {
686 case FILE_EXECUTABLE:
687 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
688 start_cgi(c->iri.path, "", c);
695 c->next = handle_copy;
696 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
700 start_reply(c, TEMP_REDIRECT, c->sbuf);
706 if (!vhost_auto_index(c->host, c->iri.path)) {
707 start_reply(c, NOT_FOUND, "not found");
712 c->next = enter_handle_dirlist;
714 if ((c->dir = fdopendir(c->pfd)) == NULL) {
715 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
716 c->pfd, c->host->domain, c->iri.path, strerror(errno));
717 start_reply(c, TEMP_FAILURE, "internal server error");
722 start_reply(c, SUCCESS, "text/gemini");
734 redirect_canonical_dir(struct client *c)
738 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
739 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
740 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
742 if (len >= sizeof(c->sbuf)) {
743 start_reply(c, TEMP_FAILURE, "internal server error");
747 start_reply(c, TEMP_REDIRECT, c->sbuf);
751 enter_handle_dirlist(int fd, short ev, void *d)
753 struct client *c = d;
757 strlcpy(b, c->iri.path, sizeof(b));
758 l = snprintf(c->sbuf, sizeof(c->sbuf),
759 "# Index of %s\n\n", b);
760 if (l >= sizeof(c->sbuf)) {
761 /* this is impossible, given that we have enough space
762 * in c->sbuf to hold the ancilliary string plus the
763 * full path; but it wouldn't read nice without some
764 * error checking, and I'd like to avoid a strlen. */
765 close_conn(fd, ev, c);
770 handle_dirlist(fd, ev, c);
774 handle_dirlist(int fd, short ev, void *d)
776 struct client *c = d;
780 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
782 close_conn(fd, ev, c);
784 case TLS_WANT_POLLOUT:
785 reschedule_read(fd, c, &handle_dirlist);
787 case TLS_WANT_POLLIN:
788 reschedule_write(fd, c, &handle_dirlist);
796 send_directory_listing(fd, ev, c);
800 read_next_dir_entry(struct client *c)
806 if ((d = readdir(c->dir)) == NULL) {
808 log_err(c, "readdir: %s", strerror(errno));
811 } while (!strcmp(d->d_name, "."));
813 /* XXX: url escape */
814 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
815 d->d_name, d->d_name);
816 c->len = strlen(c->sbuf);
823 send_directory_listing(int fd, short ev, void *d)
825 struct client *c = d;
830 if (!read_next_dir_entry(c))
835 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
839 case TLS_WANT_POLLOUT:
840 reschedule_read(fd, c, &send_directory_listing);
843 case TLS_WANT_POLLIN:
844 reschedule_write(fd, c, &send_directory_listing);
856 close_conn(fd, ev, d);
859 /* accumulate the meta line from the cgi script. */
861 handle_cgi_reply(int fd, short ev, void *d)
863 struct client *c = d;
869 buf = c->sbuf + c->len;
870 len = sizeof(c->sbuf) - c->len;
872 r = read(c->pfd, buf, len);
873 if (r == 0 || r == -1) {
874 start_reply(c, CGI_ERROR, "CGI error");
880 /* TODO: error if the CGI script don't reply correctly */
881 e = strchr(c->sbuf, '\n');
882 if (e != NULL || c->len == sizeof(c->sbuf)) {
883 log_request(c, c->sbuf, c->len);
886 handle_copy(fd, ev, c);
890 reschedule_read(fd, c, &handle_cgi_reply);
894 handle_copy(int fd, short ev, void *d)
896 struct client *c = d;
901 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
905 case TLS_WANT_POLLOUT:
906 reschedule_write(c->fd, c, &handle_copy);
909 case TLS_WANT_POLLIN:
910 reschedule_read(c->fd, c, &handle_copy);
920 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
924 if (errno == EAGAIN || errno == EWOULDBLOCK) {
925 reschedule_read(c->pfd, c, &handle_copy);
936 close_conn(c->fd, ev, d);
940 close_conn(int fd, short ev, void *d)
942 struct client *c = d;
944 switch (tls_close(c->ctx)) {
945 case TLS_WANT_POLLIN:
946 reschedule_read(fd, c, &close_conn);
948 case TLS_WANT_POLLOUT:
949 reschedule_read(fd, c, &close_conn);
969 do_accept(int sock, short et, void *d)
972 struct server *s = d;
973 struct sockaddr_storage addr;
974 struct sockaddr *saddr;
981 saddr = (struct sockaddr*)&addr;
983 if ((fd = accept(sock, saddr, &len)) == -1) {
984 if (errno == EWOULDBLOCK || errno == EAGAIN)
986 fatal("accept: %s", strerror(errno));
991 for (i = 0; i < MAX_USERS; ++i) {
994 memset(c, 0, sizeof(*c));
995 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
996 break; /* goodbye fd! */
1003 reschedule_read(fd, c, &handle_handshake);
1004 connected_clients++;
1013 handle_sighup(int fd, short ev, void *d)
1022 signal_del(&siginfo);
1023 signal_del(&sigusr2);
1024 signal_del(&sighup);
1028 handle_siginfo(int fd, short ev, void *d)
1034 log_info(NULL, "%d connected clients", connected_clients);
1038 loop(struct tls *ctx, int sock4, int sock6)
1040 struct server server;
1045 memset(&server, 0, sizeof(server));
1046 for (i = 0; i < MAX_USERS; ++i)
1047 server.clients[i].fd = -1;
1049 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1050 event_add(&e4, NULL);
1054 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1055 event_add(&e6, NULL);
1058 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1059 signal_add(&sighup, NULL);
1063 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1064 signal_add(&siginfo, NULL);
1066 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1067 signal_add(&sigusr2, NULL);