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"},
98 char *url_after_proto(char*);
99 char *url_start_of_request(char*);
101 void adjust_path(char*);
102 int path_isdir(char*);
103 ssize_t filesize(int);
105 int start_reply(struct pollfd*, struct client*, int, const char*);
107 const char *path_ext(const char*);
108 const char *mime(const char*);
109 int open_file(char*, struct pollfd*, struct client*);
110 void send_file(char*, struct pollfd*, struct client*);
111 void send_dir(char*, struct pollfd*, struct client*);
112 void handle(struct pollfd*, struct client*);
114 void mark_nonblock(int);
116 void do_accept(int, struct tls*, struct pollfd*, struct client*);
117 void goodbye(struct pollfd*, struct client*);
118 void loop(struct tls*, int);
120 void usage(const char*);
123 url_after_proto(char *url)
126 const char *proto = "gemini";
127 const char *marker = "://";
129 if ((s = strstr(url, marker)) == NULL)
132 /* not a gemini:// URL */
134 if (s - strlen(proto) < url)
137 /* if (strcmp(s - strlen(proto), proto)) */
140 /* a valid gemini:// URL */
141 return s + strlen(marker);
145 url_start_of_request(char *url)
149 if ((s = url_after_proto(url)) == NULL)
152 if ((t = strstr(s, "/")) == NULL)
153 return s + strlen(s);
160 const char *e = "\r\n";
163 if ((s = strstr(url, e)) == NULL)
169 fprintf(stderr, "the request was longer than 1024 bytes\n");
177 adjust_path(char *path)
185 if (!strcmp(&path[len-3], "/..")) {
190 /* if the path is only `..` trim out and exit */
191 if (!strcmp(path, "..")) {
196 /* remove every ../ in the path */
198 if ((s = strstr(path, "../")) == NULL)
200 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
205 path_isdir(char *path)
209 return path[strlen(path)-1] == '/';
213 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
215 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
220 client->meta = reason;
221 client->state = S_INITIALIZING;
223 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
224 assert(len < (int)sizeof(buf));
225 ret = tls_write(client->ctx, buf, len);
226 if (ret == TLS_WANT_POLLIN) {
227 pfd->events = POLLIN;
231 if (ret == TLS_WANT_POLLOUT) {
232 pfd->events = POLLOUT;
244 if (fstat(fd, &sb) == -1) {
246 return 1; /* we'll probably fail later on anyway */
249 return S_ISDIR(sb.st_mode);
257 if ((len = lseek(fd, 0, SEEK_END)) == -1)
259 if (lseek(fd, 0, SEEK_SET) == -1)
265 path_ext(const char *path)
269 end = path + strlen(path)-1; /* the last byte before the NUL */
270 for (; end != path; --end) {
281 mime(const char *path)
283 const char *ext, *def = "application/octet-stream";
286 if ((ext = path_ext(path)) == NULL)
289 for (t = filetypes; t->mime != NULL; ++t)
290 if (!strcmp(ext, t->ext))
297 open_file(char *path, struct pollfd *fds, struct client *c)
301 assert(path != NULL);
303 bzero(fpath, sizeof(fpath));
307 strlcat(fpath, path, PATHBUF);
309 if ((c->fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
310 warn("open: %s", fpath);
311 if (!start_reply(fds, c, NOT_FOUND, "not found"))
318 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
321 send_dir(fpath, fds, c);
325 if ((c->len = filesize(c->fd)) == -1) {
326 warn("filesize: %s", fpath);
331 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
332 c->fd, 0)) == MAP_FAILED) {
333 warn("mmap: %s", fpath);
339 return start_reply(fds, c, SUCCESS, mime(fpath));
343 send_file(char *path, struct pollfd *fds, struct client *c)
348 if (!open_file(path, fds, c))
350 c->state = S_SENDING;
353 len = (c->buf + c->len) - c->i;
356 switch (ret = tls_write(c->ctx, c->i, len)) {
358 warnx("tls_write: %s", tls_error(c->ctx));
362 case TLS_WANT_POLLIN:
363 fds->events = POLLIN;
366 case TLS_WANT_POLLOUT:
367 fds->events = POLLOUT;
381 send_dir(char *path, struct pollfd *fds, struct client *client)
386 bzero(fpath, PATHBUF);
391 /* this cannot fail since sizeof(fpath) > maxlen of path */
392 strlcat(fpath, path, PATHBUF);
395 /* add a trailing / in case. */
396 if (fpath[len-1] != '/') {
400 strlcat(fpath, "index.gmi", sizeof(fpath));
402 send_file(fpath, fds, client);
406 handle(struct pollfd *fds, struct client *client)
408 char buf[GEMINI_URL_LEN];
411 switch (client->state) {
413 bzero(buf, GEMINI_URL_LEN);
414 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
416 warnx("tls_read: %s", tls_error(client->ctx));
417 goodbye(fds, client);
420 case TLS_WANT_POLLIN:
421 fds->events = POLLIN;
424 case TLS_WANT_POLLOUT:
425 fds->events = POLLOUT;
429 if (!url_trim(buf)) {
430 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
432 goodbye(fds, client);
436 if ((path = url_start_of_request(buf)) == NULL) {
437 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
439 goodbye(fds, client);
444 fprintf(stderr, "requested path: %s\n", path);
446 if (path_isdir(path))
447 send_dir(path, fds, client);
449 send_file(path, fds, client);
453 if (!start_reply(fds, client, client->code, client->meta))
456 if (client->code != SUCCESS) {
457 /* we don't need a body */
458 goodbye(fds, client);
462 client->state = S_SENDING;
467 send_file(NULL, fds, client);
471 goodbye(fds, client);
481 mark_nonblock(int fd)
485 if ((flags = fcntl(fd, F_GETFL)) == -1)
486 err(1, "fcntl(F_GETFL)");
487 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
488 err(1, "fcntl(F_SETFL)");
492 make_socket(int port, int family)
495 struct sockaddr_in addr4;
496 struct sockaddr_in6 addr6;
497 struct sockaddr *addr;
502 bzero(&addr4, sizeof(addr4));
503 addr4.sin_family = family;
504 addr4.sin_port = htons(port);
505 addr4.sin_addr.s_addr = INADDR_ANY;
506 addr = (struct sockaddr*)&addr4;
511 bzero(&addr6, sizeof(addr6));
512 addr6.sin6_family = AF_INET6;
513 addr6.sin6_port = htons(port);
514 addr6.sin6_addr = in6addr_any;
515 addr = (struct sockaddr*)&addr6;
524 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
528 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
529 err(1, "setsockopt(SO_REUSEADDR)");
532 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
533 err(1, "setsockopt(SO_REUSEPORT)");
537 if (bind(sock, addr, len) == -1)
540 if (listen(sock, 16) == -1)
547 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
550 struct sockaddr_in addr;
554 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
555 if (errno == EWOULDBLOCK)
562 for (i = 0; i < MAX_USERS; ++i) {
563 if (fds[i].fd == -1) {
564 bzero(&clients[i], sizeof(struct client));
565 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
566 break; /* goodbye fd! */
569 fds[i].events = POLLIN;
571 clients[i].state = S_OPEN;
573 clients[i].buf = MAP_FAILED;
583 goodbye(struct pollfd *pfd, struct client *c)
587 c->state = S_CLOSING;
589 ret = tls_close(c->ctx);
590 if (ret == TLS_WANT_POLLIN) {
591 pfd->events = POLLIN;
594 if (ret == TLS_WANT_POLLOUT) {
595 pfd->events = POLLOUT;
602 if (c->buf != MAP_FAILED)
603 munmap(c->buf, c->len);
613 loop(struct tls *ctx, int sock)
616 struct client clients[MAX_USERS];
617 struct pollfd fds[MAX_USERS];
619 for (i = 0; i < MAX_USERS; ++i) {
621 fds[i].events = POLLIN;
622 bzero(&clients[i], sizeof(struct client));
628 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
631 for (i = 0; i < MAX_USERS; i++) {
632 assert(i < MAX_USERS);
634 if (fds[i].revents == 0)
637 if (fds[i].revents & (POLLERR|POLLNVAL))
638 err(1, "bad fd %d", fds[i].fd);
640 if (fds[i].revents & POLLHUP) {
641 goodbye(&fds[i], &clients[i]);
647 if (i == 0) { /* new client */
648 do_accept(sock, ctx, fds, clients);
652 handle(&fds[i], &clients[i]);
658 usage(const char *me)
661 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
666 main(int argc, char **argv)
668 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
669 struct tls *ctx = NULL;
670 struct tls_config *conf;
673 signal(SIGPIPE, SIG_IGN);
675 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
699 if ((conf = tls_config_new()) == NULL)
700 err(1, "tls_config_new");
702 if (tls_config_set_protocols(conf,
703 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
704 err(1, "tls_config_set_protocols");
706 if (tls_config_set_cert_file(conf, cert) == -1)
707 err(1, "tls_config_set_cert_file: %s", cert);
709 if (tls_config_set_key_file(conf, key) == -1)
710 err(1, "tls_config_set_key_file: %s", key);
712 if ((ctx = tls_server()) == NULL)
713 err(1, "tls_server");
715 if (tls_configure(ctx, conf) == -1)
716 errx(1, "tls_configure: %s", tls_error(ctx));
718 sock = make_socket(1965, AF_INET);
720 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
721 err(1, "open: %s", dir);
723 if (unveil(dir, "r") == -1)
726 if (pledge("stdio rpath inet", "") == -1)
733 tls_config_free(conf);