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 || !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");
327 return;
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");
334 return;
337 open_file(fds, c);
340 void
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 */
344 const char *lang;
345 size_t len;
347 c->code = code;
348 c->meta = meta;
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)) {
364 case -1:
365 close_conn(pfd, c);
366 return;
367 case TLS_WANT_POLLIN:
368 pfd->events = POLLIN;
369 return;
370 case TLS_WANT_POLLOUT:
371 pfd->events = POLLOUT;
372 return;
375 log_request(c, buf, sizeof(buf));
377 /* we don't need a body */
378 if (c->code != SUCCESS) {
379 close_conn(pfd, c);
380 return;
383 /* advance the state machine */
384 c->state = c->next;
385 handle(pfd, c);
388 void
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;
394 int e;
396 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
397 addr, sizeof(addr),
398 NULL, 0,
399 NI_NUMERICHOST);
400 if (e != 0)
401 goto err;
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);
407 } else {
408 ruser = NULL;
409 cissuer = NULL;
410 chash = NULL;
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))
421 goto err;
423 close(c->fd);
424 if ((c->fd = recv_fd(exfd)) == -1) {
425 start_reply(fds, c, TEMP_FAILURE, "internal server error");
426 return;
428 c->state = S_SENDING_CGI;
429 cgi_poll_on_child(fds, c);
430 c->code = -1;
431 /* handle_cgi(fds, c); */
432 return;
434 err:
435 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
436 fatal("cannot talk to the executor process");
439 void
440 send_file(struct pollfd *fds, struct client *c)
442 ssize_t ret, len;
444 /* ensure the correct state */
445 c->state = S_SENDING_FILE;
447 len = (c->buf + c->len) - c->i;
449 while (len > 0) {
450 switch (ret = tls_write(c->ctx, c->i, len)) {
451 case -1:
452 LOGE(c, "tls_write: %s", tls_error(c->ctx));
453 close_conn(fds, c);
454 return;
456 case TLS_WANT_POLLIN:
457 fds->events = POLLIN;
458 return;
460 case TLS_WANT_POLLOUT:
461 fds->events = POLLOUT;
462 return;
464 default:
465 c->i += ret;
466 len -= ret;
467 break;
471 close_conn(fds, c);
474 void
475 open_dir(struct pollfd *fds, struct client *c)
477 size_t len;
478 int dirfd;
479 char *before_file;
481 len = strlen(c->iri.path);
482 if (len > 0 && !ends_with(c->iri.path, "/")) {
483 redirect_canonical_dir(fds, c);
484 return;
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),
493 sizeof(c->sbuf));
494 if (len >= sizeof(c->sbuf)) {
495 start_reply(fds, c, TEMP_FAILURE, "internal server error");
496 return;
499 c->iri.path = c->sbuf;
501 /* close later unless we have to generate the dir listing */
502 dirfd = c->fd;
503 c->fd = -1;
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);
509 break;
512 /* fallthrough */
514 case FILE_EXISTS:
515 load_file(fds, c);
516 break;
518 case FILE_DIRECTORY:
519 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
520 break;
522 case FILE_MISSING:
523 *before_file = '\0';
525 if (!vhost_auto_index(c->host, c->iri.path)) {
526 start_reply(fds, c, NOT_FOUND, "not found");
527 break;
530 c->fd = dirfd;
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");
537 return;
539 c->off = 0;
541 start_reply(fds, c, SUCCESS, "text/gemini");
542 return;
544 default:
545 /* unreachable */
546 abort();
549 close(dirfd);
552 void
553 redirect_canonical_dir(struct pollfd *fds, struct client *c)
555 size_t len;
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");
563 return;
566 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
569 int
570 read_next_dir_entry(struct client *c)
572 struct dirent *d;
574 do {
575 errno = 0;
576 if ((d = readdir(c->dir)) == NULL) {
577 if (errno != 0)
578 LOGE(c, "readdir: %s", strerror(errno));
579 return 0;
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);
587 c->off = 0;
589 return 1;
592 void
593 send_directory_listing(struct pollfd *fds, struct client *c)
595 ssize_t r;
597 while (1) {
598 if (c->len == 0) {
599 if (!read_next_dir_entry(c))
600 goto end;
603 while (c->len > 0) {
604 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
605 case -1:
606 goto end;
608 case TLS_WANT_POLLOUT:
609 fds->events = POLLOUT;
610 return;
612 case TLS_WANT_POLLIN:
613 fds->events = POLLIN;
614 return;
616 default:
617 c->off += r;
618 c->len -= r;
619 break;
624 end:
625 close_conn(fds, c);
628 void
629 cgi_poll_on_child(struct pollfd *fds, struct client *c)
631 int fd;
633 if (c->waiting_on_child)
634 return;
635 c->waiting_on_child = 1;
637 fds->events = POLLIN;
639 fd = fds->fd;
640 fds->fd = c->fd;
641 c->fd = fd;
644 void
645 cgi_poll_on_client(struct pollfd *fds, struct client *c)
647 int fd;
649 if (!c->waiting_on_child)
650 return;
651 c->waiting_on_child = 0;
653 fd = fds->fd;
654 fds->fd = c->fd;
655 c->fd = fd;
658 /* handle the read from the child process. Return like read(2) */
659 static ssize_t
660 read_from_cgi(struct client *c)
662 void *buf;
663 size_t len;
664 ssize_t r;
666 /* if we haven't read a whole response line, we want to
667 * continue reading. */
669 if (c->code == -1) {
670 buf = c->sbuf + c->len;
671 len = sizeof(c->sbuf) - c->len;
672 } else {
673 buf = c->sbuf;
674 len = sizeof(c->sbuf);
677 r = read(c->fd, buf, len);
678 if (r == 0 || r == -1)
679 return r;
681 c->len += r;
682 c->off = 0;
684 if (c->code != -1)
685 return r;
687 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
688 c->code = 0;
689 log_request(c, c->sbuf, c->len);
692 return r;
695 void
696 handle_cgi(struct pollfd *fds, struct client *c)
698 ssize_t r;
700 /* ensure c->fd is the child and fds->fd the client */
701 cgi_poll_on_client(fds, c);
703 while (1) {
704 if (c->code == -1 || c->len == 0) {
705 switch (r = read_from_cgi(c)) {
706 case 0:
707 goto end;
709 case -1:
710 if (errno == EAGAIN || errno == EWOULDBLOCK) {
711 cgi_poll_on_child(fds, c);
712 return;
714 goto end;
718 if (c->code == -1) {
719 cgi_poll_on_child(fds, c);
720 return;
723 while (c->len > 0) {
724 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
725 case -1:
726 goto end;
728 case TLS_WANT_POLLOUT:
729 fds->events = POLLOUT;
730 return;
732 case TLS_WANT_POLLIN:
733 fds->events = POLLIN;
734 return;
736 default:
737 c->off += r;
738 c->len -= r;
739 break;
744 end:
745 close_conn(fds, c);
748 void
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;
756 return;
757 case TLS_WANT_POLLOUT:
758 pfd->events = POLLOUT;
759 return;
762 connected_clients--;
764 tls_free(c->ctx);
765 c->ctx = NULL;
767 if (c->buf != MAP_FAILED)
768 munmap(c->buf, c->len);
770 if (c->fd != -1)
771 close(c->fd);
773 if (c->dir != NULL)
774 closedir(c->dir);
776 close(pfd->fd);
777 pfd->fd = -1;
780 void
781 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
783 int i, fd;
784 struct sockaddr_storage addr;
785 socklen_t len;
787 len = sizeof(addr);
788 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
789 if (errno == EWOULDBLOCK)
790 return;
791 fatal("accept: %s", strerror(errno));
794 mark_nonblock(fd);
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! */
802 fds[i].fd = fd;
803 fds[i].events = POLLIN;
805 clients[i].state = S_HANDSHAKE;
806 clients[i].next = S_SENDING_FILE;
807 clients[i].fd = -1;
808 clients[i].waiting_on_child = 0;
809 clients[i].buf = MAP_FAILED;
810 clients[i].dir = NULL;
811 clients[i].addr = addr;
813 connected_clients++;
814 return;
818 close(fd);
821 void
822 handle(struct pollfd *fds, struct client *client)
824 switch (client->state) {
825 case S_HANDSHAKE:
826 handle_handshake(fds, client);
827 break;
829 case S_OPEN:
830 handle_open_conn(fds, client);
831 break;
833 case S_INITIALIZING:
834 start_reply(fds, client, client->code, client->meta);
835 break;
837 case S_SENDING_FILE:
838 send_file(fds, client);
839 break;
841 case S_SENDING_DIR:
842 send_directory_listing(fds, client);
843 break;
845 case S_SENDING_CGI:
846 handle_cgi(fds, client);
847 break;
849 case S_CLOSING:
850 close_conn(fds, client);
851 break;
853 default:
854 /* unreachable */
855 abort();
859 void
860 loop(struct tls *ctx, int sock4, int sock6)
862 int i;
863 struct client clients[MAX_USERS];
864 struct pollfd fds[MAX_USERS];
866 connected_clients = 0;
868 for (i = 0; i < MAX_USERS; ++i) {
869 fds[i].fd = -1;
870 fds[i].events = POLLIN;
871 bzero(&clients[i], sizeof(struct client));
874 fds[0].fd = sock4;
875 fds[1].fd = sock6;
877 for (;;) {
878 if (poll(fds, MAX_USERS, INFTIM) == -1) {
879 if (errno == EINTR) {
880 fprintf(stderr, "connected clients: %d\n",
881 connected_clients);
882 continue;
884 fatal("poll: %s", strerror(errno));
887 for (i = 0; i < MAX_USERS; i++) {
888 if (fds[i].revents == 0)
889 continue;
891 if (fds[i].revents & (POLLERR|POLLNVAL))
892 fatal("bad fd %d: %s", fds[i].fd,
893 strerror(errno));
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]);
900 continue;
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);
908 else
909 handle(&fds[i], &clients[i]);