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.
31 int connected_clients;
34 vhost_lang(struct vhost *v, const char *path)
38 if (v == NULL || path == NULL)
41 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
42 if (!fnmatch(loc->match, path, 0)) {
43 if (loc->lang != NULL)
48 return v->locations[0].lang;
52 vhost_default_mime(struct vhost *v, const char *path)
55 const char *default_mime = "application/octet-stream";
57 if (v == NULL || path == NULL)
60 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
61 if (!fnmatch(loc->match, path, 0)) {
62 if (loc->default_mime != NULL)
63 return loc->default_mime;
67 if (v->locations[0].default_mime != NULL)
68 return v->locations[0].default_mime;
73 vhost_index(struct vhost *v, const char *path)
76 const char *index = "index.gmi";
78 if (v == NULL || path == NULL)
81 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
82 if (!fnmatch(loc->match, path, 0)) {
83 if (loc->index != NULL)
88 if (v->locations[0].index != NULL)
89 return v->locations[0].index;
94 vhost_auto_index(struct vhost *v, const char *path)
98 if (v == NULL || path == NULL)
101 for (loc = v->locations; loc->match != NULL; ++loc) {
102 if (!fnmatch(loc->match, path, 0)) {
103 if (loc->auto_index != 0)
104 return loc->auto_index == 1;
108 return v->locations[0].auto_index == 1;
112 check_path(struct client *c, const char *path, int *fd)
118 assert(path != NULL);
122 else if (*path == '/')
123 /* in send_dir we add an initial / (to be
124 * redirect-friendly), but here we want to skip it */
129 flags = O_RDONLY | O_NOFOLLOW;
131 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
134 if (fstat(*fd, &sb) == -1) {
135 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
139 if (S_ISDIR(sb.st_mode))
140 return FILE_DIRECTORY;
142 if (sb.st_mode & S_IXUSR)
143 return FILE_EXECUTABLE;
149 open_file(struct pollfd *fds, struct client *c)
151 switch (check_path(c, c->iri.path, &c->fd)) {
152 case FILE_EXECUTABLE:
153 if (starts_with(c->iri.path, c->host->cgi)) {
154 start_cgi(c->iri.path, "", fds, c);
169 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
170 check_for_cgi(fds, c);
173 start_reply(fds, c, NOT_FOUND, "not found");
183 load_file(struct pollfd *fds, struct client *c)
185 if ((c->len = filesize(c->fd)) == -1) {
186 LOGE(c, "failed to get file size for %s", c->iri.path);
187 start_reply(fds, c, TEMP_FAILURE, "internal server error");
191 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
192 c->fd, 0)) == MAP_FAILED) {
193 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
194 start_reply(fds, c, TEMP_FAILURE, "internal server error");
199 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
203 * the inverse of this algorithm, i.e. starting from the start of the
204 * path + strlen(cgi), and checking if each component, should be
205 * faster. But it's tedious to write. This does the opposite: starts
206 * from the end and strip one component at a time, until either an
207 * executable is found or we emptied the path.
210 check_for_cgi(struct pollfd *fds, struct client *c)
215 strlcpy(path, c->iri.path, sizeof(path));
216 end = strchr(path, '\0');
218 /* NB: assume CGI is enabled and path matches cgi */
221 /* go up one level. UNIX paths are simple and POSIX
222 * dirname, with its ambiguities on if the given path
223 * is changed or not, gives me headaches. */
228 switch (check_path(c, path, &c->fd)) {
229 case FILE_EXECUTABLE:
230 start_cgi(path, end+1, fds, c);
243 start_reply(fds, c, NOT_FOUND, "not found");
248 mark_nonblock(int fd)
252 if ((flags = fcntl(fd, F_GETFL)) == -1)
253 fatal("fcntl(F_GETFL): %s", strerror(errno));
254 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
255 fatal("fcntl(F_SETFL): %s", strerror(errno));
259 handle_handshake(struct pollfd *fds, struct client *c)
262 const char *servname;
263 const char *parse_err = "unknown error";
265 switch (tls_handshake(c->ctx)) {
266 case 0: /* success */
267 case -1: /* already handshaked */
269 case TLS_WANT_POLLIN:
270 fds->events = POLLIN;
272 case TLS_WANT_POLLOUT:
273 fds->events = POLLOUT;
280 servname = tls_conn_servername(c->ctx);
281 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
282 LOGI(c, "%s", parse_err);
286 for (h = hosts; h->domain != NULL; ++h) {
287 if (!fnmatch(h->domain, c->domain, 0))
291 /* LOGD(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"", */
292 /* servname != NULL ? servname : "(null)", */
294 /* h->domain != NULL ? h->domain : "(null)"); */
296 if (h->domain != NULL) {
297 c->state = handle_open_conn;
299 handle_open_conn(fds, c);
304 if (servname != NULL)
305 strncpy(c->req, servname, sizeof(c->req));
307 strncpy(c->req, "null", sizeof(c->req));
309 start_reply(fds, c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
313 handle_open_conn(struct pollfd *fds, struct client *c)
315 const char *parse_err = "invalid request";
316 char decoded[DOMAIN_NAME_LEN];
318 bzero(c->req, sizeof(c->req));
319 bzero(&c->iri, sizeof(c->iri));
321 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
323 LOGE(c, "tls_read: %s", tls_error(c->ctx));
327 case TLS_WANT_POLLIN:
328 fds->events = POLLIN;
331 case TLS_WANT_POLLOUT:
332 fds->events = POLLOUT;
336 if (!trim_req_iri(c->req, &parse_err)
337 || !parse_iri(c->req, &c->iri, &parse_err)
338 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
339 LOGI(c, "iri parse error: %s", parse_err);
340 start_reply(fds, c, BAD_REQUEST, "invalid request");
344 if (c->iri.port_no != conf.port
345 || strcmp(c->iri.schema, "gemini")
346 || strcmp(decoded, c->domain)) {
347 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
355 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
359 c->state = handle_start_reply;
364 handle_start_reply(struct pollfd *pfd, struct client *c)
366 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
370 lang = vhost_lang(c->host, c->iri.path);
372 snprintf(buf, sizeof(buf), "%d ", c->code);
373 strlcat(buf, c->meta, sizeof(buf));
374 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
375 strlcat(buf, "; lang=", sizeof(buf));
376 strlcat(buf, lang, sizeof(buf));
379 len = strlcat(buf, "\r\n", sizeof(buf));
380 assert(len < sizeof(buf));
382 switch (tls_write(c->ctx, buf, len)) {
386 case TLS_WANT_POLLIN:
387 pfd->events = POLLIN;
389 case TLS_WANT_POLLOUT:
390 pfd->events = POLLOUT;
394 log_request(c, buf, sizeof(buf));
396 /* we don't need a body */
397 if (c->code != SUCCESS) {
402 /* advance the state machine */
408 start_cgi(const char *spath, const char *relpath,
409 struct pollfd *fds, struct client *c)
411 char addr[NI_MAXHOST];
412 const char *ruser, *cissuer, *chash;
415 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
422 if (tls_peer_cert_provided(c->ctx)) {
423 ruser = tls_peer_cert_subject(c->ctx);
424 cissuer = tls_peer_cert_issuer(c->ctx);
425 chash = tls_peer_cert_hash(c->ctx);
432 if (!send_iri(exfd, &c->iri)
433 || !send_string(exfd, spath)
434 || !send_string(exfd, relpath)
435 || !send_string(exfd, addr)
436 || !send_string(exfd, ruser)
437 || !send_string(exfd, cissuer)
438 || !send_string(exfd, chash)
439 || !send_vhost(exfd, c->host))
443 if ((c->fd = recv_fd(exfd)) == -1) {
444 start_reply(fds, c, TEMP_FAILURE, "internal server error");
447 c->state = handle_cgi;
448 cgi_poll_on_child(fds, c);
450 /* handle_cgi(fds, c); */
454 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
455 fatal("cannot talk to the executor process");
459 send_file(struct pollfd *fds, struct client *c)
463 len = (c->buf + c->len) - c->i;
466 switch (ret = tls_write(c->ctx, c->i, len)) {
468 LOGE(c, "tls_write: %s", tls_error(c->ctx));
472 case TLS_WANT_POLLIN:
473 fds->events = POLLIN;
476 case TLS_WANT_POLLOUT:
477 fds->events = POLLOUT;
491 open_dir(struct pollfd *fds, struct client *c)
497 len = strlen(c->iri.path);
498 if (len > 0 && !ends_with(c->iri.path, "/")) {
499 redirect_canonical_dir(fds, c);
503 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
504 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
505 if (!ends_with(c->sbuf, "/"))
506 strlcat(c->sbuf, "/", sizeof(c->sbuf));
507 before_file = strchr(c->sbuf, '\0');
508 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
510 if (len >= sizeof(c->sbuf)) {
511 start_reply(fds, c, TEMP_FAILURE, "internal server error");
515 c->iri.path = c->sbuf;
517 /* close later unless we have to generate the dir listing */
521 switch (check_path(c, c->iri.path, &c->fd)) {
522 case FILE_EXECUTABLE:
523 if (starts_with(c->iri.path, c->host->cgi)) {
524 start_cgi(c->iri.path, "", fds, c);
535 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
541 if (!vhost_auto_index(c->host, c->iri.path)) {
542 start_reply(fds, c, NOT_FOUND, "not found");
547 c->next = send_directory_listing;
549 if ((c->dir = fdopendir(c->fd)) == NULL) {
550 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
551 c->fd, c->host->domain, c->iri.path, strerror(errno));
552 start_reply(fds, c, TEMP_FAILURE, "internal server error");
557 start_reply(fds, c, SUCCESS, "text/gemini");
569 redirect_canonical_dir(struct pollfd *fds, struct client *c)
573 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
574 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
575 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
577 if (len >= sizeof(c->sbuf)) {
578 start_reply(fds, c, TEMP_FAILURE, "internal server error");
582 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
586 read_next_dir_entry(struct client *c)
592 if ((d = readdir(c->dir)) == NULL) {
594 LOGE(c, "readdir: %s", strerror(errno));
597 } while (!strcmp(d->d_name, "."));
599 /* XXX: url escape */
600 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
601 d->d_name, d->d_name);
602 c->len = strlen(c->sbuf);
609 send_directory_listing(struct pollfd *fds, struct client *c)
615 if (!read_next_dir_entry(c))
620 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
624 case TLS_WANT_POLLOUT:
625 fds->events = POLLOUT;
628 case TLS_WANT_POLLIN:
629 fds->events = POLLIN;
645 cgi_poll_on_child(struct pollfd *fds, struct client *c)
649 if (c->waiting_on_child)
651 c->waiting_on_child = 1;
653 fds->events = POLLIN;
661 cgi_poll_on_client(struct pollfd *fds, struct client *c)
665 if (!c->waiting_on_child)
667 c->waiting_on_child = 0;
674 /* handle the read from the child process. Return like read(2) */
676 read_from_cgi(struct client *c)
682 /* if we haven't read a whole response line, we want to
683 * continue reading. */
686 buf = c->sbuf + c->len;
687 len = sizeof(c->sbuf) - c->len;
690 len = sizeof(c->sbuf);
693 r = read(c->fd, buf, len);
694 if (r == 0 || r == -1)
703 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
705 log_request(c, c->sbuf, c->len);
712 handle_cgi(struct pollfd *fds, struct client *c)
716 /* ensure c->fd is the child and fds->fd the client */
717 cgi_poll_on_client(fds, c);
720 if (c->code == -1 || c->len == 0) {
721 switch (r = read_from_cgi(c)) {
726 if (errno == EAGAIN || errno == EWOULDBLOCK) {
727 cgi_poll_on_child(fds, c);
735 cgi_poll_on_child(fds, c);
740 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
744 case TLS_WANT_POLLOUT:
745 fds->events = POLLOUT;
748 case TLS_WANT_POLLIN:
749 fds->events = POLLIN;
765 close_conn(struct pollfd *pfd, struct client *c)
767 c->state = close_conn;
769 switch (tls_close(c->ctx)) {
770 case TLS_WANT_POLLIN:
771 pfd->events = POLLIN;
773 case TLS_WANT_POLLOUT:
774 pfd->events = POLLOUT;
783 if (c->buf != MAP_FAILED)
784 munmap(c->buf, c->len);
797 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
800 struct sockaddr_storage addr;
804 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
805 if (errno == EWOULDBLOCK)
807 fatal("accept: %s", strerror(errno));
812 for (i = 0; i < MAX_USERS; ++i) {
813 if (fds[i].fd == -1) {
814 bzero(&clients[i], sizeof(struct client));
815 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
816 break; /* goodbye fd! */
819 fds[i].events = POLLIN;
821 clients[i].state = handle_handshake;
822 clients[i].next = send_file;
824 clients[i].waiting_on_child = 0;
825 clients[i].buf = MAP_FAILED;
826 clients[i].dir = NULL;
827 clients[i].addr = addr;
838 loop(struct tls *ctx, int sock4, int sock6)
841 struct client clients[MAX_USERS];
842 struct pollfd fds[MAX_USERS];
844 connected_clients = 0;
846 for (i = 0; i < MAX_USERS; ++i) {
848 fds[i].events = POLLIN;
849 bzero(&clients[i], sizeof(struct client));
856 if (poll(fds, MAX_USERS, INFTIM) == -1) {
857 if (errno == EINTR) {
858 fprintf(stderr, "connected clients: %d\n",
862 fatal("poll: %s", strerror(errno));
865 for (i = 0; i < MAX_USERS; i++) {
866 if (fds[i].revents == 0)
869 if (fds[i].revents & (POLLERR|POLLNVAL))
870 fatal("bad fd %d: %s", fds[i].fd,
873 if (fds[i].revents & POLLHUP) {
874 /* fds[i] may be the fd of the stdin
875 * of a cgi script that has exited. */
876 if (!clients[i].waiting_on_child) {
877 close_conn(&fds[i], &clients[i]);
882 if (fds[i].fd == sock4)
883 do_accept(sock4, ctx, fds, clients);
884 else if (fds[i].fd == sock6)
885 do_accept(sock6, ctx, fds, clients);
887 clients[i].state(&fds[i], &clients[i]);