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 server_events {
44 int connected_clients;
46 static inline void reschedule_read(int, struct client*, statefn);
47 static inline void reschedule_write(int, struct client*, statefn);
49 static int check_path(struct client*, const char*, int*);
50 static void open_file(struct client*);
51 static void load_file(struct client*);
52 static void check_for_cgi(struct client*);
53 static void handle_handshake(int, short, void*);
54 static char *strip_path(char*, int);
55 static void fmt_sbuf(const char*, struct client*, const char*);
56 static int apply_block_return(struct client*);
57 static void handle_open_conn(int, short, void*);
58 static void start_reply(struct client*, int, const char*);
59 static void handle_start_reply(int, short, void*);
60 static void start_cgi(const char*, const char*, struct client*);
61 static void send_file(int, short, void*);
62 static void open_dir(struct client*);
63 static void redirect_canonical_dir(struct client*);
64 static void enter_handle_dirlist(int, short, void*);
65 static void handle_dirlist(int, short, void*);
66 static int read_next_dir_entry(struct client*);
67 static void send_directory_listing(int, short, void*);
68 static void handle_cgi_reply(int, short, void*);
69 static void handle_cgi(int, short, void*);
70 static void close_conn(int, short, void*);
71 static void do_accept(int, short, void*);
72 static void handle_sighup(int, short, void*);
75 reschedule_read(int fd, struct client *c, statefn fn)
77 event_once(fd, EV_READ, fn, c, NULL);
81 reschedule_write(int fd, struct client *c, statefn fn)
83 event_once(fd, EV_WRITE, fn, c, NULL);
87 vhost_lang(struct vhost *v, const char *path)
91 if (v == NULL || path == NULL)
94 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
95 if (loc->lang != NULL) {
96 if (!fnmatch(loc->match, path, 0))
101 return v->locations[0].lang;
105 vhost_default_mime(struct vhost *v, const char *path)
107 struct location *loc;
108 const char *default_mime = "application/octet-stream";
110 if (v == NULL || path == NULL)
113 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
114 if (loc->default_mime != NULL) {
115 if (!fnmatch(loc->match, path, 0))
116 return loc->default_mime;
120 if (v->locations[0].default_mime != NULL)
121 return v->locations[0].default_mime;
126 vhost_index(struct vhost *v, const char *path)
128 struct location *loc;
129 const char *index = "index.gmi";
131 if (v == NULL || path == NULL)
134 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
135 if (loc->index != NULL) {
136 if (!fnmatch(loc->match, path, 0))
141 if (v->locations[0].index != NULL)
142 return v->locations[0].index;
147 vhost_auto_index(struct vhost *v, const char *path)
149 struct location *loc;
151 if (v == NULL || path == NULL)
154 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
155 if (loc->auto_index != 0) {
156 if (!fnmatch(loc->match, path, 0))
157 return loc->auto_index == 1;
161 return v->locations[0].auto_index == 1;
165 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
167 struct location *loc;
169 if (v == NULL || path == NULL)
172 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
173 if (loc->block_code != 0) {
174 if (!fnmatch(loc->match, path, 0)) {
175 *code = loc->block_code;
176 *fmt = loc->block_fmt;
182 *code = v->locations[0].block_code;
183 *fmt = v->locations[0].block_fmt;
184 return v->locations[0].block_code != 0;
188 vhost_strip(struct vhost *v, const char *path)
190 struct location *loc;
192 if (v == NULL || path == NULL)
195 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
196 if (loc->strip != 0) {
197 if (!fnmatch(loc->match, path, 0))
202 return v->locations[0].strip;
206 check_path(struct client *c, const char *path, int *fd)
212 assert(path != NULL);
216 else if (*path == '/')
217 /* in send_dir we add an initial / (to be
218 * redirect-friendly), but here we want to skip it */
223 flags = O_RDONLY | O_NOFOLLOW;
225 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
228 if (fstat(*fd, &sb) == -1) {
229 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
233 if (S_ISDIR(sb.st_mode))
234 return FILE_DIRECTORY;
236 if (sb.st_mode & S_IXUSR)
237 return FILE_EXECUTABLE;
243 open_file(struct client *c)
245 switch (check_path(c, c->iri.path, &c->pfd)) {
246 case FILE_EXECUTABLE:
247 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
248 start_cgi(c->iri.path, "", c);
263 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
267 start_reply(c, NOT_FOUND, "not found");
277 load_file(struct client *c)
279 if ((c->len = filesize(c->pfd)) == -1) {
280 log_err(c, "failed to get file size for %s: %s",
281 c->iri.path, strerror(errno));
282 start_reply(c, TEMP_FAILURE, "internal server error");
286 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
287 c->pfd, 0)) == MAP_FAILED) {
288 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
289 start_reply(c, TEMP_FAILURE, "internal server error");
294 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
298 * the inverse of this algorithm, i.e. starting from the start of the
299 * path + strlen(cgi), and checking if each component, should be
300 * faster. But it's tedious to write. This does the opposite: starts
301 * from the end and strip one component at a time, until either an
302 * executable is found or we emptied the path.
305 check_for_cgi(struct client *c)
310 strlcpy(path, c->iri.path, sizeof(path));
311 end = strchr(path, '\0');
314 /* go up one level. UNIX paths are simple and POSIX
315 * dirname, with its ambiguities on if the given path
316 * is changed or not, gives me headaches. */
321 switch (check_path(c, path, &c->pfd)) {
322 case FILE_EXECUTABLE:
323 start_cgi(path, end+1, c);
336 start_reply(c, NOT_FOUND, "not found");
341 mark_nonblock(int fd)
345 if ((flags = fcntl(fd, F_GETFL)) == -1)
346 fatal("fcntl(F_GETFL): %s", strerror(errno));
347 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
348 fatal("fcntl(F_SETFL): %s", strerror(errno));
352 handle_handshake(int fd, short ev, void *d)
354 struct client *c = d;
356 const char *servname;
357 const char *parse_err = "unknown error";
359 switch (tls_handshake(c->ctx)) {
360 case 0: /* success */
361 case -1: /* already handshaked */
363 case TLS_WANT_POLLIN:
364 reschedule_read(fd, c, &handle_handshake);
366 case TLS_WANT_POLLOUT:
367 reschedule_write(fd, c, &handle_handshake);
374 servname = tls_conn_servername(c->ctx);
375 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
376 log_info(c, "puny_decode: %s", parse_err);
380 for (h = hosts; h->domain != NULL; ++h) {
381 if (!fnmatch(h->domain, c->domain, 0))
385 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
386 servname != NULL ? servname : "(null)",
388 h->domain != NULL ? h->domain : "(null)");
390 if (h->domain != NULL) {
392 handle_open_conn(fd, ev, c);
397 if (servname != NULL)
398 strncpy(c->req, servname, sizeof(c->req));
400 strncpy(c->req, "null", sizeof(c->req));
402 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
406 strip_path(char *path, int strip)
411 if ((t = strchr(path, '/')) == NULL) {
412 path = strchr(path, '\0');
423 fmt_sbuf(const char *fmt, struct client *c, const char *path)
428 memset(buf, 0, sizeof(buf));
429 for (i = 0; *fmt; ++fmt) {
430 if (i == sizeof(buf)-1 || *fmt == '%') {
431 strlcat(c->sbuf, buf, sizeof(c->sbuf));
432 memset(buf, 0, sizeof(buf));
443 strlcat(c->sbuf, "%", sizeof(c->sbuf));
446 strlcat(c->sbuf, path, sizeof(c->sbuf));
449 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
452 snprintf(buf, sizeof(buf), "%d", conf.port);
453 strlcat(c->sbuf, buf, sizeof(c->sbuf));
454 memset(buf, 0, sizeof(buf));
457 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
460 fatal("%s: unknown fmt specifier %c",
466 strlcat(c->sbuf, buf, sizeof(c->sbuf));
469 /* 1 if a matching `block return' (and apply it), 0 otherwise */
471 apply_block_return(struct client *c)
473 const char *fmt, *path;
476 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
479 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
480 fmt_sbuf(fmt, c, path);
482 start_reply(c, code, c->sbuf);
487 handle_open_conn(int fd, short ev, void *d)
489 struct client *c = d;
490 const char *parse_err = "invalid request";
491 char decoded[DOMAIN_NAME_LEN];
493 bzero(c->req, sizeof(c->req));
494 bzero(&c->iri, sizeof(c->iri));
496 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
498 log_err(c, "tls_read: %s", tls_error(c->ctx));
499 close_conn(fd, ev, c);
502 case TLS_WANT_POLLIN:
503 reschedule_read(fd, c, &handle_open_conn);
506 case TLS_WANT_POLLOUT:
507 reschedule_write(fd, c, &handle_open_conn);
511 if (!trim_req_iri(c->req, &parse_err)
512 || !parse_iri(c->req, &c->iri, &parse_err)
513 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
514 log_info(c, "iri parse error: %s", parse_err);
515 start_reply(c, BAD_REQUEST, "invalid request");
519 if (c->iri.port_no != conf.port
520 || strcmp(c->iri.schema, "gemini")
521 || strcmp(decoded, c->domain)) {
522 start_reply(c, PROXY_REFUSED, "won't proxy request");
526 if (apply_block_return(c))
529 if (c->host->entrypoint != NULL) {
530 start_cgi(c->host->entrypoint, c->iri.path, c);
538 start_reply(struct client *c, int code, const char *meta)
542 handle_start_reply(c->fd, 0, c);
546 handle_start_reply(int fd, short ev, void *d)
548 struct client *c = d;
549 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
553 lang = vhost_lang(c->host, c->iri.path);
555 snprintf(buf, sizeof(buf), "%d ", c->code);
556 strlcat(buf, c->meta, sizeof(buf));
557 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
558 strlcat(buf, "; lang=", sizeof(buf));
559 strlcat(buf, lang, sizeof(buf));
562 len = strlcat(buf, "\r\n", sizeof(buf));
563 assert(len < sizeof(buf));
565 switch (tls_write(c->ctx, buf, len)) {
567 close_conn(fd, ev, c);
569 case TLS_WANT_POLLIN:
570 reschedule_read(fd, c, &handle_start_reply);
572 case TLS_WANT_POLLOUT:
573 reschedule_write(fd, c, &handle_start_reply);
577 log_request(c, buf, sizeof(buf));
579 if (c->code != SUCCESS)
580 close_conn(fd, ev, c);
586 start_cgi(const char *spath, const char *relpath, struct client *c)
588 char addr[NI_MAXHOST];
591 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
598 if (!send_iri(exfd, &c->iri)
599 || !send_string(exfd, spath)
600 || !send_string(exfd, relpath)
601 || !send_string(exfd, addr)
602 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
603 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
604 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
605 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
606 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
607 || !send_vhost(exfd, c->host))
611 if ((c->pfd = recv_fd(exfd)) == -1) {
612 start_reply(c, TEMP_FAILURE, "internal server error");
616 reschedule_read(c->pfd, c, &handle_cgi_reply);
620 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
621 fatal("cannot talk to the executor process");
625 send_file(int fd, short ev, void *d)
627 struct client *c = d;
630 len = (c->buf + c->len) - c->i;
633 switch (ret = tls_write(c->ctx, c->i, len)) {
635 log_err(c, "tls_write: %s", tls_error(c->ctx));
636 close_conn(fd, ev, c);
639 case TLS_WANT_POLLIN:
640 reschedule_read(fd, c, &send_file);
643 case TLS_WANT_POLLOUT:
644 reschedule_write(fd, c, &send_file);
654 close_conn(fd, ev, c);
658 open_dir(struct client *c)
664 len = strlen(c->iri.path);
665 if (len > 0 && !ends_with(c->iri.path, "/")) {
666 redirect_canonical_dir(c);
670 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
671 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
672 if (!ends_with(c->sbuf, "/"))
673 strlcat(c->sbuf, "/", sizeof(c->sbuf));
674 before_file = strchr(c->sbuf, '\0');
675 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
677 if (len >= sizeof(c->sbuf)) {
678 start_reply(c, TEMP_FAILURE, "internal server error");
682 c->iri.path = c->sbuf;
684 /* close later unless we have to generate the dir listing */
688 switch (check_path(c, c->iri.path, &c->pfd)) {
689 case FILE_EXECUTABLE:
690 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
691 start_cgi(c->iri.path, "", c);
702 start_reply(c, TEMP_REDIRECT, c->sbuf);
708 if (!vhost_auto_index(c->host, c->iri.path)) {
709 start_reply(c, NOT_FOUND, "not found");
714 c->next = enter_handle_dirlist;
716 if ((c->dir = fdopendir(c->pfd)) == NULL) {
717 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
718 c->pfd, c->host->domain, c->iri.path, strerror(errno));
719 start_reply(c, TEMP_FAILURE, "internal server error");
724 start_reply(c, SUCCESS, "text/gemini");
736 redirect_canonical_dir(struct client *c)
740 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
741 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
742 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
744 if (len >= sizeof(c->sbuf)) {
745 start_reply(c, TEMP_FAILURE, "internal server error");
749 start_reply(c, TEMP_REDIRECT, c->sbuf);
753 enter_handle_dirlist(int fd, short ev, void *d)
755 struct client *c = d;
759 strlcpy(b, c->iri.path, sizeof(b));
760 l = snprintf(c->sbuf, sizeof(c->sbuf),
761 "# Index of %s\n\n", b);
762 if (l >= sizeof(c->sbuf)) {
763 /* this is impossible, given that we have enough space
764 * in c->sbuf to hold the ancilliary string plus the
765 * full path; but it wouldn't read nice without some
766 * error checking, and I'd like to avoid a strlen. */
767 close_conn(fd, ev, c);
772 handle_dirlist(fd, ev, c);
776 handle_dirlist(int fd, short ev, void *d)
778 struct client *c = d;
782 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
784 close_conn(fd, ev, c);
786 case TLS_WANT_POLLOUT:
787 reschedule_read(fd, c, &handle_dirlist);
789 case TLS_WANT_POLLIN:
790 reschedule_write(fd, c, &handle_dirlist);
798 send_directory_listing(fd, ev, c);
802 read_next_dir_entry(struct client *c)
808 if ((d = readdir(c->dir)) == NULL) {
810 log_err(c, "readdir: %s", strerror(errno));
813 } while (!strcmp(d->d_name, "."));
815 /* XXX: url escape */
816 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
817 d->d_name, d->d_name);
818 c->len = strlen(c->sbuf);
825 send_directory_listing(int fd, short ev, void *d)
827 struct client *c = d;
832 if (!read_next_dir_entry(c))
837 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
841 case TLS_WANT_POLLOUT:
842 reschedule_read(fd, c, &send_directory_listing);
845 case TLS_WANT_POLLIN:
846 reschedule_write(fd, c, &send_directory_listing);
858 close_conn(fd, ev, d);
861 /* accumulate the meta line from the cgi script. */
863 handle_cgi_reply(int fd, short ev, void *d)
865 struct client *c = d;
871 buf = c->sbuf + c->len;
872 len = sizeof(c->sbuf) - c->len;
874 r = read(c->pfd, buf, len);
875 if (r == 0 || r == -1) {
876 start_reply(c, CGI_ERROR, "CGI error");
882 /* TODO: error if the CGI script don't reply correctly */
883 e = strchr(c->sbuf, '\n');
884 if (e != NULL || c->len == sizeof(c->sbuf)) {
885 log_request(c, c->sbuf, c->len);
888 handle_cgi(fd, ev, c);
892 reschedule_read(fd, c, &handle_cgi_reply);
896 handle_cgi(int fd, short ev, void *d)
898 struct client *c = d;
903 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
907 if (errno == EAGAIN || errno == EWOULDBLOCK) {
908 reschedule_read(c->pfd, c, &handle_cgi);
919 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
923 case TLS_WANT_POLLOUT:
924 reschedule_read(c->fd, c, &handle_cgi);
927 case TLS_WANT_POLLIN:
928 reschedule_write(c->fd, c, &handle_cgi);
940 close_conn(c->fd, ev, d);
944 close_conn(int fd, short ev, void *d)
946 struct client *c = d;
948 switch (tls_close(c->ctx)) {
949 case TLS_WANT_POLLIN:
950 reschedule_read(fd, c, &close_conn);
952 case TLS_WANT_POLLOUT:
953 reschedule_read(fd, c, &close_conn);
962 if (c->buf != MAP_FAILED)
963 munmap(c->buf, c->len);
976 do_accept(int sock, short et, void *d)
979 struct server *s = d;
980 struct sockaddr_storage addr;
981 struct sockaddr *saddr;
988 saddr = (struct sockaddr*)&addr;
990 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
991 if (errno == EWOULDBLOCK || errno == EAGAIN)
993 fatal("accept: %s", strerror(errno));
996 for (i = 0; i < MAX_USERS; ++i) {
999 memset(c, 0, sizeof(*c));
1000 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1001 break; /* goodbye fd! */
1005 c->buf = MAP_FAILED;
1009 reschedule_read(fd, c, &handle_handshake);
1010 connected_clients++;
1019 handle_sighup(int fd, short ev, void *d)
1021 struct server_events *events = d;
1026 event_del(&events->e4);
1027 if (events->has_ipv6)
1028 event_del(&events->e6);
1029 signal_del(&events->sighup);
1033 handle_siginfo(int fd, short ev, void *d)
1039 log_info(NULL, "%d connected clients", connected_clients);
1043 loop(struct tls *ctx, int sock4, int sock6)
1045 struct server_events events;
1046 struct server server;
1052 memset(&events, 0, sizeof(events));
1053 memset(&server, 0, sizeof(server));
1054 for (i = 0; i < MAX_USERS; ++i)
1055 server.clients[i].fd = -1;
1057 event_set(&events.e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1058 event_add(&events.e4, NULL);
1061 events.has_ipv6 = 1;
1062 event_set(&events.e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1063 event_add(&events.e6, NULL);
1066 signal_set(&events.sighup, SIGHUP, &handle_sighup, &events);
1067 signal_add(&events.sighup, NULL);
1070 signal_set(&info, SIGINFO, &handle_siginfo, NULL);
1071 signal_add(&info, NULL);
1073 signal_set(&info, SIGUSR2, &handle_siginfo, NULL);
1074 signal_add(&info, NULL);