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 int apply_block_return(struct client*);
55 static void handle_open_conn(int, short, void*);
56 static void start_reply(struct client*, int, const char*);
57 static void handle_start_reply(int, short, void*);
58 static void start_cgi(const char*, const char*, struct client*);
59 static void send_file(int, short, void*);
60 static void open_dir(struct client*);
61 static void redirect_canonical_dir(struct client*);
62 static void enter_handle_dirlist(int, short, void*);
63 static void handle_dirlist(int, short, void*);
64 static int read_next_dir_entry(struct client*);
65 static void send_directory_listing(int, short, void*);
66 static void handle_cgi_reply(int, short, void*);
67 static void handle_cgi(int, short, void*);
68 static void close_conn(int, short, void*);
69 static void do_accept(int, short, void*);
70 static void handle_sighup(int, short, void*);
73 reschedule_read(int fd, struct client *c, statefn fn)
75 event_once(fd, EV_READ, fn, c, NULL);
79 reschedule_write(int fd, struct client *c, statefn fn)
81 event_once(fd, EV_WRITE, fn, c, NULL);
85 vhost_lang(struct vhost *v, const char *path)
89 if (v == NULL || path == NULL)
92 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
93 if (loc->lang != NULL) {
94 if (!fnmatch(loc->match, path, 0))
99 return v->locations[0].lang;
103 vhost_default_mime(struct vhost *v, const char *path)
105 struct location *loc;
106 const char *default_mime = "application/octet-stream";
108 if (v == NULL || path == NULL)
111 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
112 if (loc->default_mime != NULL) {
113 if (!fnmatch(loc->match, path, 0))
114 return loc->default_mime;
118 if (v->locations[0].default_mime != NULL)
119 return v->locations[0].default_mime;
124 vhost_index(struct vhost *v, const char *path)
126 struct location *loc;
127 const char *index = "index.gmi";
129 if (v == NULL || path == NULL)
132 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
133 if (loc->index != NULL) {
134 if (!fnmatch(loc->match, path, 0))
139 if (v->locations[0].index != NULL)
140 return v->locations[0].index;
145 vhost_auto_index(struct vhost *v, const char *path)
147 struct location *loc;
149 if (v == NULL || path == NULL)
152 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
153 if (loc->auto_index != 0) {
154 if (!fnmatch(loc->match, path, 0))
155 return loc->auto_index == 1;
159 return v->locations[0].auto_index == 1;
163 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
165 struct location *loc;
167 if (v == NULL || path == NULL)
170 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
171 if (loc->block_code != 0) {
172 if (!fnmatch(loc->match, path, 0)) {
173 *code = loc->block_code;
174 *fmt = loc->block_fmt;
180 *code = v->locations[0].block_code;
181 *fmt = v->locations[0].block_fmt;
182 return v->locations[0].block_code != 0;
186 vhost_strip(struct vhost *v, const char *path)
188 struct location *loc;
190 if (v == NULL || path == NULL)
193 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
194 if (loc->strip != 0) {
195 if (!fnmatch(loc->match, path, 0))
200 return v->locations[0].strip;
204 check_path(struct client *c, const char *path, int *fd)
210 assert(path != NULL);
214 else if (*path == '/')
215 /* in send_dir we add an initial / (to be
216 * redirect-friendly), but here we want to skip it */
221 flags = O_RDONLY | O_NOFOLLOW;
223 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
226 if (fstat(*fd, &sb) == -1) {
227 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
231 if (S_ISDIR(sb.st_mode))
232 return FILE_DIRECTORY;
234 if (sb.st_mode & S_IXUSR)
235 return FILE_EXECUTABLE;
241 open_file(struct client *c)
243 switch (check_path(c, c->iri.path, &c->pfd)) {
244 case FILE_EXECUTABLE:
245 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
246 start_cgi(c->iri.path, "", c);
261 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
265 start_reply(c, NOT_FOUND, "not found");
275 load_file(struct client *c)
277 if ((c->len = filesize(c->pfd)) == -1) {
278 log_err(c, "failed to get file size for %s: %s",
279 c->iri.path, strerror(errno));
280 start_reply(c, TEMP_FAILURE, "internal server error");
284 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
285 c->pfd, 0)) == MAP_FAILED) {
286 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
287 start_reply(c, TEMP_FAILURE, "internal server error");
292 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
296 * the inverse of this algorithm, i.e. starting from the start of the
297 * path + strlen(cgi), and checking if each component, should be
298 * faster. But it's tedious to write. This does the opposite: starts
299 * from the end and strip one component at a time, until either an
300 * executable is found or we emptied the path.
303 check_for_cgi(struct client *c)
308 strlcpy(path, c->iri.path, sizeof(path));
309 end = strchr(path, '\0');
312 /* go up one level. UNIX paths are simple and POSIX
313 * dirname, with its ambiguities on if the given path
314 * is changed or not, gives me headaches. */
319 switch (check_path(c, path, &c->pfd)) {
320 case FILE_EXECUTABLE:
321 start_cgi(path, end+1, c);
334 start_reply(c, NOT_FOUND, "not found");
339 mark_nonblock(int fd)
343 if ((flags = fcntl(fd, F_GETFL)) == -1)
344 fatal("fcntl(F_GETFL): %s", strerror(errno));
345 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
346 fatal("fcntl(F_SETFL): %s", strerror(errno));
350 handle_handshake(int fd, short ev, void *d)
352 struct client *c = d;
354 const char *servname;
355 const char *parse_err = "unknown error";
357 switch (tls_handshake(c->ctx)) {
358 case 0: /* success */
359 case -1: /* already handshaked */
361 case TLS_WANT_POLLIN:
362 reschedule_read(fd, c, &handle_handshake);
364 case TLS_WANT_POLLOUT:
365 reschedule_write(fd, c, &handle_handshake);
372 servname = tls_conn_servername(c->ctx);
373 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
374 log_info(c, "puny_decode: %s", parse_err);
378 for (h = hosts; h->domain != NULL; ++h) {
379 if (!fnmatch(h->domain, c->domain, 0))
383 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
384 servname != NULL ? servname : "(null)",
386 h->domain != NULL ? h->domain : "(null)");
388 if (h->domain != NULL) {
390 handle_open_conn(fd, ev, c);
395 if (servname != NULL)
396 strncpy(c->req, servname, sizeof(c->req));
398 strncpy(c->req, "null", sizeof(c->req));
400 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
403 /* 1 if a matching `block return' (and apply it), 0 otherwise */
405 apply_block_return(struct client *c)
407 char *t, *path, buf[32];
412 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
415 strip = vhost_strip(c->host, c->iri.path);
418 if ((t = strchr(path, '/')) == NULL) {
419 path = strchr(path, '\0');
426 memset(buf, 0, sizeof(buf));
427 for (i = 0; *fmt; ++fmt) {
428 if (i == sizeof(buf)-1 || *fmt == '%') {
429 strlcat(c->sbuf, buf, sizeof(c->sbuf));
430 memset(buf, 0, sizeof(buf));
441 strlcat(c->sbuf, "%", sizeof(c->sbuf));
444 strlcat(c->sbuf, path, sizeof(c->sbuf));
447 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
450 snprintf(buf, sizeof(buf), "%d", conf.port);
451 strlcat(c->sbuf, buf, sizeof(c->sbuf));
452 memset(buf, 0, sizeof(buf));
455 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
458 fatal("%s: unknown fmt specifier %c",
464 strlcat(c->sbuf, buf, sizeof(c->sbuf));
466 start_reply(c, code, c->sbuf);
471 handle_open_conn(int fd, short ev, void *d)
473 struct client *c = d;
474 const char *parse_err = "invalid request";
475 char decoded[DOMAIN_NAME_LEN];
477 bzero(c->req, sizeof(c->req));
478 bzero(&c->iri, sizeof(c->iri));
480 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
482 log_err(c, "tls_read: %s", tls_error(c->ctx));
483 close_conn(fd, ev, c);
486 case TLS_WANT_POLLIN:
487 reschedule_read(fd, c, &handle_open_conn);
490 case TLS_WANT_POLLOUT:
491 reschedule_write(fd, c, &handle_open_conn);
495 if (!trim_req_iri(c->req, &parse_err)
496 || !parse_iri(c->req, &c->iri, &parse_err)
497 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
498 log_info(c, "iri parse error: %s", parse_err);
499 start_reply(c, BAD_REQUEST, "invalid request");
503 if (c->iri.port_no != conf.port
504 || strcmp(c->iri.schema, "gemini")
505 || strcmp(decoded, c->domain)) {
506 start_reply(c, PROXY_REFUSED, "won't proxy request");
510 if (apply_block_return(c))
513 if (c->host->entrypoint != NULL) {
514 start_cgi(c->host->entrypoint, c->iri.path, c);
522 start_reply(struct client *c, int code, const char *meta)
526 handle_start_reply(c->fd, 0, c);
530 handle_start_reply(int fd, short ev, void *d)
532 struct client *c = d;
533 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
537 lang = vhost_lang(c->host, c->iri.path);
539 snprintf(buf, sizeof(buf), "%d ", c->code);
540 strlcat(buf, c->meta, sizeof(buf));
541 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
542 strlcat(buf, "; lang=", sizeof(buf));
543 strlcat(buf, lang, sizeof(buf));
546 len = strlcat(buf, "\r\n", sizeof(buf));
547 assert(len < sizeof(buf));
549 switch (tls_write(c->ctx, buf, len)) {
551 close_conn(fd, ev, c);
553 case TLS_WANT_POLLIN:
554 reschedule_read(fd, c, &handle_start_reply);
556 case TLS_WANT_POLLOUT:
557 reschedule_write(fd, c, &handle_start_reply);
561 log_request(c, buf, sizeof(buf));
563 if (c->code != SUCCESS)
564 close_conn(fd, ev, c);
570 start_cgi(const char *spath, const char *relpath, struct client *c)
572 char addr[NI_MAXHOST];
575 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
582 if (!send_iri(exfd, &c->iri)
583 || !send_string(exfd, spath)
584 || !send_string(exfd, relpath)
585 || !send_string(exfd, addr)
586 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
587 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
588 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
589 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
590 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
591 || !send_vhost(exfd, c->host))
595 if ((c->pfd = recv_fd(exfd)) == -1) {
596 start_reply(c, TEMP_FAILURE, "internal server error");
600 reschedule_read(c->pfd, c, &handle_cgi_reply);
604 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
605 fatal("cannot talk to the executor process");
609 send_file(int fd, short ev, void *d)
611 struct client *c = d;
614 len = (c->buf + c->len) - c->i;
617 switch (ret = tls_write(c->ctx, c->i, len)) {
619 log_err(c, "tls_write: %s", tls_error(c->ctx));
620 close_conn(fd, ev, c);
623 case TLS_WANT_POLLIN:
624 reschedule_read(fd, c, &send_file);
627 case TLS_WANT_POLLOUT:
628 reschedule_write(fd, c, &send_file);
638 close_conn(fd, ev, c);
642 open_dir(struct client *c)
648 len = strlen(c->iri.path);
649 if (len > 0 && !ends_with(c->iri.path, "/")) {
650 redirect_canonical_dir(c);
654 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
655 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
656 if (!ends_with(c->sbuf, "/"))
657 strlcat(c->sbuf, "/", sizeof(c->sbuf));
658 before_file = strchr(c->sbuf, '\0');
659 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
661 if (len >= sizeof(c->sbuf)) {
662 start_reply(c, TEMP_FAILURE, "internal server error");
666 c->iri.path = c->sbuf;
668 /* close later unless we have to generate the dir listing */
672 switch (check_path(c, c->iri.path, &c->pfd)) {
673 case FILE_EXECUTABLE:
674 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
675 start_cgi(c->iri.path, "", c);
686 start_reply(c, TEMP_REDIRECT, c->sbuf);
692 if (!vhost_auto_index(c->host, c->iri.path)) {
693 start_reply(c, NOT_FOUND, "not found");
698 c->next = enter_handle_dirlist;
700 if ((c->dir = fdopendir(c->pfd)) == NULL) {
701 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
702 c->pfd, c->host->domain, c->iri.path, strerror(errno));
703 start_reply(c, TEMP_FAILURE, "internal server error");
708 start_reply(c, SUCCESS, "text/gemini");
720 redirect_canonical_dir(struct client *c)
724 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
725 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
726 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
728 if (len >= sizeof(c->sbuf)) {
729 start_reply(c, TEMP_FAILURE, "internal server error");
733 start_reply(c, TEMP_REDIRECT, c->sbuf);
737 enter_handle_dirlist(int fd, short ev, void *d)
739 struct client *c = d;
743 strlcpy(b, c->iri.path, sizeof(b));
744 l = snprintf(c->sbuf, sizeof(c->sbuf),
745 "# Index of %s\n\n", b);
746 if (l >= sizeof(c->sbuf)) {
747 /* this is impossible, given that we have enough space
748 * in c->sbuf to hold the ancilliary string plus the
749 * full path; but it wouldn't read nice without some
750 * error checking, and I'd like to avoid a strlen. */
751 close_conn(fd, ev, c);
756 handle_dirlist(fd, ev, c);
760 handle_dirlist(int fd, short ev, void *d)
762 struct client *c = d;
766 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
768 close_conn(fd, ev, c);
770 case TLS_WANT_POLLOUT:
771 reschedule_read(fd, c, &handle_dirlist);
773 case TLS_WANT_POLLIN:
774 reschedule_write(fd, c, &handle_dirlist);
782 send_directory_listing(fd, ev, c);
786 read_next_dir_entry(struct client *c)
792 if ((d = readdir(c->dir)) == NULL) {
794 log_err(c, "readdir: %s", strerror(errno));
797 } while (!strcmp(d->d_name, "."));
799 /* XXX: url escape */
800 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
801 d->d_name, d->d_name);
802 c->len = strlen(c->sbuf);
809 send_directory_listing(int fd, short ev, void *d)
811 struct client *c = d;
816 if (!read_next_dir_entry(c))
821 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
825 case TLS_WANT_POLLOUT:
826 reschedule_read(fd, c, &send_directory_listing);
829 case TLS_WANT_POLLIN:
830 reschedule_write(fd, c, &send_directory_listing);
842 close_conn(fd, ev, d);
845 /* accumulate the meta line from the cgi script. */
847 handle_cgi_reply(int fd, short ev, void *d)
849 struct client *c = d;
855 buf = c->sbuf + c->len;
856 len = sizeof(c->sbuf) - c->len;
858 r = read(c->pfd, buf, len);
859 if (r == 0 || r == -1) {
860 start_reply(c, CGI_ERROR, "CGI error");
866 /* TODO: error if the CGI script don't reply correctly */
867 e = strchr(c->sbuf, '\n');
868 if (e != NULL || c->len == sizeof(c->sbuf)) {
869 log_request(c, c->sbuf, c->len);
872 handle_cgi(fd, ev, c);
876 reschedule_read(fd, c, &handle_cgi_reply);
880 handle_cgi(int fd, short ev, void *d)
882 struct client *c = d;
887 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
891 if (errno == EAGAIN || errno == EWOULDBLOCK) {
892 reschedule_read(c->pfd, c, &handle_cgi);
903 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
907 case TLS_WANT_POLLOUT:
908 reschedule_read(c->fd, c, &handle_cgi);
911 case TLS_WANT_POLLIN:
912 reschedule_write(c->fd, c, &handle_cgi);
924 close_conn(c->fd, ev, d);
928 close_conn(int fd, short ev, void *d)
930 struct client *c = d;
932 switch (tls_close(c->ctx)) {
933 case TLS_WANT_POLLIN:
934 reschedule_read(fd, c, &close_conn);
936 case TLS_WANT_POLLOUT:
937 reschedule_read(fd, c, &close_conn);
946 if (c->buf != MAP_FAILED)
947 munmap(c->buf, c->len);
960 do_accept(int sock, short et, void *d)
963 struct server *s = d;
964 struct sockaddr_storage addr;
965 struct sockaddr *saddr;
972 saddr = (struct sockaddr*)&addr;
974 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
975 if (errno == EWOULDBLOCK || errno == EAGAIN)
977 fatal("accept: %s", strerror(errno));
980 for (i = 0; i < MAX_USERS; ++i) {
983 memset(c, 0, sizeof(*c));
984 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
985 break; /* goodbye fd! */
993 reschedule_read(fd, c, &handle_handshake);
1003 handle_sighup(int fd, short ev, void *d)
1005 struct server_events *events = d;
1010 event_del(&events->e4);
1011 if (events->has_ipv6)
1012 event_del(&events->e6);
1013 signal_del(&events->sighup);
1017 handle_siginfo(int fd, short ev, void *d)
1023 log_info(NULL, "%d connected clients", connected_clients);
1027 loop(struct tls *ctx, int sock4, int sock6)
1029 struct server_events events;
1030 struct server server;
1036 memset(&events, 0, sizeof(events));
1037 memset(&server, 0, sizeof(server));
1038 for (i = 0; i < MAX_USERS; ++i)
1039 server.clients[i].fd = -1;
1041 event_set(&events.e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1042 event_add(&events.e4, NULL);
1045 events.has_ipv6 = 1;
1046 event_set(&events.e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1047 event_add(&events.e6, NULL);
1050 signal_set(&events.sighup, SIGHUP, &handle_sighup, &events);
1051 signal_add(&events.sighup, NULL);
1054 signal_set(&info, SIGINFO, &handle_siginfo, NULL);
1055 signal_add(&info, NULL);
1057 signal_set(&info, SIGUSR2, &handle_siginfo, NULL);
1058 signal_add(&info, NULL);