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 if (v == NULL || path == 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 if (v == NULL || path == NULL)
60 for (loc = v->locations; loc->match != NULL; ++loc) {
61 if (!fnmatch(loc->match, path, 0)) {
62 if (loc->default_mime != NULL)
63 default_mime = loc->default_mime;
71 vhost_index(struct vhost *v, const char *path)
74 const char *index = "index.gmi";
76 if (v == NULL || path == NULL)
79 for (loc = v->locations; loc->match != NULL; ++loc) {
80 if (!fnmatch(loc->match, path, 0)) {
81 if (loc->index != NULL)
90 vhost_auto_index(struct vhost *v, const char *path)
95 for (loc = v->locations; loc->match != NULL; ++loc) {
96 if (!fnmatch(loc->match, path, 0)) {
98 auto_index = loc->auto_index;
102 return auto_index == 1;
106 check_path(struct client *c, const char *path, int *fd)
112 assert(path != NULL);
116 else if (*path == '/')
117 /* in send_dir we add an initial / (to be
118 * redirect-friendly), but here we want to skip it */
123 flags = O_RDONLY | O_NOFOLLOW;
125 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
128 if (fstat(*fd, &sb) == -1) {
129 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
133 if (S_ISDIR(sb.st_mode))
134 return FILE_DIRECTORY;
136 if (sb.st_mode & S_IXUSR)
137 return FILE_EXECUTABLE;
143 open_file(struct pollfd *fds, struct client *c)
145 switch (check_path(c, c->iri.path, &c->fd)) {
146 case FILE_EXECUTABLE:
147 if (starts_with(c->iri.path, c->host->cgi)) {
148 start_cgi(c->iri.path, "", c->iri.query, fds, c);
163 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
164 check_for_cgi(c->iri.path, c->iri.query, fds, c);
167 start_reply(fds, c, NOT_FOUND, "not found");
177 load_file(struct pollfd *fds, struct client *c)
179 if ((c->len = filesize(c->fd)) == -1) {
180 LOGE(c, "failed to get file size for %s", c->iri.path);
181 start_reply(fds, c, TEMP_FAILURE, "internal server error");
185 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
186 c->fd, 0)) == MAP_FAILED) {
187 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
188 start_reply(fds, c, TEMP_FAILURE, "internal server error");
192 c->next = S_SENDING_FILE;
193 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
197 * the inverse of this algorithm, i.e. starting from the start of the
198 * path + strlen(cgi), and checking if each component, should be
199 * faster. But it's tedious to write. This does the opposite: starts
200 * from the end and strip one component at a time, until either an
201 * executable is found or we emptied the path.
204 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
207 end = strchr(path, '\0');
209 /* NB: assume CGI is enabled and path matches cgi */
212 /* go up one level. UNIX paths are simple and POSIX
213 * dirname, with its ambiguities on if the given path
214 * is changed or not, gives me headaches. */
219 switch (check_path(c, path, &c->fd)) {
220 case FILE_EXECUTABLE:
221 start_cgi(path, end+1, query, fds,c);
234 start_reply(fds, c, NOT_FOUND, "not found");
239 mark_nonblock(int fd)
243 if ((flags = fcntl(fd, F_GETFL)) == -1)
244 fatal("fcntl(F_GETFL): %s", strerror(errno));
245 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
246 fatal("fcntl(F_SETFL): %s", strerror(errno));
250 handle_handshake(struct pollfd *fds, struct client *c)
253 const char *servname;
255 switch (tls_handshake(c->ctx)) {
256 case 0: /* success */
257 case -1: /* already handshaked */
259 case TLS_WANT_POLLIN:
260 fds->events = POLLIN;
262 case TLS_WANT_POLLOUT:
263 fds->events = POLLOUT;
270 servname = tls_conn_servername(c->ctx);
271 puny_decode(servname, c->domain, sizeof(c->domain));
273 for (h = hosts; h->domain != NULL; ++h) {
274 if (!fnmatch(h->domain, c->domain, 0))
278 LOGD(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
279 servname != NULL ? servname : "(null)",
281 h->domain != NULL ? h->domain : "(null)");
283 if (h->domain != NULL) {
286 handle_open_conn(fds, c);
290 if (servname != NULL)
291 strncpy(c->req, servname, sizeof(c->req));
293 strncpy(c->req, "null", sizeof(c->req));
295 start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
299 handle_open_conn(struct pollfd *fds, struct client *c)
301 const char *parse_err = "invalid request";
302 char decoded[DOMAIN_NAME_LEN];
304 bzero(c->req, sizeof(c->req));
305 bzero(&c->iri, sizeof(c->iri));
307 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
309 LOGE(c, "tls_read: %s", tls_error(c->ctx));
313 case TLS_WANT_POLLIN:
314 fds->events = POLLIN;
317 case TLS_WANT_POLLOUT:
318 fds->events = POLLOUT;
322 if (!trim_req_iri(c->req, &parse_err)
323 || !parse_iri(c->req, &c->iri, &parse_err)) {
324 LOGI(c, "iri parse error: %s", parse_err);
325 start_reply(fds, c, BAD_REQUEST, "invalid request");
329 puny_decode(c->iri.host, decoded, sizeof(decoded));
331 if (c->iri.port_no != conf.port
332 || strcmp(c->iri.schema, "gemini")
333 || strcmp(decoded, c->domain)) {
334 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
342 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
344 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
350 c->state = S_INITIALIZING;
352 lang = vhost_lang(c->host, c->iri.path);
354 snprintf(buf, sizeof(buf), "%d ", code);
355 strlcat(buf, meta, sizeof(buf));
356 if (!strcmp(meta, "text/gemini") && lang != NULL) {
357 strlcat(buf, "; lang=", sizeof(buf));
358 strlcat(buf, lang, sizeof(buf));
361 len = strlcat(buf, "\r\n", sizeof(buf));
362 assert(len < sizeof(buf));
364 switch (tls_write(c->ctx, buf, len)) {
368 case TLS_WANT_POLLIN:
369 pfd->events = POLLIN;
371 case TLS_WANT_POLLOUT:
372 pfd->events = POLLOUT;
376 log_request(c, buf, sizeof(buf));
378 /* we don't need a body */
379 if (c->code != SUCCESS) {
384 /* advance the state machine */
390 start_cgi(const char *spath, const char *relpath, const char *query,
391 struct pollfd *fds, struct client *c)
393 char addr[NI_MAXHOST];
394 const char *ruser, *cissuer, *chash;
397 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
404 if (tls_peer_cert_provided(c->ctx)) {
405 ruser = tls_peer_cert_subject(c->ctx);
406 cissuer = tls_peer_cert_issuer(c->ctx);
407 chash = tls_peer_cert_hash(c->ctx);
414 if (!send_string(exfd, spath)
415 || !send_string(exfd, relpath)
416 || !send_string(exfd, query)
417 || !send_string(exfd, addr)
418 || !send_string(exfd, ruser)
419 || !send_string(exfd, cissuer)
420 || !send_string(exfd, chash)
421 || !send_vhost(exfd, c->host))
425 if ((c->fd = recv_fd(exfd)) == -1) {
426 start_reply(fds, c, TEMP_FAILURE, "internal server error");
429 c->state = S_SENDING_CGI;
430 cgi_poll_on_child(fds, c);
432 /* handle_cgi(fds, c); */
436 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
437 fatal("cannot talk to the executor process");
441 send_file(struct pollfd *fds, struct client *c)
445 /* ensure the correct state */
446 c->state = S_SENDING_FILE;
448 len = (c->buf + c->len) - c->i;
451 switch (ret = tls_write(c->ctx, c->i, len)) {
453 LOGE(c, "tls_write: %s", tls_error(c->ctx));
457 case TLS_WANT_POLLIN:
458 fds->events = POLLIN;
461 case TLS_WANT_POLLOUT:
462 fds->events = POLLOUT;
476 open_dir(struct pollfd *fds, struct client *c)
482 len = strlen(c->iri.path);
483 if (len > 0 && !ends_with(c->iri.path, "/")) {
484 redirect_canonical_dir(fds, c);
488 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
489 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
490 if (!ends_with(c->sbuf, "/"))
491 strlcat(c->sbuf, "/", sizeof(c->sbuf));
492 before_file = strchr(c->sbuf, '\0');
493 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
495 if (len >= sizeof(c->sbuf)) {
496 start_reply(fds, c, TEMP_FAILURE, "internal server error");
500 c->iri.path = c->sbuf;
502 /* close later unless we have to generate the dir listing */
506 switch (check_path(c, c->iri.path, &c->fd)) {
507 case FILE_EXECUTABLE:
508 if (starts_with(c->iri.path, c->host->cgi)) {
509 start_cgi(c->iri.path, "", c->iri.query, fds, c);
520 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
526 if (!vhost_auto_index(c->host, c->iri.path)) {
527 start_reply(fds, c, NOT_FOUND, "not found");
532 c->next = S_SENDING_DIR;
534 if ((c->dir = fdopendir(c->fd)) == NULL) {
535 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
536 c->fd, c->host->domain, c->iri.path, strerror(errno));
537 start_reply(fds, c, TEMP_FAILURE, "internal server error");
542 start_reply(fds, c, SUCCESS, "text/gemini");
554 redirect_canonical_dir(struct pollfd *fds, struct client *c)
558 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
559 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
560 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
562 if (len >= sizeof(c->sbuf)) {
563 start_reply(fds, c, TEMP_FAILURE, "internal server error");
567 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
571 read_next_dir_entry(struct client *c)
577 if ((d = readdir(c->dir)) == NULL) {
579 LOGE(c, "readdir: %s", strerror(errno));
582 } while (!strcmp(d->d_name, "."));
584 /* XXX: url escape */
585 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
586 d->d_name, d->d_name);
587 c->len = strlen(c->sbuf);
594 send_directory_listing(struct pollfd *fds, struct client *c)
600 if (!read_next_dir_entry(c))
605 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
609 case TLS_WANT_POLLOUT:
610 fds->events = POLLOUT;
613 case TLS_WANT_POLLIN:
614 fds->events = POLLIN;
630 cgi_poll_on_child(struct pollfd *fds, struct client *c)
634 if (c->waiting_on_child)
636 c->waiting_on_child = 1;
638 fds->events = POLLIN;
646 cgi_poll_on_client(struct pollfd *fds, struct client *c)
650 if (!c->waiting_on_child)
652 c->waiting_on_child = 0;
659 /* handle the read from the child process. Return like read(2) */
661 read_from_cgi(struct client *c)
667 /* if we haven't read a whole response line, we want to
668 * continue reading. */
671 buf = c->sbuf + c->len;
672 len = sizeof(c->sbuf) - c->len;
675 len = sizeof(c->sbuf);
678 r = read(c->fd, buf, len);
679 if (r == 0 || r == -1)
688 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
690 log_request(c, c->sbuf, c->len);
697 handle_cgi(struct pollfd *fds, struct client *c)
701 /* ensure c->fd is the child and fds->fd the client */
702 cgi_poll_on_client(fds, c);
705 if (c->code == -1 || c->len == 0) {
706 switch (r = read_from_cgi(c)) {
711 if (errno == EAGAIN || errno == EWOULDBLOCK) {
712 cgi_poll_on_child(fds, c);
720 cgi_poll_on_child(fds, c);
725 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
729 case TLS_WANT_POLLOUT:
730 fds->events = POLLOUT;
733 case TLS_WANT_POLLIN:
734 fds->events = POLLIN;
750 close_conn(struct pollfd *pfd, struct client *c)
752 c->state = S_CLOSING;
754 switch (tls_close(c->ctx)) {
755 case TLS_WANT_POLLIN:
756 pfd->events = POLLIN;
758 case TLS_WANT_POLLOUT:
759 pfd->events = POLLOUT;
768 if (c->buf != MAP_FAILED)
769 munmap(c->buf, c->len);
782 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
785 struct sockaddr_storage addr;
789 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
790 if (errno == EWOULDBLOCK)
792 fatal("accept: %s", strerror(errno));
797 for (i = 0; i < MAX_USERS; ++i) {
798 if (fds[i].fd == -1) {
799 bzero(&clients[i], sizeof(struct client));
800 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
801 break; /* goodbye fd! */
804 fds[i].events = POLLIN;
806 clients[i].state = S_HANDSHAKE;
807 clients[i].next = S_SENDING_FILE;
809 clients[i].waiting_on_child = 0;
810 clients[i].buf = MAP_FAILED;
811 clients[i].dir = NULL;
812 clients[i].addr = addr;
823 handle(struct pollfd *fds, struct client *client)
825 switch (client->state) {
827 handle_handshake(fds, client);
831 handle_open_conn(fds, client);
835 start_reply(fds, client, client->code, client->meta);
839 send_file(fds, client);
843 send_directory_listing(fds, client);
847 handle_cgi(fds, client);
851 close_conn(fds, client);
861 loop(struct tls *ctx, int sock4, int sock6)
864 struct client clients[MAX_USERS];
865 struct pollfd fds[MAX_USERS];
867 connected_clients = 0;
869 for (i = 0; i < MAX_USERS; ++i) {
871 fds[i].events = POLLIN;
872 bzero(&clients[i], sizeof(struct client));
879 if (poll(fds, MAX_USERS, INFTIM) == -1) {
880 if (errno == EINTR) {
881 fprintf(stderr, "connected clients: %d\n",
885 fatal("poll: %s", strerror(errno));
888 for (i = 0; i < MAX_USERS; i++) {
889 if (fds[i].revents == 0)
892 if (fds[i].revents & (POLLERR|POLLNVAL))
893 fatal("bad fd %d: %s", fds[i].fd,
896 if (fds[i].revents & POLLHUP) {
897 /* fds[i] may be the fd of the stdin
898 * of a cgi script that has exited. */
899 if (!clients[i].waiting_on_child) {
900 close_conn(&fds[i], &clients[i]);
905 if (fds[i].fd == sock4)
906 do_accept(sock4, ctx, fds, clients);
907 else if (fds[i].fd == sock6)
908 do_accept(sock6, ctx, fds, clients);
910 handle(&fds[i], &clients[i]);