Blob


1 /*
2 * Copyright (c) 2020 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/socket.h>
19 #include <sys/stat.h>
21 #include <netinet/in.h>
23 #include <assert.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <poll.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <tls.h>
33 #include <unistd.h>
35 #ifndef __OpenBSD__
36 # define pledge(a, b) 0
37 # define unveil(a, b) 0
38 #endif /* __OpenBSD__ */
40 #ifndef INFTIM
41 # define INFTIM -1
42 #endif /* INFTIM */
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 */
47 #define PATHBUF 2048
49 #define SUCCESS 20
50 #define NOT_FOUND 51
51 #define BAD_REQUEST 59
53 #ifndef MAX_USERS
54 #define MAX_USERS 64
55 #endif
57 enum {
58 S_OPEN,
59 S_INITIALIZING,
60 S_SENDING,
61 S_CLOSING,
62 };
64 struct client {
65 struct tls *ctx;
66 int state;
67 int code;
68 const char *meta;
69 int fd;
70 void *buf, *i;
71 ssize_t len, off;
72 };
74 struct etm { /* file extension to mime */
75 const char *mime;
76 const char *ext;
77 } filetypes[] = {
78 {"application/pdf", "pdf"},
80 {"image/gif", "gif"},
81 {"image/jpeg", "jpg"},
82 {"image/jpeg", "jpeg"},
83 {"image/png", "png"},
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"},
92 {NULL, NULL}
93 };
95 int dirfd;
97 char *url_after_proto(char*);
98 char *url_start_of_request(char*);
99 int url_trim(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*);
105 int isdir(int);
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);
114 int make_soket(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*);
121 char *
122 url_after_proto(char *url)
124 char *s;
125 const char *proto = "gemini";
126 const char *marker = "://";
128 if ((s = strstr(url, marker)) == NULL)
129 return url;
131 /* not a gemini:// URL */
133 if (s - strlen(proto) < url)
134 return NULL;
135 /* TODO: */
136 /* if (strcmp(s - strlen(proto), proto)) */
137 /* return NULL; */
139 /* a valid gemini:// URL */
140 return s + strlen(marker);
143 char *
144 url_start_of_request(char *url)
146 char *s, *t;
148 if ((s = url_after_proto(url)) == NULL)
149 return NULL;
151 if ((t = strstr(s, "/")) == NULL)
152 return s + strlen(s);
153 return t;
156 int
157 url_trim(char *url)
159 const char *e = "\r\n";
160 char *s;
162 if ((s = strstr(url, e)) == NULL)
163 return 0;
164 s[0] = '\0';
165 s[1] = '\0';
167 if (s[2] != '\0') {
168 fprintf(stderr, "the request was longer than 1024 bytes\n");
169 return 0;
172 return 1;
175 void
176 adjust_path(char *path)
178 char *s;
179 size_t len;
181 /* /.. -> / */
182 len = strlen(path);
183 if (len >= 3) {
184 if (!strcmp(&path[len-3], "/..")) {
185 path[len-2] = '\0';
189 /* if the path is only `..` trim out and exit */
190 if (!strcmp(path, "..")) {
191 path[0] = '\0';
192 return;
195 /* remove every ../ in the path */
196 while (1) {
197 if ((s = strstr(path, "../")) == NULL)
198 return;
199 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
203 int
204 path_isdir(char *path)
206 if (*path == '\0')
207 return 1;
208 return path[strlen(path)-1] == '/';
211 int
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 */
215 int len;
216 int ret;
218 client->code = code;
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;
227 return 0;
230 if (ret == TLS_WANT_POLLOUT) {
231 pfd->events = POLLOUT;
232 return 0;
235 return 1;
238 int
239 isdir(int fd)
241 struct stat sb;
243 if (fstat(fd, &sb) == -1) {
244 warn("fstat");
245 return 1; /* we'll probably fail later on anyway */
248 return S_ISDIR(sb.st_mode);
251 ssize_t
252 filesize(int fd)
254 ssize_t len;
256 if ((len = lseek(fd, 0, SEEK_END)) == -1)
257 return -1;
258 if (lseek(fd, 0, SEEK_SET) == -1)
259 return -1;
260 return len;
263 const char *
264 path_ext(const char *path)
266 const char *end;
268 end = path + strlen(path)-1; /* the last byte before the NUL */
269 for (; end != path; --end) {
270 if (*end == '.')
271 return end+1;
272 if (*end == '/')
273 break;
276 return NULL;
279 const char *
280 mime(const char *path)
282 const char *ext, *def = "application/octet-stream";
283 struct etm *t;
285 if ((ext = path_ext(path)) == NULL)
286 return def;
288 for (t = filetypes; t->mime != NULL; ++t)
289 if (!strcmp(ext, t->ext))
290 return t->mime;
292 return def;
295 int
296 open_file(char *path, struct pollfd *fds, struct client *c)
298 char fpath[PATHBUF];
300 assert(path != NULL);
302 bzero(fpath, sizeof(fpath));
304 if (*path != '.')
305 fpath[0] = '.';
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"))
311 return 0;
312 goodbye(fds, c);
313 return 0;
316 if (isdir(c->fd)) {
317 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
318 close(c->fd);
319 c->fd = -1;
320 send_dir(fpath, fds, c);
321 return 0;
324 if ((c->len = filesize(c->fd)) == -1) {
325 warn("filesize: %s", fpath);
326 goodbye(fds, c);
327 return 0;
330 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
331 c->fd, 0)) == MAP_FAILED) {
332 warn("mmap: %s", fpath);
333 goodbye(fds, c);
334 return 0;
336 c->i = c->buf;
338 return start_reply(fds, c, SUCCESS, mime(fpath));
341 void
342 send_file(char *path, struct pollfd *fds, struct client *c)
344 ssize_t ret, len;
346 if (c->fd == -1) {
347 if (!open_file(path, fds, c))
348 return;
349 c->state = S_SENDING;
352 len = (c->buf + c->len) - c->i;
354 while (len > 0) {
355 switch (ret = tls_write(c->ctx, c->i, len)) {
356 case -1:
357 warnx("tls_write: %s", tls_error(c->ctx));
358 goodbye(fds, c);
359 return;
361 case TLS_WANT_POLLIN:
362 fds->events = POLLIN;
363 return;
365 case TLS_WANT_POLLOUT:
366 fds->events = POLLOUT;
367 return;
369 default:
370 c->i += ret;
371 len -= ret;
372 break;
376 goodbye(fds, c);
379 void
380 send_dir(char *path, struct pollfd *fds, struct client *client)
382 char fpath[PATHBUF];
383 size_t len;
385 bzero(fpath, PATHBUF);
387 if (path[0] != '.')
388 fpath[0] = '.';
390 /* this cannot fail since sizeof(fpath) > maxlen of path */
391 strlcat(fpath, path, PATHBUF);
392 len = strlen(fpath);
394 /* add a trailing / in case. */
395 if (fpath[len-1] != '/') {
396 fpath[len] = '/';
399 strlcat(fpath, "index.gmi", sizeof(fpath));
401 send_file(fpath, fds, client);
404 void
405 handle(struct pollfd *fds, struct client *client)
407 char buf[GEMINI_URL_LEN];
408 char *path;
410 switch (client->state) {
411 case S_OPEN:
412 bzero(buf, GEMINI_URL_LEN);
413 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
414 case -1:
415 warnx("tls_read: %s", tls_error(client->ctx));
416 goodbye(fds, client);
417 return;
419 case TLS_WANT_POLLIN:
420 fds->events = POLLIN;
421 return;
423 case TLS_WANT_POLLOUT:
424 fds->events = POLLOUT;
425 return;
428 if (!url_trim(buf)) {
429 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
430 return;
431 goodbye(fds, client);
432 return;
435 if ((path = url_start_of_request(buf)) == NULL) {
436 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
437 return;
438 goodbye(fds, client);
439 return;
442 adjust_path(path);
443 fprintf(stderr, "requested path: %s\n", path);
445 if (path_isdir(path))
446 send_dir(path, fds, client);
447 else
448 send_file(path, fds, client);
449 break;
451 case S_INITIALIZING:
452 if (!start_reply(fds, client, client->code, client->meta))
453 return;
455 if (client->code != SUCCESS) {
456 /* we don't need a body */
457 goodbye(fds, client);
458 return;
461 client->state = S_SENDING;
463 /* fallthrough */
465 case S_SENDING:
466 send_file(NULL, fds, client);
467 break;
469 case S_CLOSING:
470 goodbye(fds, client);
471 break;
473 default:
474 /* unreachable */
475 abort();
479 void
480 mark_nonblock(int fd)
482 int flags;
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)");
490 int
491 make_socket(int port, int family)
493 int sock, v;
494 struct sockaddr_in addr4;
495 struct sockaddr_in6 addr6;
496 struct sockaddr *addr;
497 socklen_t len;
499 switch (family) {
500 case AF_INET:
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;
506 len = sizeof(addr4);
507 break;
509 case AF_INET6:
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;
515 len = sizeof(addr6);
516 break;
518 default:
519 /* unreachable */
520 abort();
523 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
524 err(1, "socket");
526 v = 1;
527 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
528 err(1, "setsockopt(SO_REUSEADDR)");
530 v = 1;
531 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
532 err(1, "setsockopt(SO_REUSEPORT)");
534 mark_nonblock(sock);
536 if (bind(sock, addr, len) == -1)
537 err(1, "bind");
539 if (listen(sock, 16) == -1)
540 err(1, "listen");
542 return sock;
545 void
546 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
548 int i, fd;
549 struct sockaddr_in addr;
550 socklen_t len;
552 len = sizeof(addr);
553 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
554 if (errno == EWOULDBLOCK)
555 return;
556 err(1, "accept");
559 mark_nonblock(fd);
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! */
567 fds[i].fd = fd;
568 fds[i].events = POLLIN;
570 clients[i].state = S_OPEN;
571 clients[i].fd = -1;
572 clients[i].buf = MAP_FAILED;
574 return;
578 close(fd);
581 void
582 goodbye(struct pollfd *pfd, struct client *c)
584 ssize_t ret;
586 c->state = S_CLOSING;
588 ret = tls_close(c->ctx);
589 if (ret == TLS_WANT_POLLIN) {
590 pfd->events = POLLIN;
591 return;
593 if (ret == TLS_WANT_POLLOUT) {
594 pfd->events = POLLOUT;
595 return;
598 tls_free(c->ctx);
599 c->ctx = NULL;
601 if (c->buf != MAP_FAILED)
602 munmap(c->buf, c->len);
604 if (c->fd != -1)
605 close(c->fd);
607 close(pfd->fd);
608 pfd->fd = -1;
611 void
612 loop(struct tls *ctx, int sock)
614 int i, todo;
615 struct client clients[MAX_USERS];
616 struct pollfd fds[MAX_USERS];
618 for (i = 0; i < MAX_USERS; ++i) {
619 fds[i].fd = -1;
620 fds[i].events = POLLIN;
621 bzero(&clients[i], sizeof(struct client));
624 fds[0].fd = sock;
626 for (;;) {
627 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
628 err(1, "poll");
630 for (i = 0; i < MAX_USERS; i++) {
631 assert(i < MAX_USERS);
633 if (fds[i].revents == 0)
634 continue;
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]);
641 continue;
644 todo--;
646 if (i == 0) { /* new client */
647 do_accept(sock, ctx, fds, clients);
648 continue;
651 handle(&fds[i], &clients[i]);
656 void
657 usage(const char *me)
659 fprintf(stderr,
660 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
661 me);
664 int
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;
670 int sock, ch;
672 signal(SIGPIPE, SIG_IGN);
674 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
675 switch (ch) {
676 case 'c':
677 cert = optarg;
678 break;
680 case 'd':
681 dir = optarg;
682 break;
684 case 'h':
685 usage(*argv);
686 return 0;
688 case 'k':
689 key = optarg;
690 break;
692 default:
693 usage(*argv);
694 return 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)
723 err(1, "unveil");
725 if (pledge("stdio rpath inet", "") == -1)
726 err(1, "pledge");
728 loop(ctx, sock);
730 close(sock);
731 tls_free(ctx);
732 tls_config_free(conf);