2 * Copyright (c) 2020 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.
18 #include <sys/socket.h>
21 #include <netinet/in.h>
36 # define pledge(a, b) 0
37 # define unveil(a, b) 0
38 #endif /* __OpenBSD__ */
44 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
46 /* large enough to hold a copy of a gemini URL and still have extra room */
51 #define BAD_REQUEST 59
74 struct etm { /* file extension to mime */
78 {"application/pdf", "pdf"},
81 {"image/jpeg", "jpg"},
82 {"image/jpeg", "jpeg"},
84 {"image/svg+xml", "svg"},
86 {"text/gemini", "gemini"},
87 {"text/gemini", "gmi"},
88 {"text/markdown", "markdown"},
89 {"text/markdown", "md"},
90 {"text/plain", "txt"},
97 char *url_after_proto(char*);
98 char *url_start_of_request(char*);
100 void adjust_path(char*);
101 int path_isdir(char*);
102 ssize_t filesize(int);
104 int start_reply(struct pollfd*, struct client*, int, const char*);
106 const char *path_ext(const char*);
107 const char *mime(const char*);
108 int open_file(char*, struct pollfd*, struct client*);
109 void send_file(char*, struct pollfd*, struct client*);
110 void send_dir(char*, struct pollfd*, struct client*);
111 void handle(struct pollfd*, struct client*);
113 void mark_nonblock(int);
115 void do_accept(int, struct tls*, struct pollfd*, struct client*);
116 void goodbye(struct pollfd*, struct client*);
117 void loop(struct tls*, int);
119 void usage(const char*);
122 url_after_proto(char *url)
125 const char *proto = "gemini";
126 const char *marker = "://";
128 if ((s = strstr(url, marker)) == NULL)
131 /* not a gemini:// URL */
133 if (s - strlen(proto) < url)
136 /* if (strcmp(s - strlen(proto), proto)) */
139 /* a valid gemini:// URL */
140 return s + strlen(marker);
144 url_start_of_request(char *url)
148 if ((s = url_after_proto(url)) == NULL)
151 if ((t = strstr(s, "/")) == NULL)
152 return s + strlen(s);
159 const char *e = "\r\n";
162 if ((s = strstr(url, e)) == NULL)
168 fprintf(stderr, "the request was longer than 1024 bytes\n");
176 adjust_path(char *path)
184 if (!strcmp(&path[len-3], "/..")) {
189 /* if the path is only `..` trim out and exit */
190 if (!strcmp(path, "..")) {
195 /* remove every ../ in the path */
197 if ((s = strstr(path, "../")) == NULL)
199 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
204 path_isdir(char *path)
208 return path[strlen(path)-1] == '/';
212 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
214 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
219 client->meta = reason;
220 client->state = S_INITIALIZING;
222 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
223 assert(len < (int)sizeof(buf));
224 ret = tls_write(client->ctx, buf, len);
225 if (ret == TLS_WANT_POLLIN) {
226 pfd->events = POLLIN;
230 if (ret == TLS_WANT_POLLOUT) {
231 pfd->events = POLLOUT;
243 if (fstat(fd, &sb) == -1) {
245 return 1; /* we'll probably fail later on anyway */
248 return S_ISDIR(sb.st_mode);
256 if ((len = lseek(fd, 0, SEEK_END)) == -1)
258 if (lseek(fd, 0, SEEK_SET) == -1)
264 path_ext(const char *path)
268 end = path + strlen(path)-1; /* the last byte before the NUL */
269 for (; end != path; --end) {
280 mime(const char *path)
282 const char *ext, *def = "application/octet-stream";
285 if ((ext = path_ext(path)) == NULL)
288 for (t = filetypes; t->mime != NULL; ++t)
289 if (!strcmp(ext, t->ext))
296 open_file(char *path, struct pollfd *fds, struct client *c)
300 assert(path != NULL);
302 bzero(fpath, sizeof(fpath));
306 strlcat(fpath, path, PATHBUF);
308 if ((c->fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
309 warn("open: %s", fpath);
310 if (!start_reply(fds, c, NOT_FOUND, "not found"))
317 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
320 send_dir(fpath, fds, c);
324 if ((c->len = filesize(c->fd)) == -1) {
325 warn("filesize: %s", fpath);
330 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
331 c->fd, 0)) == MAP_FAILED) {
332 warn("mmap: %s", fpath);
338 return start_reply(fds, c, SUCCESS, mime(fpath));
342 send_file(char *path, struct pollfd *fds, struct client *c)
347 if (!open_file(path, fds, c))
349 c->state = S_SENDING;
352 len = (c->buf + c->len) - c->i;
355 switch (ret = tls_write(c->ctx, c->i, len)) {
357 warnx("tls_write: %s", tls_error(c->ctx));
361 case TLS_WANT_POLLIN:
362 fds->events = POLLIN;
365 case TLS_WANT_POLLOUT:
366 fds->events = POLLOUT;
380 send_dir(char *path, struct pollfd *fds, struct client *client)
385 bzero(fpath, PATHBUF);
390 /* this cannot fail since sizeof(fpath) > maxlen of path */
391 strlcat(fpath, path, PATHBUF);
394 /* add a trailing / in case. */
395 if (fpath[len-1] != '/') {
399 strlcat(fpath, "index.gmi", sizeof(fpath));
401 send_file(fpath, fds, client);
405 handle(struct pollfd *fds, struct client *client)
407 char buf[GEMINI_URL_LEN];
410 switch (client->state) {
412 bzero(buf, GEMINI_URL_LEN);
413 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
415 warnx("tls_read: %s", tls_error(client->ctx));
416 goodbye(fds, client);
419 case TLS_WANT_POLLIN:
420 fds->events = POLLIN;
423 case TLS_WANT_POLLOUT:
424 fds->events = POLLOUT;
428 if (!url_trim(buf)) {
429 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
431 goodbye(fds, client);
435 if ((path = url_start_of_request(buf)) == NULL) {
436 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
438 goodbye(fds, client);
443 fprintf(stderr, "requested path: %s\n", path);
445 if (path_isdir(path))
446 send_dir(path, fds, client);
448 send_file(path, fds, client);
452 if (!start_reply(fds, client, client->code, client->meta))
455 if (client->code != SUCCESS) {
456 /* we don't need a body */
457 goodbye(fds, client);
461 client->state = S_SENDING;
466 send_file(NULL, fds, client);
470 goodbye(fds, client);
480 mark_nonblock(int fd)
484 if ((flags = fcntl(fd, F_GETFL)) == -1)
485 err(1, "fcntl(F_GETFL)");
486 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
487 err(1, "fcntl(F_SETFL)");
491 make_socket(int port, int family)
494 struct sockaddr_in addr4;
495 struct sockaddr_in6 addr6;
496 struct sockaddr *addr;
501 bzero(&addr4, sizeof(addr4));
502 addr4.sin_family = family;
503 addr4.sin_port = htons(port);
504 addr4.sin_addr.s_addr = INADDR_ANY;
505 addr = (struct sockaddr*)&addr4;
510 bzero(&addr6, sizeof(addr6));
511 addr6.sin6_family = AF_INET6;
512 addr6.sin6_port = htons(port);
513 addr6.sin6_addr = in6addr_any;
514 addr = (struct sockaddr*)&addr6;
523 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
527 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
528 err(1, "setsockopt(SO_REUSEADDR)");
531 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
532 err(1, "setsockopt(SO_REUSEPORT)");
536 if (bind(sock, addr, len) == -1)
539 if (listen(sock, 16) == -1)
546 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
549 struct sockaddr_in addr;
553 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
554 if (errno == EWOULDBLOCK)
561 for (i = 0; i < MAX_USERS; ++i) {
562 if (fds[i].fd == -1) {
563 bzero(&clients[i], sizeof(struct client));
564 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
565 break; /* goodbye fd! */
568 fds[i].events = POLLIN;
570 clients[i].state = S_OPEN;
572 clients[i].buf = MAP_FAILED;
582 goodbye(struct pollfd *pfd, struct client *c)
586 c->state = S_CLOSING;
588 ret = tls_close(c->ctx);
589 if (ret == TLS_WANT_POLLIN) {
590 pfd->events = POLLIN;
593 if (ret == TLS_WANT_POLLOUT) {
594 pfd->events = POLLOUT;
601 if (c->buf != MAP_FAILED)
602 munmap(c->buf, c->len);
612 loop(struct tls *ctx, int sock)
615 struct client clients[MAX_USERS];
616 struct pollfd fds[MAX_USERS];
618 for (i = 0; i < MAX_USERS; ++i) {
620 fds[i].events = POLLIN;
621 bzero(&clients[i], sizeof(struct client));
627 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
630 for (i = 0; i < MAX_USERS; i++) {
631 assert(i < MAX_USERS);
633 if (fds[i].revents == 0)
636 if (fds[i].revents & (POLLERR|POLLNVAL))
637 err(1, "bad fd %d", fds[i].fd);
639 if (fds[i].revents & POLLHUP) {
640 goodbye(&fds[i], &clients[i]);
646 if (i == 0) { /* new client */
647 do_accept(sock, ctx, fds, clients);
651 handle(&fds[i], &clients[i]);
657 usage(const char *me)
660 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
665 main(int argc, char **argv)
667 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
668 struct tls *ctx = NULL;
669 struct tls_config *conf;
672 signal(SIGPIPE, SIG_IGN);
674 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
698 if ((conf = tls_config_new()) == NULL)
699 err(1, "tls_config_new");
701 if (tls_config_set_protocols(conf,
702 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
703 err(1, "tls_config_set_protocols");
705 if (tls_config_set_cert_file(conf, cert) == -1)
706 err(1, "tls_config_set_cert_file: %s", cert);
708 if (tls_config_set_key_file(conf, key) == -1)
709 err(1, "tls_config_set_key_file: %s", key);
711 if ((ctx = tls_server()) == NULL)
712 err(1, "tls_server");
714 if (tls_configure(ctx, conf) == -1)
715 errx(1, "tls_configure: %s", tls_error(ctx));
717 sock = make_socket(1965, AF_INET);
719 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
720 err(1, "open: %s", dir);
722 if (unveil(dir, "r") == -1)
725 if (pledge("stdio rpath inet", "") == -1)
732 tls_config_free(conf);