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;
33 static int check_path(struct client*, const char*, int*);
34 static void open_file(struct pollfd*, struct client*);
35 static void load_file(struct pollfd*, struct client*);
36 static void check_for_cgi(struct pollfd*, struct client*);
37 static void handle_handshake(struct pollfd*, struct client*);
38 static void handle_open_conn(struct pollfd*, struct client*);
39 static void start_reply(struct pollfd*, struct client*, int, const char*);
40 static void handle_start_reply(struct pollfd*, struct client*);
41 static void start_cgi(const char*, const char*, struct pollfd*, struct client*);
42 static void send_file(struct pollfd*, struct client*);
43 static void open_dir(struct pollfd*, struct client*);
44 static void redirect_canonical_dir(struct pollfd*, struct client*);
45 static void enter_handle_dirlist(struct pollfd*, struct client*);
46 static void handle_dirlist(struct pollfd*, struct client*);
47 static int read_next_dir_entry(struct client*);
48 static void send_directory_listing(struct pollfd*, struct client*);
49 static void cgi_poll_on_child(struct pollfd*, struct client*);
50 static void cgi_poll_on_client(struct pollfd*, struct client*);
51 static void handle_cgi_reply(struct pollfd*, struct client*);
52 static void handle_cgi(struct pollfd*, struct client*);
53 static void close_conn(struct pollfd*, struct client*);
54 static void do_accept(int, struct tls*, struct pollfd*, struct client*);
57 vhost_lang(struct vhost *v, const char *path)
61 if (v == NULL || path == NULL)
64 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
65 if (!fnmatch(loc->match, path, 0)) {
66 if (loc->lang != NULL)
71 return v->locations[0].lang;
75 vhost_default_mime(struct vhost *v, const char *path)
78 const char *default_mime = "application/octet-stream";
80 if (v == NULL || path == NULL)
83 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
84 if (!fnmatch(loc->match, path, 0)) {
85 if (loc->default_mime != NULL)
86 return loc->default_mime;
90 if (v->locations[0].default_mime != NULL)
91 return v->locations[0].default_mime;
96 vhost_index(struct vhost *v, const char *path)
99 const char *index = "index.gmi";
101 if (v == NULL || path == NULL)
104 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
105 if (!fnmatch(loc->match, path, 0)) {
106 if (loc->index != NULL)
111 if (v->locations[0].index != NULL)
112 return v->locations[0].index;
117 vhost_auto_index(struct vhost *v, const char *path)
119 struct location *loc;
121 if (v == NULL || path == NULL)
124 for (loc = v->locations; loc->match != NULL; ++loc) {
125 if (!fnmatch(loc->match, path, 0)) {
126 if (loc->auto_index != 0)
127 return loc->auto_index == 1;
131 return v->locations[0].auto_index == 1;
135 check_path(struct client *c, const char *path, int *fd)
141 assert(path != NULL);
145 else if (*path == '/')
146 /* in send_dir we add an initial / (to be
147 * redirect-friendly), but here we want to skip it */
152 flags = O_RDONLY | O_NOFOLLOW;
154 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
157 if (fstat(*fd, &sb) == -1) {
158 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
162 if (S_ISDIR(sb.st_mode))
163 return FILE_DIRECTORY;
165 if (sb.st_mode & S_IXUSR)
166 return FILE_EXECUTABLE;
172 open_file(struct pollfd *fds, struct client *c)
174 switch (check_path(c, c->iri.path, &c->fd)) {
175 case FILE_EXECUTABLE:
176 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
177 start_cgi(c->iri.path, "", fds, c);
192 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
193 check_for_cgi(fds, c);
196 start_reply(fds, c, NOT_FOUND, "not found");
206 load_file(struct pollfd *fds, struct client *c)
208 if ((c->len = filesize(c->fd)) == -1) {
209 LOGE(c, "failed to get file size for %s: %s",
210 c->iri.path, strerror(errno));
211 start_reply(fds, c, TEMP_FAILURE, "internal server error");
215 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
216 c->fd, 0)) == MAP_FAILED) {
217 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
218 start_reply(fds, c, TEMP_FAILURE, "internal server error");
223 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
227 * the inverse of this algorithm, i.e. starting from the start of the
228 * path + strlen(cgi), and checking if each component, should be
229 * faster. But it's tedious to write. This does the opposite: starts
230 * from the end and strip one component at a time, until either an
231 * executable is found or we emptied the path.
234 check_for_cgi(struct pollfd *fds, struct client *c)
239 strlcpy(path, c->iri.path, sizeof(path));
240 end = strchr(path, '\0');
242 /* NB: assume CGI is enabled and path matches cgi */
245 /* go up one level. UNIX paths are simple and POSIX
246 * dirname, with its ambiguities on if the given path
247 * is changed or not, gives me headaches. */
252 switch (check_path(c, path, &c->fd)) {
253 case FILE_EXECUTABLE:
254 start_cgi(path, end+1, fds, c);
267 start_reply(fds, c, NOT_FOUND, "not found");
272 handle_handshake(struct pollfd *fds, struct client *c)
275 const char *servname;
276 const char *parse_err = "unknown error";
278 switch (tls_handshake(c->ctx)) {
279 case 0: /* success */
280 case -1: /* already handshaked */
282 case TLS_WANT_POLLIN:
283 fds->events = POLLIN;
285 case TLS_WANT_POLLOUT:
286 fds->events = POLLOUT;
293 servname = tls_conn_servername(c->ctx);
294 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
295 LOGI(c, "%s", parse_err);
299 for (h = hosts; h->domain != NULL; ++h) {
300 if (!fnmatch(h->domain, c->domain, 0))
304 /* LOGD(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"", */
305 /* servname != NULL ? servname : "(null)", */
307 /* h->domain != NULL ? h->domain : "(null)"); */
309 if (h->domain != NULL) {
311 c->state = handle_open_conn;
317 if (servname != NULL)
318 strncpy(c->req, servname, sizeof(c->req));
320 strncpy(c->req, "null", sizeof(c->req));
322 start_reply(fds, c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
326 handle_open_conn(struct pollfd *fds, struct client *c)
328 const char *parse_err = "invalid request";
329 char decoded[DOMAIN_NAME_LEN];
331 bzero(c->req, sizeof(c->req));
332 bzero(&c->iri, sizeof(c->iri));
334 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
336 LOGE(c, "tls_read: %s", tls_error(c->ctx));
340 case TLS_WANT_POLLIN:
341 fds->events = POLLIN;
344 case TLS_WANT_POLLOUT:
345 fds->events = POLLOUT;
349 if (!trim_req_iri(c->req, &parse_err)
350 || !parse_iri(c->req, &c->iri, &parse_err)
351 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
352 LOGI(c, "iri parse error: %s", parse_err);
353 start_reply(fds, c, BAD_REQUEST, "invalid request");
357 if (c->iri.port_no != conf.port
358 || strcmp(c->iri.schema, "gemini")
359 || strcmp(decoded, c->domain)) {
360 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
368 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
372 c->state = handle_start_reply;
373 handle_start_reply(pfd, c);
377 handle_start_reply(struct pollfd *pfd, struct client *c)
379 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
383 lang = vhost_lang(c->host, c->iri.path);
385 snprintf(buf, sizeof(buf), "%d ", c->code);
386 strlcat(buf, c->meta, sizeof(buf));
387 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
388 strlcat(buf, "; lang=", sizeof(buf));
389 strlcat(buf, lang, sizeof(buf));
392 len = strlcat(buf, "\r\n", sizeof(buf));
393 assert(len < sizeof(buf));
395 switch (tls_write(c->ctx, buf, len)) {
399 case TLS_WANT_POLLIN:
400 pfd->events = POLLIN;
402 case TLS_WANT_POLLOUT:
403 pfd->events = POLLOUT;
407 log_request(c, buf, sizeof(buf));
409 /* we don't need a body */
410 if (c->code != SUCCESS) {
415 /* advance the state machine */
421 start_cgi(const char *spath, const char *relpath,
422 struct pollfd *fds, struct client *c)
424 char addr[NI_MAXHOST];
425 const char *ruser, *cissuer, *chash;
428 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
435 if (tls_peer_cert_provided(c->ctx)) {
436 ruser = tls_peer_cert_subject(c->ctx);
437 cissuer = tls_peer_cert_issuer(c->ctx);
438 chash = tls_peer_cert_hash(c->ctx);
445 if (!send_iri(exfd, &c->iri)
446 || !send_string(exfd, spath)
447 || !send_string(exfd, relpath)
448 || !send_string(exfd, addr)
449 || !send_string(exfd, ruser)
450 || !send_string(exfd, cissuer)
451 || !send_string(exfd, chash)
452 || !send_vhost(exfd, c->host))
456 if ((c->fd = recv_fd(exfd)) == -1) {
457 start_reply(fds, c, TEMP_FAILURE, "internal server error");
461 cgi_poll_on_child(fds, c);
462 c->state = handle_cgi_reply;
466 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
467 fatal("cannot talk to the executor process");
471 send_file(struct pollfd *fds, struct client *c)
475 len = (c->buf + c->len) - c->i;
478 switch (ret = tls_write(c->ctx, c->i, len)) {
480 LOGE(c, "tls_write: %s", tls_error(c->ctx));
484 case TLS_WANT_POLLIN:
485 fds->events = POLLIN;
488 case TLS_WANT_POLLOUT:
489 fds->events = POLLOUT;
503 open_dir(struct pollfd *fds, struct client *c)
509 len = strlen(c->iri.path);
510 if (len > 0 && !ends_with(c->iri.path, "/")) {
511 redirect_canonical_dir(fds, c);
515 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
516 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
517 if (!ends_with(c->sbuf, "/"))
518 strlcat(c->sbuf, "/", sizeof(c->sbuf));
519 before_file = strchr(c->sbuf, '\0');
520 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
522 if (len >= sizeof(c->sbuf)) {
523 start_reply(fds, c, TEMP_FAILURE, "internal server error");
527 c->iri.path = c->sbuf;
529 /* close later unless we have to generate the dir listing */
533 switch (check_path(c, c->iri.path, &c->fd)) {
534 case FILE_EXECUTABLE:
535 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
536 start_cgi(c->iri.path, "", fds, c);
547 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
553 if (!vhost_auto_index(c->host, c->iri.path)) {
554 start_reply(fds, c, NOT_FOUND, "not found");
559 c->next = enter_handle_dirlist;
561 if ((c->dir = fdopendir(c->fd)) == NULL) {
562 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
563 c->fd, c->host->domain, c->iri.path, strerror(errno));
564 start_reply(fds, c, TEMP_FAILURE, "internal server error");
569 start_reply(fds, c, SUCCESS, "text/gemini");
581 redirect_canonical_dir(struct pollfd *fds, struct client *c)
585 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
586 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
587 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
589 if (len >= sizeof(c->sbuf)) {
590 start_reply(fds, c, TEMP_FAILURE, "internal server error");
594 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
598 enter_handle_dirlist(struct pollfd *fds, struct client *c)
603 strlcpy(b, c->iri.path, sizeof(b));
604 l = snprintf(c->sbuf, sizeof(c->sbuf),
605 "# Index of %s\n\n", b);
606 if (l >= sizeof(c->sbuf)) {
607 /* this is impossible, given that we have enough space
608 * in c->sbuf to hold the ancilliary string plus the
609 * full path; but it wouldn't read nice without some
610 * error checking, and I'd like to avoid a strlen. */
616 c->state = handle_dirlist;
617 handle_dirlist(fds, c);
621 handle_dirlist(struct pollfd *fds, struct client *c)
626 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
630 case TLS_WANT_POLLOUT:
631 fds->events = POLLOUT;
633 case TLS_WANT_POLLIN:
634 fds->events = POLLIN;
642 c->state = send_directory_listing;
643 send_directory_listing(fds, c);
647 read_next_dir_entry(struct client *c)
653 if ((d = readdir(c->dir)) == NULL) {
655 LOGE(c, "readdir: %s", strerror(errno));
658 } while (!strcmp(d->d_name, "."));
660 /* XXX: url escape */
661 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
662 d->d_name, d->d_name);
663 c->len = strlen(c->sbuf);
670 send_directory_listing(struct pollfd *fds, struct client *c)
676 if (!read_next_dir_entry(c))
681 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
685 case TLS_WANT_POLLOUT:
686 fds->events = POLLOUT;
689 case TLS_WANT_POLLIN:
690 fds->events = POLLIN;
706 cgi_poll_on_child(struct pollfd *fds, struct client *c)
710 if (c->waiting_on_child)
712 c->waiting_on_child = 1;
714 fds->events = POLLIN;
722 cgi_poll_on_client(struct pollfd *fds, struct client *c)
726 if (!c->waiting_on_child)
728 c->waiting_on_child = 0;
735 /* accumulate the meta line from the cgi script. */
737 handle_cgi_reply(struct pollfd *fds, struct client *c)
743 buf = c->sbuf + c->len;
744 len = sizeof(c->sbuf) - c->len;
746 /* we're polling on the child! */
747 r = read(fds->fd, buf, len);
748 if (r == 0 || r == -1) {
749 cgi_poll_on_client(fds, c);
750 start_reply(fds, c, CGI_ERROR, "CGI error");
756 /* TODO: error if the CGI script don't reply correctly */
757 e = strchr(c->sbuf, '\n');
758 if (e != NULL || c->len == sizeof(c->sbuf)) {
759 log_request(c, c->sbuf, c->len);
762 c->state = handle_cgi;
769 handle_cgi(struct pollfd *fds, struct client *c)
773 /* ensure c->fd is the child and fds->fd the client */
774 cgi_poll_on_client(fds, c);
778 switch (r = read(c->fd, c->sbuf, sizeof(c->sbuf))) {
782 if (errno == EAGAIN || errno == EWOULDBLOCK) {
783 cgi_poll_on_child(fds, c);
794 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
798 case TLS_WANT_POLLOUT:
799 fds->events = POLLOUT;
802 case TLS_WANT_POLLIN:
803 fds->events = POLLIN;
819 close_conn(struct pollfd *pfd, struct client *c)
821 c->state = close_conn;
823 switch (tls_close(c->ctx)) {
824 case TLS_WANT_POLLIN:
825 pfd->events = POLLIN;
827 case TLS_WANT_POLLOUT:
828 pfd->events = POLLOUT;
837 if (c->buf != MAP_FAILED)
838 munmap(c->buf, c->len);
851 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
854 struct sockaddr_storage addr;
858 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
859 if (errno == EWOULDBLOCK)
861 fatal("accept: %s", strerror(errno));
866 for (i = 0; i < MAX_USERS; ++i) {
867 if (fds[i].fd == -1) {
868 bzero(&clients[i], sizeof(struct client));
869 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
870 break; /* goodbye fd! */
873 fds[i].events = POLLIN;
875 clients[i].state = handle_handshake;
876 clients[i].next = send_file;
878 clients[i].waiting_on_child = 0;
879 clients[i].buf = MAP_FAILED;
880 clients[i].dir = NULL;
881 clients[i].addr = addr;
892 loop(struct tls *ctx, int sock4, int sock6)
895 struct client clients[MAX_USERS];
896 struct pollfd fds[MAX_USERS];
898 connected_clients = 0;
900 for (i = 0; i < MAX_USERS; ++i) {
902 fds[i].events = POLLIN;
903 bzero(&clients[i], sizeof(struct client));
910 if (poll(fds, MAX_USERS, INFTIM) == -1) {
911 if (errno == EINTR) {
912 fprintf(stderr, "connected clients: %d\n",
916 fatal("poll: %s", strerror(errno));
919 for (i = 0; i < MAX_USERS; i++) {
920 if (fds[i].revents == 0)
923 if (fds[i].revents & (POLLERR|POLLNVAL))
924 fatal("bad fd %d: %s", fds[i].fd,
927 if (fds[i].revents & POLLHUP) {
928 /* fds[i] may be the fd of the stdin
929 * of a cgi script that has exited. */
930 if (!clients[i].waiting_on_child) {
931 close_conn(&fds[i], &clients[i]);
936 if (fds[i].fd == sock4)
937 do_accept(sock4, ctx, fds, clients);
938 else if (fds[i].fd == sock6)
939 do_accept(sock6, ctx, fds, clients);
941 clients[i].state(&fds[i], &clients[i]);