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.
30 int connected_clients;
33 vhost_lang(struct vhost *v, const char *path)
36 const char *lang = NULL;
41 for (loc = v->locations; loc->match != NULL; ++loc) {
42 if (!fnmatch(loc->match, path, 0)) {
43 if (loc->lang != NULL)
52 vhost_default_mime(struct vhost *v, const char *path)
55 const char *default_mime = "application/octet-stream";
57 for (loc = v->locations; loc->match != NULL; ++loc) {
58 if (!fnmatch(loc->match, path, 0)) {
59 if (loc->default_mime != NULL)
60 default_mime = loc->default_mime;
68 vhost_index(struct vhost *v, const char *path)
71 const char *index = "index.gmi";
73 for (loc = v->locations; loc->match != NULL; ++loc) {
74 if (!fnmatch(loc->match, path, 0)) {
75 if (loc->index != NULL)
84 vhost_auto_index(struct vhost *v, const char *path)
89 for (loc = v->locations; loc->match != NULL; ++loc) {
90 if (!fnmatch(loc->match, path, 0)) {
92 auto_index = loc->auto_index;
96 return auto_index == 1;
100 check_path(struct client *c, const char *path, int *fd)
106 assert(path != NULL);
110 else if (*path == '/')
111 /* in send_dir we add an initial / (to be
112 * redirect-friendly), but here we want to skip it */
117 flags = O_RDONLY | O_NOFOLLOW;
119 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
122 if (fstat(*fd, &sb) == -1) {
123 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
127 if (S_ISDIR(sb.st_mode))
128 return FILE_DIRECTORY;
130 if (sb.st_mode & S_IXUSR)
131 return FILE_EXECUTABLE;
137 open_file(struct pollfd *fds, struct client *c)
139 switch (check_path(c, c->iri.path, &c->fd)) {
140 case FILE_EXECUTABLE:
141 if (starts_with(c->iri.path, c->host->cgi)) {
142 start_cgi(c->iri.path, "", c->iri.query, fds, c);
157 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
158 check_for_cgi(c->iri.path, c->iri.query, fds, c);
161 start_reply(fds, c, NOT_FOUND, "not found");
171 load_file(struct pollfd *fds, struct client *c)
173 if ((c->len = filesize(c->fd)) == -1) {
174 LOGE(c, "failed to get file size for %s", c->iri.path);
175 start_reply(fds, c, TEMP_FAILURE, "internal server error");
179 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
180 c->fd, 0)) == MAP_FAILED) {
181 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
182 start_reply(fds, c, TEMP_FAILURE, "internal server error");
186 c->next = S_SENDING_FILE;
187 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
191 * the inverse of this algorithm, i.e. starting from the start of the
192 * path + strlen(cgi), and checking if each component, should be
193 * faster. But it's tedious to write. This does the opposite: starts
194 * from the end and strip one component at a time, until either an
195 * executable is found or we emptied the path.
198 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
201 end = strchr(path, '\0');
203 /* NB: assume CGI is enabled and path matches cgi */
206 /* go up one level. UNIX paths are simple and POSIX
207 * dirname, with its ambiguities on if the given path
208 * is changed or not, gives me headaches. */
213 switch (check_path(c, path, &c->fd)) {
214 case FILE_EXECUTABLE:
215 start_cgi(path, end+1, query, fds,c);
228 start_reply(fds, c, NOT_FOUND, "not found");
233 mark_nonblock(int fd)
237 if ((flags = fcntl(fd, F_GETFL)) == -1)
238 fatal("fcntl(F_GETFL): %s", strerror(errno));
239 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
240 fatal("fcntl(F_SETFL): %s", strerror(errno));
244 handle_handshake(struct pollfd *fds, struct client *c)
247 const char *servname;
249 switch (tls_handshake(c->ctx)) {
250 case 0: /* success */
251 case -1: /* already handshaked */
253 case TLS_WANT_POLLIN:
254 fds->events = POLLIN;
256 case TLS_WANT_POLLOUT:
257 fds->events = POLLOUT;
264 servname = tls_conn_servername(c->ctx);
265 puny_decode(servname, c->domain, sizeof(c->domain));
267 for (h = hosts; h->domain != NULL; ++h) {
268 if (!fnmatch(h->domain, c->domain, 0))
272 if (h->domain != NULL) {
275 handle_open_conn(fds, c);
279 if (servname != NULL)
280 strncpy(c->req, servname, sizeof(c->req));
282 strncpy(c->req, "null", sizeof(c->req));
284 start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
288 handle_open_conn(struct pollfd *fds, struct client *c)
290 const char *parse_err = "invalid request";
291 char decoded[DOMAIN_NAME_LEN];
293 bzero(c->req, sizeof(c->req));
294 bzero(&c->iri, sizeof(c->iri));
296 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
298 LOGE(c, "tls_read: %s", tls_error(c->ctx));
302 case TLS_WANT_POLLIN:
303 fds->events = POLLIN;
306 case TLS_WANT_POLLOUT:
307 fds->events = POLLOUT;
311 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
312 start_reply(fds, c, BAD_REQUEST, parse_err);
316 puny_decode(c->iri.host, decoded, sizeof(decoded));
318 if (c->iri.port_no != conf.port
319 || strcmp(c->iri.schema, "gemini")
320 || strcmp(decoded, c->domain)) {
321 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
329 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
331 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
337 c->state = S_INITIALIZING;
339 lang = vhost_lang(c->host, c->iri.path);
341 snprintf(buf, sizeof(buf), "%d ", code);
342 strlcat(buf, meta, sizeof(buf));
343 if (!strcmp(meta, "text/gemini") && lang != NULL) {
344 strlcat(buf, "; lang=", sizeof(buf));
345 strlcat(buf, lang, sizeof(buf));
348 len = strlcat(buf, "\r\n", sizeof(buf));
349 assert(len < sizeof(buf));
351 switch (tls_write(c->ctx, buf, len)) {
355 case TLS_WANT_POLLIN:
356 pfd->events = POLLIN;
358 case TLS_WANT_POLLOUT:
359 pfd->events = POLLOUT;
363 log_request(c, buf, sizeof(buf));
365 /* we don't need a body */
366 if (c->code != SUCCESS) {
371 /* advance the state machine */
377 start_cgi(const char *spath, const char *relpath, const char *query,
378 struct pollfd *fds, struct client *c)
380 char addr[NI_MAXHOST];
381 const char *ruser, *cissuer, *chash;
384 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
391 if (tls_peer_cert_provided(c->ctx)) {
392 ruser = tls_peer_cert_subject(c->ctx);
393 cissuer = tls_peer_cert_issuer(c->ctx);
394 chash = tls_peer_cert_hash(c->ctx);
401 if (!send_string(exfd, spath)
402 || !send_string(exfd, relpath)
403 || !send_string(exfd, query)
404 || !send_string(exfd, addr)
405 || !send_string(exfd, ruser)
406 || !send_string(exfd, cissuer)
407 || !send_string(exfd, chash)
408 || !send_vhost(exfd, c->host))
412 if ((c->fd = recv_fd(exfd)) == -1) {
413 start_reply(fds, c, TEMP_FAILURE, "internal server error");
416 c->state = S_SENDING_CGI;
417 cgi_poll_on_child(fds, c);
419 /* handle_cgi(fds, c); */
423 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
424 fatal("cannot talk to the executor process");
428 send_file(struct pollfd *fds, struct client *c)
432 /* ensure the correct state */
433 c->state = S_SENDING_FILE;
435 len = (c->buf + c->len) - c->i;
438 switch (ret = tls_write(c->ctx, c->i, len)) {
440 LOGE(c, "tls_write: %s", tls_error(c->ctx));
444 case TLS_WANT_POLLIN:
445 fds->events = POLLIN;
448 case TLS_WANT_POLLOUT:
449 fds->events = POLLOUT;
463 open_dir(struct pollfd *fds, struct client *c)
469 len = strlen(c->iri.path);
470 if (len > 0 && !ends_with(c->iri.path, "/")) {
471 redirect_canonical_dir(fds, c);
475 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
476 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
477 if (!ends_with(c->sbuf, "/"))
478 strlcat(c->sbuf, "/", sizeof(c->sbuf));
479 before_file = strchr(c->sbuf, '\0');
480 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
482 if (len >= sizeof(c->sbuf)) {
483 start_reply(fds, c, TEMP_FAILURE, "internal server error");
487 c->iri.path = c->sbuf;
489 /* close later unless we have to generate the dir listing */
493 switch (check_path(c, c->iri.path, &c->fd)) {
494 case FILE_EXECUTABLE:
495 if (starts_with(c->iri.path, c->host->cgi)) {
496 start_cgi(c->iri.path, "", c->iri.query, fds, c);
507 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
513 if (!vhost_auto_index(c->host, c->iri.path)) {
514 start_reply(fds, c, NOT_FOUND, "not found");
519 c->next = S_SENDING_DIR;
521 if ((c->dir = fdopendir(c->fd)) == NULL) {
522 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
523 c->fd, c->host->domain, c->iri.path, strerror(errno));
524 start_reply(fds, c, TEMP_FAILURE, "internal server error");
529 start_reply(fds, c, SUCCESS, "text/gemini");
541 redirect_canonical_dir(struct pollfd *fds, struct client *c)
545 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
546 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
547 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
549 if (len >= sizeof(c->sbuf)) {
550 start_reply(fds, c, TEMP_FAILURE, "internal server error");
554 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
558 read_next_dir_entry(struct client *c)
564 if ((d = readdir(c->dir)) == NULL) {
566 LOGE(c, "readdir: %s", strerror(errno));
569 } while (!strcmp(d->d_name, "."));
571 /* XXX: url escape */
572 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
573 d->d_name, d->d_name);
574 c->len = strlen(c->sbuf);
581 send_directory_listing(struct pollfd *fds, struct client *c)
587 if (!read_next_dir_entry(c))
592 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
596 case TLS_WANT_POLLOUT:
597 fds->events = POLLOUT;
600 case TLS_WANT_POLLIN:
601 fds->events = POLLIN;
617 cgi_poll_on_child(struct pollfd *fds, struct client *c)
621 if (c->waiting_on_child)
623 c->waiting_on_child = 1;
625 fds->events = POLLIN;
633 cgi_poll_on_client(struct pollfd *fds, struct client *c)
637 if (!c->waiting_on_child)
639 c->waiting_on_child = 0;
646 /* handle the read from the child process. Return like read(2) */
648 read_from_cgi(struct client *c)
654 /* if we haven't read a whole response line, we want to
655 * continue reading. */
658 buf = c->sbuf + c->len;
659 len = sizeof(c->sbuf) - c->len;
662 len = sizeof(c->sbuf);
665 r = read(c->fd, buf, len);
666 if (r == 0 || r == -1)
675 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
677 log_request(c, c->sbuf, c->len);
684 handle_cgi(struct pollfd *fds, struct client *c)
688 /* ensure c->fd is the child and fds->fd the client */
689 cgi_poll_on_client(fds, c);
692 if (c->code == -1 || c->len == 0) {
693 switch (r = read_from_cgi(c)) {
698 if (errno == EAGAIN || errno == EWOULDBLOCK) {
699 cgi_poll_on_child(fds, c);
707 cgi_poll_on_child(fds, c);
712 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
716 case TLS_WANT_POLLOUT:
717 fds->events = POLLOUT;
720 case TLS_WANT_POLLIN:
721 fds->events = POLLIN;
737 close_conn(struct pollfd *pfd, struct client *c)
739 c->state = S_CLOSING;
741 switch (tls_close(c->ctx)) {
742 case TLS_WANT_POLLIN:
743 pfd->events = POLLIN;
745 case TLS_WANT_POLLOUT:
746 pfd->events = POLLOUT;
755 if (c->buf != MAP_FAILED)
756 munmap(c->buf, c->len);
769 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
772 struct sockaddr_storage addr;
776 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
777 if (errno == EWOULDBLOCK)
779 fatal("accept: %s", strerror(errno));
784 for (i = 0; i < MAX_USERS; ++i) {
785 if (fds[i].fd == -1) {
786 bzero(&clients[i], sizeof(struct client));
787 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
788 break; /* goodbye fd! */
791 fds[i].events = POLLIN;
793 clients[i].state = S_HANDSHAKE;
794 clients[i].next = S_SENDING_FILE;
796 clients[i].waiting_on_child = 0;
797 clients[i].buf = MAP_FAILED;
798 clients[i].dir = NULL;
799 clients[i].addr = addr;
810 handle(struct pollfd *fds, struct client *client)
812 switch (client->state) {
814 handle_handshake(fds, client);
818 handle_open_conn(fds, client);
822 start_reply(fds, client, client->code, client->meta);
826 send_file(fds, client);
830 send_directory_listing(fds, client);
834 handle_cgi(fds, client);
838 close_conn(fds, client);
848 loop(struct tls *ctx, int sock4, int sock6)
851 struct client clients[MAX_USERS];
852 struct pollfd fds[MAX_USERS];
854 connected_clients = 0;
856 for (i = 0; i < MAX_USERS; ++i) {
858 fds[i].events = POLLIN;
859 bzero(&clients[i], sizeof(struct client));
866 if (poll(fds, MAX_USERS, INFTIM) == -1) {
867 if (errno == EINTR) {
868 fprintf(stderr, "connected clients: %d\n",
872 fatal("poll: %s", strerror(errno));
875 for (i = 0; i < MAX_USERS; i++) {
876 if (fds[i].revents == 0)
879 if (fds[i].revents & (POLLERR|POLLNVAL))
880 fatal("bad fd %d: %s", fds[i].fd,
883 if (fds[i].revents & POLLHUP) {
884 /* fds[i] may be the fd of the stdin
885 * of a cgi script that has exited. */
886 if (!clients[i].waiting_on_child) {
887 close_conn(&fds[i], &clients[i]);
892 if (fds[i].fd == sock4)
893 do_accept(sock4, ctx, fds, clients);
894 else if (fds[i].fd == sock6)
895 do_accept(sock6, ctx, fds, clients);
897 handle(&fds[i], &clients[i]);