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 <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <tls.h>
32 #include <unistd.h>
34 #ifndef __OpenBSD__
35 # define pledge(a, b) 0
36 # define unveil(a, b) 0
37 #endif /* __OpenBSD__ */
39 #ifndef INFTIM
40 # define INFTIM -1
41 #endif /* INFTIM */
43 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
45 /* large enough to hold a copy of a gemini URL and still have extra room */
46 #define PATHBUF 2048
48 #define SUCCESS 20
49 #define NOT_FOUND 51
50 #define BAD_REQUEST 59
52 #ifndef MAX_USERS
53 #define MAX_USERS 64
54 #endif
56 enum {
57 S_OPEN,
58 S_INITIALIZING,
59 S_SENDING,
60 S_CLOSING,
61 };
63 struct client {
64 struct tls *ctx;
65 int state;
66 int code;
67 const char *meta;
68 int fd;
69 void *buf, *i;
70 ssize_t len, off;
71 };
73 struct etm { /* file extension to mime */
74 const char *mime;
75 const char *ext;
76 } filetypes[] = {
77 {"application/pdf", "pdf"},
79 {"image/gif", "gif"},
80 {"image/jpeg", "jpg"},
81 {"image/jpeg", "jpeg"},
82 {"image/png", "png"},
83 {"image/svg+xml", "svg"},
85 {"text/gemini", "gemini"},
86 {"text/gemini", "gmi"},
87 {"text/markdown", "markdown"},
88 {"text/markdown", "md"},
89 {"text/plain", "txt"},
91 {NULL, NULL}
92 };
94 int dirfd;
96 char *url_after_proto(char*);
97 char *url_start_of_request(char*);
98 int url_trim(char*);
99 void adjust_path(char*);
100 int path_isdir(char*);
101 ssize_t filesize(int);
103 int start_reply(struct pollfd*, struct client*, int, const char*);
104 int isdir(int);
105 const char *path_ext(const char*);
106 const char *mime(const char*);
107 int open_file(char*, struct pollfd*, struct client*);
108 void send_file(char*, struct pollfd*, struct client*);
109 void send_dir(char*, struct pollfd*, struct client*);
110 void handle(struct pollfd*, struct client*);
112 void mark_nonblock(int);
113 int make_soket(int);
114 void do_accept(int, struct tls*, struct pollfd*, struct client*);
115 void goodbye(struct pollfd*, struct client*);
116 void loop(struct tls*, int);
118 void usage(const char*);
120 char *
121 url_after_proto(char *url)
123 char *s;
124 const char *proto = "gemini";
125 const char *marker = "://";
127 if ((s = strstr(url, marker)) == NULL)
128 return url;
130 /* not a gemini:// URL */
132 if (s - strlen(proto) < url)
133 return NULL;
134 /* TODO: */
135 /* if (strcmp(s - strlen(proto), proto)) */
136 /* return NULL; */
138 /* a valid gemini:// URL */
139 return s + strlen(marker);
142 char *
143 url_start_of_request(char *url)
145 char *s, *t;
147 if ((s = url_after_proto(url)) == NULL)
148 return NULL;
150 if ((t = strstr(s, "/")) == NULL)
151 return s + strlen(s);
152 return t;
155 int
156 url_trim(char *url)
158 const char *e = "\r\n";
159 char *s;
161 if ((s = strstr(url, e)) == NULL)
162 return 0;
163 s[0] = '\0';
164 s[1] = '\0';
166 if (s[2] != '\0') {
167 fprintf(stderr, "the request was longer than 1024 bytes\n");
168 return 0;
171 return 1;
174 void
175 adjust_path(char *path)
177 char *s;
178 size_t len;
180 /* /.. -> / */
181 len = strlen(path);
182 if (len >= 3) {
183 if (!strcmp(&path[len-3], "/..")) {
184 path[len-2] = '\0';
188 /* if the path is only `..` trim out and exit */
189 if (!strcmp(path, "..")) {
190 path[0] = '\0';
191 return;
194 /* remove every ../ in the path */
195 while (1) {
196 if ((s = strstr(path, "../")) == NULL)
197 return;
198 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
202 int
203 path_isdir(char *path)
205 if (*path == '\0')
206 return 1;
207 return path[strlen(path)-1] == '/';
210 int
211 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
213 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
214 int len;
215 int ret;
217 client->code = code;
218 client->meta = reason;
219 client->state = S_INITIALIZING;
221 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
222 assert(len < (int)sizeof(buf));
223 ret = tls_write(client->ctx, buf, len);
224 if (ret == TLS_WANT_POLLIN) {
225 pfd->events = POLLIN;
226 return 0;
229 if (ret == TLS_WANT_POLLOUT) {
230 pfd->events = POLLOUT;
231 return 0;
234 return 1;
237 int
238 isdir(int fd)
240 struct stat sb;
242 if (fstat(fd, &sb) == -1) {
243 warn("fstat");
244 return 1; /* we'll probably fail later on anyway */
247 return S_ISDIR(sb.st_mode);
250 ssize_t
251 filesize(int fd)
253 ssize_t len;
255 if ((len = lseek(fd, 0, SEEK_END)) == -1)
256 return -1;
257 if (lseek(fd, 0, SEEK_SET) == -1)
258 return -1;
259 return len;
262 const char *
263 path_ext(const char *path)
265 const char *end;
267 end = path + strlen(path)-1; /* the last byte before the NUL */
268 for (; end != path; --end) {
269 if (*end == '.')
270 return end+1;
271 if (*end == '/')
272 break;
275 return NULL;
278 const char *
279 mime(const char *path)
281 const char *ext, *def = "application/octet-stream";
282 struct etm *t;
284 if ((ext = path_ext(path)) == NULL)
285 return def;
287 for (t = filetypes; t->mime != NULL; ++t)
288 if (!strcmp(ext, t->ext))
289 return t->mime;
291 return def;
294 int
295 open_file(char *path, struct pollfd *fds, struct client *c)
297 char fpath[PATHBUF];
299 assert(path != NULL);
301 bzero(fpath, sizeof(fpath));
303 if (*path != '.')
304 fpath[0] = '.';
305 strlcat(fpath, path, PATHBUF);
307 if ((c->fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
308 warn("open: %s", fpath);
309 if (!start_reply(fds, c, NOT_FOUND, "not found"))
310 return 0;
311 goodbye(fds, c);
312 return 0;
315 if (isdir(c->fd)) {
316 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
317 close(c->fd);
318 c->fd = -1;
319 send_dir(fpath, fds, c);
320 return 0;
323 if ((c->len = filesize(c->fd)) == -1) {
324 warn("filesize: %s", fpath);
325 goodbye(fds, c);
326 return 0;
329 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
330 c->fd, 0)) == MAP_FAILED) {
331 warn("mmap: %s", fpath);
332 goodbye(fds, c);
333 return 0;
335 c->i = c->buf;
337 return start_reply(fds, c, SUCCESS, mime(fpath));
340 void
341 send_file(char *path, struct pollfd *fds, struct client *c)
343 ssize_t ret, len;
345 if (c->fd == -1) {
346 if (!open_file(path, fds, c))
347 return;
348 c->state = S_SENDING;
351 len = (c->buf + c->len) - c->i;
353 while (len > 0) {
354 switch (ret = tls_write(c->ctx, c->i, len)) {
355 case -1:
356 warnx("tls_write: %s", tls_error(c->ctx));
357 goodbye(fds, c);
358 return;
360 case TLS_WANT_POLLIN:
361 fds->events = POLLIN;
362 return;
364 case TLS_WANT_POLLOUT:
365 fds->events = POLLOUT;
366 return;
368 default:
369 c->i += ret;
370 len -= ret;
371 break;
375 goodbye(fds, c);
378 void
379 send_dir(char *path, struct pollfd *fds, struct client *client)
381 char fpath[PATHBUF];
382 size_t len;
384 bzero(fpath, PATHBUF);
386 if (path[0] != '.')
387 fpath[0] = '.';
389 /* this cannot fail since sizeof(fpath) > maxlen of path */
390 strlcat(fpath, path, PATHBUF);
391 len = strlen(fpath);
393 /* add a trailing / in case. */
394 if (fpath[len-1] != '/') {
395 fpath[len] = '/';
398 strlcat(fpath, "index.gmi", sizeof(fpath));
400 send_file(fpath, fds, client);
403 void
404 handle(struct pollfd *fds, struct client *client)
406 char buf[GEMINI_URL_LEN];
407 char *path;
409 switch (client->state) {
410 case S_OPEN:
411 bzero(buf, GEMINI_URL_LEN);
412 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
413 case -1:
414 warnx("tls_read: %s", tls_error(client->ctx));
415 goodbye(fds, client);
416 return;
418 case TLS_WANT_POLLIN:
419 fds->events = POLLIN;
420 return;
422 case TLS_WANT_POLLOUT:
423 fds->events = POLLOUT;
424 return;
427 if (!url_trim(buf)) {
428 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
429 return;
430 goodbye(fds, client);
431 return;
434 if ((path = url_start_of_request(buf)) == NULL) {
435 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
436 return;
437 goodbye(fds, client);
438 return;
441 adjust_path(path);
442 fprintf(stderr, "requested path: %s\n", path);
444 if (path_isdir(path))
445 send_dir(path, fds, client);
446 else
447 send_file(path, fds, client);
448 break;
450 case S_INITIALIZING:
451 if (!start_reply(fds, client, client->code, client->meta))
452 return;
454 if (client->code != SUCCESS) {
455 /* we don't need a body */
456 goodbye(fds, client);
457 return;
460 client->state = S_SENDING;
462 /* fallthrough */
464 case S_SENDING:
465 send_file(NULL, fds, client);
466 break;
468 case S_CLOSING:
469 goodbye(fds, client);
470 break;
472 default:
473 /* unreachable */
474 abort();
478 void
479 mark_nonblock(int fd)
481 int flags;
483 if ((flags = fcntl(fd, F_GETFL)) == -1)
484 err(1, "fcntl(F_GETFL)");
485 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
486 err(1, "fcntl(F_SETFL)");
489 int
490 make_socket(int port)
492 int sock, v;
493 struct sockaddr_in addr;
495 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
496 err(1, "socket");
498 v = 1;
499 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
500 err(1, "setsockopt(SO_REUSEADDR)");
502 v = 1;
503 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
504 err(1, "setsockopt(SO_REUSEPORT)");
506 mark_nonblock(sock);
508 bzero(&addr, sizeof(addr));
509 addr.sin_family = AF_INET;
510 addr.sin_port = htons(port);
511 addr.sin_addr.s_addr = INADDR_ANY;
513 if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
514 err(1, "bind");
516 if (listen(sock, 16) == -1)
517 err(1, "listen");
519 return sock;
522 void
523 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
525 int i, fd;
526 struct sockaddr_in addr;
527 socklen_t len;
529 len = sizeof(addr);
530 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
531 if (errno == EWOULDBLOCK)
532 return;
533 err(1, "accept");
536 mark_nonblock(fd);
538 for (i = 0; i < MAX_USERS; ++i) {
539 if (fds[i].fd == -1) {
540 bzero(&clients[i], sizeof(struct client));
541 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
542 break; /* goodbye fd! */
544 fds[i].fd = fd;
545 fds[i].events = POLLIN;
547 clients[i].state = S_OPEN;
548 clients[i].fd = -1;
549 clients[i].buf = MAP_FAILED;
551 return;
555 close(fd);
558 void
559 goodbye(struct pollfd *pfd, struct client *c)
561 ssize_t ret;
563 c->state = S_CLOSING;
565 ret = tls_close(c->ctx);
566 if (ret == TLS_WANT_POLLIN) {
567 pfd->events = POLLIN;
568 return;
570 if (ret == TLS_WANT_POLLOUT) {
571 pfd->events = POLLOUT;
572 return;
575 tls_free(c->ctx);
576 c->ctx = NULL;
578 if (c->buf != MAP_FAILED)
579 munmap(c->buf, c->len);
581 if (c->fd != -1)
582 close(c->fd);
584 close(pfd->fd);
585 pfd->fd = -1;
588 void
589 loop(struct tls *ctx, int sock)
591 int i, todo;
592 struct client clients[MAX_USERS];
593 struct pollfd fds[MAX_USERS];
595 for (i = 0; i < MAX_USERS; ++i) {
596 fds[i].fd = -1;
597 fds[i].events = POLLIN;
598 bzero(&clients[i], sizeof(struct client));
601 fds[0].fd = sock;
603 for (;;) {
604 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
605 err(1, "poll");
607 for (i = 0; i < MAX_USERS; i++) {
608 assert(i < MAX_USERS);
610 if (fds[i].revents == 0)
611 continue;
613 if (fds[i].revents & (POLLERR|POLLNVAL))
614 err(1, "bad fd %d", fds[i].fd);
616 if (fds[i].revents & POLLHUP) {
617 goodbye(&fds[i], &clients[i]);
618 continue;
621 todo--;
623 if (i == 0) { /* new client */
624 do_accept(sock, ctx, fds, clients);
625 continue;
628 handle(&fds[i], &clients[i]);
633 void
634 usage(const char *me)
636 fprintf(stderr,
637 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
638 me);
641 int
642 main(int argc, char **argv)
644 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
645 struct tls *ctx = NULL;
646 struct tls_config *conf;
647 int sock, ch;
649 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
650 switch (ch) {
651 case 'c':
652 cert = optarg;
653 break;
655 case 'd':
656 dir = optarg;
657 break;
659 case 'h':
660 usage(*argv);
661 return 0;
663 case 'k':
664 key = optarg;
665 break;
667 default:
668 usage(*argv);
669 return 1;
673 if ((conf = tls_config_new()) == NULL)
674 err(1, "tls_config_new");
676 if (tls_config_set_protocols(conf,
677 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
678 err(1, "tls_config_set_protocols");
680 if (tls_config_set_cert_file(conf, cert) == -1)
681 err(1, "tls_config_set_cert_file: %s", cert);
683 if (tls_config_set_key_file(conf, key) == -1)
684 err(1, "tls_config_set_key_file: %s", key);
686 if ((ctx = tls_server()) == NULL)
687 err(1, "tls_server");
689 if (tls_configure(ctx, conf) == -1)
690 errx(1, "tls_configure: %s", tls_error(ctx));
692 sock = make_socket(1965);
694 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
695 err(1, "open: %s", dir);
697 if (unveil(dir, "r") == -1)
698 err(1, "unveil");
700 if (pledge("stdio rpath inet", "") == -1)
701 err(1, "pledge");
703 loop(ctx, sock);
705 close(sock);
706 tls_free(ctx);
707 tls_config_free(conf);