Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
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.
7 *
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.
15 */
17 #include <sys/mman.h>
18 #include <sys/stat.h>
20 #include <netdb.h>
22 #include <assert.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <fnmatch.h>
26 #include <string.h>
28 #include "gmid.h"
30 int connected_clients;
32 const char *
33 vhost_lang(struct vhost *v, const char *path)
34 {
35 struct location *loc;
36 const char *lang = NULL;
38 if (v == NULL || path == NULL)
39 return lang;
41 for (loc = v->locations; loc->match != NULL; ++loc) {
42 if (!fnmatch(loc->match, path, 0)) {
43 if (loc->lang != NULL)
44 lang = loc->lang;
45 }
46 }
48 return lang;
49 }
51 const char *
52 vhost_default_mime(struct vhost *v, const char *path)
53 {
54 struct location *loc;
55 const char *default_mime = "application/octet-stream";
57 if (v == NULL || path == NULL)
58 return default_mime;
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;
64 }
65 }
67 return default_mime;
68 }
70 const char *
71 vhost_index(struct vhost *v, const char *path)
72 {
73 struct location *loc;
74 const char *index = "index.gmi";
76 if (v == NULL || path == NULL)
77 return index;
79 for (loc = v->locations; loc->match != NULL; ++loc) {
80 if (!fnmatch(loc->match, path, 0)) {
81 if (loc->index != NULL)
82 index = loc->index;
83 }
84 }
86 return index;
87 }
89 int
90 vhost_auto_index(struct vhost *v, const char *path)
91 {
92 struct location *loc;
93 int auto_index = 0;
95 for (loc = v->locations; loc->match != NULL; ++loc) {
96 if (!fnmatch(loc->match, path, 0)) {
97 if (loc->auto_index)
98 auto_index = loc->auto_index;
99 }
102 return auto_index == 1;
105 int
106 check_path(struct client *c, const char *path, int *fd)
108 struct stat sb;
109 const char *p;
110 int flags;
112 assert(path != NULL);
114 if (*path == '\0')
115 p = ".";
116 else if (*path == '/')
117 /* in send_dir we add an initial / (to be
118 * redirect-friendly), but here we want to skip it */
119 p = path+1;
120 else
121 p = path;
123 flags = O_RDONLY | O_NOFOLLOW;
125 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
126 return FILE_MISSING;
128 if (fstat(*fd, &sb) == -1) {
129 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
130 return FILE_MISSING;
133 if (S_ISDIR(sb.st_mode))
134 return FILE_DIRECTORY;
136 if (sb.st_mode & S_IXUSR)
137 return FILE_EXECUTABLE;
139 return FILE_EXISTS;
142 void
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);
149 return;
152 /* fallthrough */
154 case FILE_EXISTS:
155 load_file(fds, c);
156 return;
158 case FILE_DIRECTORY:
159 open_dir(fds, c);
160 return;
162 case FILE_MISSING:
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);
165 return;
167 start_reply(fds, c, NOT_FOUND, "not found");
168 return;
170 default:
171 /* unreachable */
172 abort();
176 void
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");
182 return;
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");
189 return;
191 c->i = c->buf;
192 c->next = S_SENDING_FILE;
193 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
196 /*
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.
202 */
203 void
204 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
206 char *end;
207 end = strchr(path, '\0');
209 /* NB: assume CGI is enabled and path matches cgi */
211 while (end > path) {
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. */
215 while (*end != '/')
216 end--;
217 *end = '\0';
219 switch (check_path(c, path, &c->fd)) {
220 case FILE_EXECUTABLE:
221 start_cgi(path, end+1, query, fds,c);
222 return;
223 case FILE_MISSING:
224 break;
225 default:
226 goto err;
229 *end = '/';
230 end--;
233 err:
234 start_reply(fds, c, NOT_FOUND, "not found");
235 return;
238 void
239 mark_nonblock(int fd)
241 int flags;
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));
249 void
250 handle_handshake(struct pollfd *fds, struct client *c)
252 struct vhost *h;
253 const char *servname;
255 switch (tls_handshake(c->ctx)) {
256 case 0: /* success */
257 case -1: /* already handshaked */
258 break;
259 case TLS_WANT_POLLIN:
260 fds->events = POLLIN;
261 return;
262 case TLS_WANT_POLLOUT:
263 fds->events = POLLOUT;
264 return;
265 default:
266 /* unreachable */
267 abort();
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))
275 break;
278 LOGD(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
279 servname != NULL ? servname : "(null)",
280 c->domain,
281 h->domain != NULL ? h->domain : "(null)");
283 if (h->domain != NULL) {
284 c->state = S_OPEN;
285 c->host = h;
286 handle_open_conn(fds, c);
287 return;
290 if (servname != NULL)
291 strncpy(c->req, servname, sizeof(c->req));
292 else
293 strncpy(c->req, "null", sizeof(c->req));
295 start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
298 void
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)) {
308 case -1:
309 LOGE(c, "tls_read: %s", tls_error(c->ctx));
310 close_conn(fds, c);
311 return;
313 case TLS_WANT_POLLIN:
314 fds->events = POLLIN;
315 return;
317 case TLS_WANT_POLLOUT:
318 fds->events = POLLOUT;
319 return;
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");
326 return;
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");
335 return;
338 open_file(fds, c);
341 void
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 */
345 const char *lang;
346 size_t len;
348 c->code = code;
349 c->meta = meta;
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)) {
365 case -1:
366 close_conn(pfd, c);
367 return;
368 case TLS_WANT_POLLIN:
369 pfd->events = POLLIN;
370 return;
371 case TLS_WANT_POLLOUT:
372 pfd->events = POLLOUT;
373 return;
376 log_request(c, buf, sizeof(buf));
378 /* we don't need a body */
379 if (c->code != SUCCESS) {
380 close_conn(pfd, c);
381 return;
384 /* advance the state machine */
385 c->state = c->next;
386 handle(pfd, c);
389 void
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;
395 int e;
397 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
398 addr, sizeof(addr),
399 NULL, 0,
400 NI_NUMERICHOST);
401 if (e != 0)
402 goto err;
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);
408 } else {
409 ruser = NULL;
410 cissuer = NULL;
411 chash = NULL;
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))
422 goto err;
424 close(c->fd);
425 if ((c->fd = recv_fd(exfd)) == -1) {
426 start_reply(fds, c, TEMP_FAILURE, "internal server error");
427 return;
429 c->state = S_SENDING_CGI;
430 cgi_poll_on_child(fds, c);
431 c->code = -1;
432 /* handle_cgi(fds, c); */
433 return;
435 err:
436 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
437 fatal("cannot talk to the executor process");
440 void
441 send_file(struct pollfd *fds, struct client *c)
443 ssize_t ret, len;
445 /* ensure the correct state */
446 c->state = S_SENDING_FILE;
448 len = (c->buf + c->len) - c->i;
450 while (len > 0) {
451 switch (ret = tls_write(c->ctx, c->i, len)) {
452 case -1:
453 LOGE(c, "tls_write: %s", tls_error(c->ctx));
454 close_conn(fds, c);
455 return;
457 case TLS_WANT_POLLIN:
458 fds->events = POLLIN;
459 return;
461 case TLS_WANT_POLLOUT:
462 fds->events = POLLOUT;
463 return;
465 default:
466 c->i += ret;
467 len -= ret;
468 break;
472 close_conn(fds, c);
475 void
476 open_dir(struct pollfd *fds, struct client *c)
478 size_t len;
479 int dirfd;
480 char *before_file;
482 len = strlen(c->iri.path);
483 if (len > 0 && !ends_with(c->iri.path, "/")) {
484 redirect_canonical_dir(fds, c);
485 return;
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),
494 sizeof(c->sbuf));
495 if (len >= sizeof(c->sbuf)) {
496 start_reply(fds, c, TEMP_FAILURE, "internal server error");
497 return;
500 c->iri.path = c->sbuf;
502 /* close later unless we have to generate the dir listing */
503 dirfd = c->fd;
504 c->fd = -1;
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);
510 break;
513 /* fallthrough */
515 case FILE_EXISTS:
516 load_file(fds, c);
517 break;
519 case FILE_DIRECTORY:
520 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
521 break;
523 case FILE_MISSING:
524 *before_file = '\0';
526 if (!vhost_auto_index(c->host, c->iri.path)) {
527 start_reply(fds, c, NOT_FOUND, "not found");
528 break;
531 c->fd = dirfd;
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");
538 return;
540 c->off = 0;
542 start_reply(fds, c, SUCCESS, "text/gemini");
543 return;
545 default:
546 /* unreachable */
547 abort();
550 close(dirfd);
553 void
554 redirect_canonical_dir(struct pollfd *fds, struct client *c)
556 size_t len;
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");
564 return;
567 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
570 int
571 read_next_dir_entry(struct client *c)
573 struct dirent *d;
575 do {
576 errno = 0;
577 if ((d = readdir(c->dir)) == NULL) {
578 if (errno != 0)
579 LOGE(c, "readdir: %s", strerror(errno));
580 return 0;
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);
588 c->off = 0;
590 return 1;
593 void
594 send_directory_listing(struct pollfd *fds, struct client *c)
596 ssize_t r;
598 while (1) {
599 if (c->len == 0) {
600 if (!read_next_dir_entry(c))
601 goto end;
604 while (c->len > 0) {
605 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
606 case -1:
607 goto end;
609 case TLS_WANT_POLLOUT:
610 fds->events = POLLOUT;
611 return;
613 case TLS_WANT_POLLIN:
614 fds->events = POLLIN;
615 return;
617 default:
618 c->off += r;
619 c->len -= r;
620 break;
625 end:
626 close_conn(fds, c);
629 void
630 cgi_poll_on_child(struct pollfd *fds, struct client *c)
632 int fd;
634 if (c->waiting_on_child)
635 return;
636 c->waiting_on_child = 1;
638 fds->events = POLLIN;
640 fd = fds->fd;
641 fds->fd = c->fd;
642 c->fd = fd;
645 void
646 cgi_poll_on_client(struct pollfd *fds, struct client *c)
648 int fd;
650 if (!c->waiting_on_child)
651 return;
652 c->waiting_on_child = 0;
654 fd = fds->fd;
655 fds->fd = c->fd;
656 c->fd = fd;
659 /* handle the read from the child process. Return like read(2) */
660 static ssize_t
661 read_from_cgi(struct client *c)
663 void *buf;
664 size_t len;
665 ssize_t r;
667 /* if we haven't read a whole response line, we want to
668 * continue reading. */
670 if (c->code == -1) {
671 buf = c->sbuf + c->len;
672 len = sizeof(c->sbuf) - c->len;
673 } else {
674 buf = c->sbuf;
675 len = sizeof(c->sbuf);
678 r = read(c->fd, buf, len);
679 if (r == 0 || r == -1)
680 return r;
682 c->len += r;
683 c->off = 0;
685 if (c->code != -1)
686 return r;
688 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
689 c->code = 0;
690 log_request(c, c->sbuf, c->len);
693 return r;
696 void
697 handle_cgi(struct pollfd *fds, struct client *c)
699 ssize_t r;
701 /* ensure c->fd is the child and fds->fd the client */
702 cgi_poll_on_client(fds, c);
704 while (1) {
705 if (c->code == -1 || c->len == 0) {
706 switch (r = read_from_cgi(c)) {
707 case 0:
708 goto end;
710 case -1:
711 if (errno == EAGAIN || errno == EWOULDBLOCK) {
712 cgi_poll_on_child(fds, c);
713 return;
715 goto end;
719 if (c->code == -1) {
720 cgi_poll_on_child(fds, c);
721 return;
724 while (c->len > 0) {
725 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
726 case -1:
727 goto end;
729 case TLS_WANT_POLLOUT:
730 fds->events = POLLOUT;
731 return;
733 case TLS_WANT_POLLIN:
734 fds->events = POLLIN;
735 return;
737 default:
738 c->off += r;
739 c->len -= r;
740 break;
745 end:
746 close_conn(fds, c);
749 void
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;
757 return;
758 case TLS_WANT_POLLOUT:
759 pfd->events = POLLOUT;
760 return;
763 connected_clients--;
765 tls_free(c->ctx);
766 c->ctx = NULL;
768 if (c->buf != MAP_FAILED)
769 munmap(c->buf, c->len);
771 if (c->fd != -1)
772 close(c->fd);
774 if (c->dir != NULL)
775 closedir(c->dir);
777 close(pfd->fd);
778 pfd->fd = -1;
781 void
782 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
784 int i, fd;
785 struct sockaddr_storage addr;
786 socklen_t len;
788 len = sizeof(addr);
789 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
790 if (errno == EWOULDBLOCK)
791 return;
792 fatal("accept: %s", strerror(errno));
795 mark_nonblock(fd);
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! */
803 fds[i].fd = fd;
804 fds[i].events = POLLIN;
806 clients[i].state = S_HANDSHAKE;
807 clients[i].next = S_SENDING_FILE;
808 clients[i].fd = -1;
809 clients[i].waiting_on_child = 0;
810 clients[i].buf = MAP_FAILED;
811 clients[i].dir = NULL;
812 clients[i].addr = addr;
814 connected_clients++;
815 return;
819 close(fd);
822 void
823 handle(struct pollfd *fds, struct client *client)
825 switch (client->state) {
826 case S_HANDSHAKE:
827 handle_handshake(fds, client);
828 break;
830 case S_OPEN:
831 handle_open_conn(fds, client);
832 break;
834 case S_INITIALIZING:
835 start_reply(fds, client, client->code, client->meta);
836 break;
838 case S_SENDING_FILE:
839 send_file(fds, client);
840 break;
842 case S_SENDING_DIR:
843 send_directory_listing(fds, client);
844 break;
846 case S_SENDING_CGI:
847 handle_cgi(fds, client);
848 break;
850 case S_CLOSING:
851 close_conn(fds, client);
852 break;
854 default:
855 /* unreachable */
856 abort();
860 void
861 loop(struct tls *ctx, int sock4, int sock6)
863 int i;
864 struct client clients[MAX_USERS];
865 struct pollfd fds[MAX_USERS];
867 connected_clients = 0;
869 for (i = 0; i < MAX_USERS; ++i) {
870 fds[i].fd = -1;
871 fds[i].events = POLLIN;
872 bzero(&clients[i], sizeof(struct client));
875 fds[0].fd = sock4;
876 fds[1].fd = sock6;
878 for (;;) {
879 if (poll(fds, MAX_USERS, INFTIM) == -1) {
880 if (errno == EINTR) {
881 fprintf(stderr, "connected clients: %d\n",
882 connected_clients);
883 continue;
885 fatal("poll: %s", strerror(errno));
888 for (i = 0; i < MAX_USERS; i++) {
889 if (fds[i].revents == 0)
890 continue;
892 if (fds[i].revents & (POLLERR|POLLNVAL))
893 fatal("bad fd %d: %s", fds[i].fd,
894 strerror(errno));
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]);
901 continue;
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);
909 else
910 handle(&fds[i], &clients[i]);