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 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
325 LOGI(c, "iri parse error: %s", parse_err);
326 start_reply(fds, c, BAD_REQUEST, "invalid request");
330 if (c->iri.port_no != conf.port
331 || strcmp(c->iri.schema, "gemini")
332 || strcmp(decoded, c->domain)) {
333 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
341 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
343 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
349 c->state = S_INITIALIZING;
351 lang = vhost_lang(c->host, c->iri.path);
353 snprintf(buf, sizeof(buf), "%d ", code);
354 strlcat(buf, meta, sizeof(buf));
355 if (!strcmp(meta, "text/gemini") && lang != NULL) {
356 strlcat(buf, "; lang=", sizeof(buf));
357 strlcat(buf, lang, sizeof(buf));
360 len = strlcat(buf, "\r\n", sizeof(buf));
361 assert(len < sizeof(buf));
363 switch (tls_write(c->ctx, buf, len)) {
367 case TLS_WANT_POLLIN:
368 pfd->events = POLLIN;
370 case TLS_WANT_POLLOUT:
371 pfd->events = POLLOUT;
375 log_request(c, buf, sizeof(buf));
377 /* we don't need a body */
378 if (c->code != SUCCESS) {
383 /* advance the state machine */
389 start_cgi(const char *spath, const char *relpath, const char *query,
390 struct pollfd *fds, struct client *c)
392 char addr[NI_MAXHOST];
393 const char *ruser, *cissuer, *chash;
396 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
403 if (tls_peer_cert_provided(c->ctx)) {
404 ruser = tls_peer_cert_subject(c->ctx);
405 cissuer = tls_peer_cert_issuer(c->ctx);
406 chash = tls_peer_cert_hash(c->ctx);
413 if (!send_string(exfd, spath)
414 || !send_string(exfd, relpath)
415 || !send_string(exfd, query)
416 || !send_string(exfd, addr)
417 || !send_string(exfd, ruser)
418 || !send_string(exfd, cissuer)
419 || !send_string(exfd, chash)
420 || !send_vhost(exfd, c->host))
424 if ((c->fd = recv_fd(exfd)) == -1) {
425 start_reply(fds, c, TEMP_FAILURE, "internal server error");
428 c->state = S_SENDING_CGI;
429 cgi_poll_on_child(fds, c);
431 /* handle_cgi(fds, c); */
435 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
436 fatal("cannot talk to the executor process");
440 send_file(struct pollfd *fds, struct client *c)
444 /* ensure the correct state */
445 c->state = S_SENDING_FILE;
447 len = (c->buf + c->len) - c->i;
450 switch (ret = tls_write(c->ctx, c->i, len)) {
452 LOGE(c, "tls_write: %s", tls_error(c->ctx));
456 case TLS_WANT_POLLIN:
457 fds->events = POLLIN;
460 case TLS_WANT_POLLOUT:
461 fds->events = POLLOUT;
475 open_dir(struct pollfd *fds, struct client *c)
481 len = strlen(c->iri.path);
482 if (len > 0 && !ends_with(c->iri.path, "/")) {
483 redirect_canonical_dir(fds, c);
487 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
488 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
489 if (!ends_with(c->sbuf, "/"))
490 strlcat(c->sbuf, "/", sizeof(c->sbuf));
491 before_file = strchr(c->sbuf, '\0');
492 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
494 if (len >= sizeof(c->sbuf)) {
495 start_reply(fds, c, TEMP_FAILURE, "internal server error");
499 c->iri.path = c->sbuf;
501 /* close later unless we have to generate the dir listing */
505 switch (check_path(c, c->iri.path, &c->fd)) {
506 case FILE_EXECUTABLE:
507 if (starts_with(c->iri.path, c->host->cgi)) {
508 start_cgi(c->iri.path, "", c->iri.query, fds, c);
519 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
525 if (!vhost_auto_index(c->host, c->iri.path)) {
526 start_reply(fds, c, NOT_FOUND, "not found");
531 c->next = S_SENDING_DIR;
533 if ((c->dir = fdopendir(c->fd)) == NULL) {
534 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
535 c->fd, c->host->domain, c->iri.path, strerror(errno));
536 start_reply(fds, c, TEMP_FAILURE, "internal server error");
541 start_reply(fds, c, SUCCESS, "text/gemini");
553 redirect_canonical_dir(struct pollfd *fds, struct client *c)
557 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
558 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
559 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
561 if (len >= sizeof(c->sbuf)) {
562 start_reply(fds, c, TEMP_FAILURE, "internal server error");
566 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
570 read_next_dir_entry(struct client *c)
576 if ((d = readdir(c->dir)) == NULL) {
578 LOGE(c, "readdir: %s", strerror(errno));
581 } while (!strcmp(d->d_name, "."));
583 /* XXX: url escape */
584 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
585 d->d_name, d->d_name);
586 c->len = strlen(c->sbuf);
593 send_directory_listing(struct pollfd *fds, struct client *c)
599 if (!read_next_dir_entry(c))
604 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
608 case TLS_WANT_POLLOUT:
609 fds->events = POLLOUT;
612 case TLS_WANT_POLLIN:
613 fds->events = POLLIN;
629 cgi_poll_on_child(struct pollfd *fds, struct client *c)
633 if (c->waiting_on_child)
635 c->waiting_on_child = 1;
637 fds->events = POLLIN;
645 cgi_poll_on_client(struct pollfd *fds, struct client *c)
649 if (!c->waiting_on_child)
651 c->waiting_on_child = 0;
658 /* handle the read from the child process. Return like read(2) */
660 read_from_cgi(struct client *c)
666 /* if we haven't read a whole response line, we want to
667 * continue reading. */
670 buf = c->sbuf + c->len;
671 len = sizeof(c->sbuf) - c->len;
674 len = sizeof(c->sbuf);
677 r = read(c->fd, buf, len);
678 if (r == 0 || r == -1)
687 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
689 log_request(c, c->sbuf, c->len);
696 handle_cgi(struct pollfd *fds, struct client *c)
700 /* ensure c->fd is the child and fds->fd the client */
701 cgi_poll_on_client(fds, c);
704 if (c->code == -1 || c->len == 0) {
705 switch (r = read_from_cgi(c)) {
710 if (errno == EAGAIN || errno == EWOULDBLOCK) {
711 cgi_poll_on_child(fds, c);
719 cgi_poll_on_child(fds, c);
724 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
728 case TLS_WANT_POLLOUT:
729 fds->events = POLLOUT;
732 case TLS_WANT_POLLIN:
733 fds->events = POLLIN;
749 close_conn(struct pollfd *pfd, struct client *c)
751 c->state = S_CLOSING;
753 switch (tls_close(c->ctx)) {
754 case TLS_WANT_POLLIN:
755 pfd->events = POLLIN;
757 case TLS_WANT_POLLOUT:
758 pfd->events = POLLOUT;
767 if (c->buf != MAP_FAILED)
768 munmap(c->buf, c->len);
781 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
784 struct sockaddr_storage addr;
788 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
789 if (errno == EWOULDBLOCK)
791 fatal("accept: %s", strerror(errno));
796 for (i = 0; i < MAX_USERS; ++i) {
797 if (fds[i].fd == -1) {
798 bzero(&clients[i], sizeof(struct client));
799 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
800 break; /* goodbye fd! */
803 fds[i].events = POLLIN;
805 clients[i].state = S_HANDSHAKE;
806 clients[i].next = S_SENDING_FILE;
808 clients[i].waiting_on_child = 0;
809 clients[i].buf = MAP_FAILED;
810 clients[i].dir = NULL;
811 clients[i].addr = addr;
822 handle(struct pollfd *fds, struct client *client)
824 switch (client->state) {
826 handle_handshake(fds, client);
830 handle_open_conn(fds, client);
834 start_reply(fds, client, client->code, client->meta);
838 send_file(fds, client);
842 send_directory_listing(fds, client);
846 handle_cgi(fds, client);
850 close_conn(fds, client);
860 loop(struct tls *ctx, int sock4, int sock6)
863 struct client clients[MAX_USERS];
864 struct pollfd fds[MAX_USERS];
866 connected_clients = 0;
868 for (i = 0; i < MAX_USERS; ++i) {
870 fds[i].events = POLLIN;
871 bzero(&clients[i], sizeof(struct client));
878 if (poll(fds, MAX_USERS, INFTIM) == -1) {
879 if (errno == EINTR) {
880 fprintf(stderr, "connected clients: %d\n",
884 fatal("poll: %s", strerror(errno));
887 for (i = 0; i < MAX_USERS; i++) {
888 if (fds[i].revents == 0)
891 if (fds[i].revents & (POLLERR|POLLNVAL))
892 fatal("bad fd %d: %s", fds[i].fd,
895 if (fds[i].revents & POLLHUP) {
896 /* fds[i] may be the fd of the stdin
897 * of a cgi script that has exited. */
898 if (!clients[i].waiting_on_child) {
899 close_conn(&fds[i], &clients[i]);
904 if (fds[i].fd == sock4)
905 do_accept(sock4, ctx, fds, clients);
906 else if (fds[i].fd == sock6)
907 do_accept(sock6, ctx, fds, clients);
909 handle(&fds[i], &clients[i]);