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;
38 for (loc = v->locations; loc->match != NULL; ++loc) {
39 if (!fnmatch(loc->match, path, 0)) {
40 if (loc->lang != NULL)
49 vhost_default_mime(struct vhost *v, const char *path)
52 const char *default_mime = "application/octet-stream";
54 for (loc = v->locations; loc->match != NULL; ++loc) {
55 if (!fnmatch(loc->match, path, 0)) {
56 if (loc->default_mime != NULL)
57 default_mime = loc->default_mime;
65 vhost_index(struct vhost *v, const char *path)
68 const char *index = "index.gmi";
70 for (loc = v->locations; loc->match != NULL; ++loc) {
71 if (!fnmatch(loc->match, path, 0)) {
72 if (loc->index != NULL)
81 vhost_auto_index(struct vhost *v, const char *path)
86 for (loc = v->locations; loc->match != NULL; ++loc) {
87 if (!fnmatch(loc->match, path, 0)) {
89 auto_index = loc->auto_index;
93 return auto_index == 1;
97 check_path(struct client *c, const char *path, int *fd)
103 assert(path != NULL);
107 else if (*path == '/')
108 /* in send_dir we add an initial / (to be
109 * redirect-friendly), but here we want to skip it */
114 flags = O_RDONLY | O_NOFOLLOW;
116 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
119 if (fstat(*fd, &sb) == -1) {
120 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
124 if (S_ISDIR(sb.st_mode))
125 return FILE_DIRECTORY;
127 if (sb.st_mode & S_IXUSR)
128 return FILE_EXECUTABLE;
134 open_file(struct pollfd *fds, struct client *c)
136 switch (check_path(c, c->iri.path, &c->fd)) {
137 case FILE_EXECUTABLE:
138 if (starts_with(c->iri.path, c->host->cgi)) {
139 start_cgi(c->iri.path, "", c->iri.query, fds, c);
154 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
155 check_for_cgi(c->iri.path, c->iri.query, fds, c);
158 start_reply(fds, c, NOT_FOUND, "not found");
168 load_file(struct pollfd *fds, struct client *c)
170 if ((c->len = filesize(c->fd)) == -1) {
171 LOGE(c, "failed to get file size for %s", c->iri.path);
172 start_reply(fds, c, TEMP_FAILURE, "internal server error");
176 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
177 c->fd, 0)) == MAP_FAILED) {
178 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
179 start_reply(fds, c, TEMP_FAILURE, "internal server error");
183 c->next = S_SENDING_FILE;
184 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
188 * the inverse of this algorithm, i.e. starting from the start of the
189 * path + strlen(cgi), and checking if each component, should be
190 * faster. But it's tedious to write. This does the opposite: starts
191 * from the end and strip one component at a time, until either an
192 * executable is found or we emptied the path.
195 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
198 end = strchr(path, '\0');
200 /* NB: assume CGI is enabled and path matches cgi */
203 /* go up one level. UNIX paths are simple and POSIX
204 * dirname, with its ambiguities on if the given path
205 * is changed or not, gives me headaches. */
210 switch (check_path(c, path, &c->fd)) {
211 case FILE_EXECUTABLE:
212 start_cgi(path, end+1, query, fds,c);
225 start_reply(fds, c, NOT_FOUND, "not found");
230 mark_nonblock(int fd)
234 if ((flags = fcntl(fd, F_GETFL)) == -1)
235 fatal("fcntl(F_GETFL): %s", strerror(errno));
236 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
237 fatal("fcntl(F_SETFL): %s", strerror(errno));
241 handle_handshake(struct pollfd *fds, struct client *c)
244 const char *servname;
246 switch (tls_handshake(c->ctx)) {
247 case 0: /* success */
248 case -1: /* already handshaked */
250 case TLS_WANT_POLLIN:
251 fds->events = POLLIN;
253 case TLS_WANT_POLLOUT:
254 fds->events = POLLOUT;
261 servname = tls_conn_servername(c->ctx);
263 for (h = hosts; h->domain != NULL; ++h) {
264 if (!strcmp(h->domain, "*"))
267 if (servname != NULL && !fnmatch(h->domain, servname, 0))
271 if (h->domain != NULL) {
274 handle_open_conn(fds, c);
278 if (servname != NULL)
279 strncpy(c->req, servname, sizeof(c->req));
281 strncpy(c->req, "null", sizeof(c->req));
283 start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
287 handle_open_conn(struct pollfd *fds, struct client *c)
289 const char *parse_err = "invalid request";
291 bzero(c->req, sizeof(c->req));
292 bzero(&c->iri, sizeof(c->iri));
294 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
296 LOGE(c, "tls_read: %s", tls_error(c->ctx));
300 case TLS_WANT_POLLIN:
301 fds->events = POLLIN;
304 case TLS_WANT_POLLOUT:
305 fds->events = POLLOUT;
309 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
310 start_reply(fds, c, BAD_REQUEST, parse_err);
314 /* XXX: we should check that the SNI matches the requested host */
315 if (strcmp(c->iri.schema, "gemini") || c->iri.port_no != conf.port) {
316 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
324 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
326 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
332 c->state = S_INITIALIZING;
334 lang = vhost_lang(c->host, c->iri.path);
336 snprintf(buf, sizeof(buf), "%d ", code);
337 strlcat(buf, meta, sizeof(buf));
338 if (!strcmp(meta, "text/gemini") && lang != NULL) {
339 strlcat(buf, "; lang=", sizeof(buf));
340 strlcat(buf, lang, sizeof(buf));
343 len = strlcat(buf, "\r\n", sizeof(buf));
344 assert(len < sizeof(buf));
346 switch (tls_write(c->ctx, buf, len)) {
350 case TLS_WANT_POLLIN:
351 pfd->events = POLLIN;
353 case TLS_WANT_POLLOUT:
354 pfd->events = POLLOUT;
358 log_request(c, buf, sizeof(buf));
360 /* we don't need a body */
361 if (c->code != SUCCESS) {
366 /* advance the state machine */
372 start_cgi(const char *spath, const char *relpath, const char *query,
373 struct pollfd *fds, struct client *c)
375 char addr[NI_MAXHOST];
376 const char *ruser, *cissuer, *chash;
379 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
386 if (tls_peer_cert_provided(c->ctx)) {
387 ruser = tls_peer_cert_subject(c->ctx);
388 cissuer = tls_peer_cert_issuer(c->ctx);
389 chash = tls_peer_cert_hash(c->ctx);
396 if (!send_string(exfd, spath)
397 || !send_string(exfd, relpath)
398 || !send_string(exfd, query)
399 || !send_string(exfd, addr)
400 || !send_string(exfd, ruser)
401 || !send_string(exfd, cissuer)
402 || !send_string(exfd, chash)
403 || !send_vhost(exfd, c->host))
407 if ((c->fd = recv_fd(exfd)) == -1) {
408 start_reply(fds, c, TEMP_FAILURE, "internal server error");
411 c->state = S_SENDING_CGI;
412 cgi_poll_on_child(fds, c);
414 /* handle_cgi(fds, c); */
418 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
419 fatal("cannot talk to the executor process");
423 send_file(struct pollfd *fds, struct client *c)
427 /* ensure the correct state */
428 c->state = S_SENDING_FILE;
430 len = (c->buf + c->len) - c->i;
433 switch (ret = tls_write(c->ctx, c->i, len)) {
435 LOGE(c, "tls_write: %s", tls_error(c->ctx));
439 case TLS_WANT_POLLIN:
440 fds->events = POLLIN;
443 case TLS_WANT_POLLOUT:
444 fds->events = POLLOUT;
458 open_dir(struct pollfd *fds, struct client *c)
464 len = strlen(c->iri.path);
465 if (len > 0 && !ends_with(c->iri.path, "/")) {
466 redirect_canonical_dir(fds, c);
470 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
471 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
472 if (!ends_with(c->sbuf, "/"))
473 strlcat(c->sbuf, "/", sizeof(c->sbuf));
474 before_file = strchr(c->sbuf, '\0');
475 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
477 if (len >= sizeof(c->sbuf)) {
478 start_reply(fds, c, TEMP_FAILURE, "internal server error");
482 c->iri.path = c->sbuf;
484 /* close later unless we have to generate the dir listing */
488 switch (check_path(c, c->iri.path, &c->fd)) {
489 case FILE_EXECUTABLE:
490 if (starts_with(c->iri.path, c->host->cgi)) {
491 start_cgi(c->iri.path, "", c->iri.query, fds, c);
502 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
508 if (!vhost_auto_index(c->host, c->iri.path)) {
509 start_reply(fds, c, NOT_FOUND, "not found");
514 c->next = S_SENDING_DIR;
516 if ((c->dir = fdopendir(c->fd)) == NULL) {
517 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
518 c->fd, c->host->domain, c->iri.path, strerror(errno));
519 start_reply(fds, c, TEMP_FAILURE, "internal server error");
524 start_reply(fds, c, SUCCESS, "text/gemini");
536 redirect_canonical_dir(struct pollfd *fds, struct client *c)
540 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
541 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
542 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
544 if (len >= sizeof(c->sbuf)) {
545 start_reply(fds, c, TEMP_FAILURE, "internal server error");
549 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
553 read_next_dir_entry(struct client *c)
559 if ((d = readdir(c->dir)) == NULL) {
561 LOGE(c, "readdir: %s", strerror(errno));
564 } while (!strcmp(d->d_name, "."));
566 /* XXX: url escape */
567 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
568 d->d_name, d->d_name);
569 c->len = strlen(c->sbuf);
576 send_directory_listing(struct pollfd *fds, struct client *c)
582 if (!read_next_dir_entry(c))
587 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
591 case TLS_WANT_POLLOUT:
592 fds->events = POLLOUT;
595 case TLS_WANT_POLLIN:
596 fds->events = POLLIN;
612 cgi_poll_on_child(struct pollfd *fds, struct client *c)
616 if (c->waiting_on_child)
618 c->waiting_on_child = 1;
620 fds->events = POLLIN;
628 cgi_poll_on_client(struct pollfd *fds, struct client *c)
632 if (!c->waiting_on_child)
634 c->waiting_on_child = 0;
641 /* handle the read from the child process. Return like read(2) */
643 read_from_cgi(struct client *c)
649 /* if we haven't read a whole response line, we want to
650 * continue reading. */
653 buf = c->sbuf + c->len;
654 len = sizeof(c->sbuf) - c->len;
657 len = sizeof(c->sbuf);
660 r = read(c->fd, buf, len);
661 if (r == 0 || r == -1)
670 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
672 log_request(c, c->sbuf, c->len);
679 handle_cgi(struct pollfd *fds, struct client *c)
683 /* ensure c->fd is the child and fds->fd the client */
684 cgi_poll_on_client(fds, c);
687 if (c->code == -1 || c->len == 0) {
688 switch (r = read_from_cgi(c)) {
693 if (errno == EAGAIN || errno == EWOULDBLOCK) {
694 cgi_poll_on_child(fds, c);
702 cgi_poll_on_child(fds, c);
707 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
711 case TLS_WANT_POLLOUT:
712 fds->events = POLLOUT;
715 case TLS_WANT_POLLIN:
716 fds->events = POLLIN;
732 close_conn(struct pollfd *pfd, struct client *c)
734 c->state = S_CLOSING;
736 switch (tls_close(c->ctx)) {
737 case TLS_WANT_POLLIN:
738 pfd->events = POLLIN;
740 case TLS_WANT_POLLOUT:
741 pfd->events = POLLOUT;
750 if (c->buf != MAP_FAILED)
751 munmap(c->buf, c->len);
764 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
767 struct sockaddr_storage addr;
771 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
772 if (errno == EWOULDBLOCK)
774 fatal("accept: %s", strerror(errno));
779 for (i = 0; i < MAX_USERS; ++i) {
780 if (fds[i].fd == -1) {
781 bzero(&clients[i], sizeof(struct client));
782 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
783 break; /* goodbye fd! */
786 fds[i].events = POLLIN;
788 clients[i].state = S_HANDSHAKE;
789 clients[i].next = S_SENDING_FILE;
791 clients[i].waiting_on_child = 0;
792 clients[i].buf = MAP_FAILED;
793 clients[i].dir = NULL;
794 clients[i].addr = addr;
805 handle(struct pollfd *fds, struct client *client)
807 switch (client->state) {
809 handle_handshake(fds, client);
813 handle_open_conn(fds, client);
817 start_reply(fds, client, client->code, client->meta);
821 send_file(fds, client);
825 send_directory_listing(fds, client);
829 handle_cgi(fds, client);
833 close_conn(fds, client);
843 loop(struct tls *ctx, int sock4, int sock6)
846 struct client clients[MAX_USERS];
847 struct pollfd fds[MAX_USERS];
849 connected_clients = 0;
851 for (i = 0; i < MAX_USERS; ++i) {
853 fds[i].events = POLLIN;
854 bzero(&clients[i], sizeof(struct client));
861 if (poll(fds, MAX_USERS, INFTIM) == -1) {
862 if (errno == EINTR) {
863 fprintf(stderr, "connected clients: %d\n",
867 fatal("poll: %s", strerror(errno));
870 for (i = 0; i < MAX_USERS; i++) {
871 if (fds[i].revents == 0)
874 if (fds[i].revents & (POLLERR|POLLNVAL))
875 fatal("bad fd %d: %s", fds[i].fd,
878 if (fds[i].revents & POLLHUP) {
879 /* fds[i] may be the fd of the stdin
880 * of a cgi script that has exited. */
881 if (!clients[i].waiting_on_child) {
882 close_conn(&fds[i], &clients[i]);
887 if (fds[i].fd == sock4)
888 do_accept(sock4, ctx, fds, clients);
889 else if (fds[i].fd == sock6)
890 do_accept(sock6, ctx, fds, clients);
892 handle(&fds[i], &clients[i]);