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"},
91 {"text/xml", "xml"}
93 {NULL, NULL}
94 };
96 int dirfd;
98 char *url_after_proto(char*);
99 char *url_start_of_request(char*);
100 int url_trim(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*);
106 int isdir(int);
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);
115 int make_soket(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*);
122 char *
123 url_after_proto(char *url)
125 char *s;
126 const char *proto = "gemini";
127 const char *marker = "://";
129 if ((s = strstr(url, marker)) == NULL)
130 return url;
132 /* not a gemini:// URL */
134 if (s - strlen(proto) < url)
135 return NULL;
136 /* TODO: */
137 /* if (strcmp(s - strlen(proto), proto)) */
138 /* return NULL; */
140 /* a valid gemini:// URL */
141 return s + strlen(marker);
144 char *
145 url_start_of_request(char *url)
147 char *s, *t;
149 if ((s = url_after_proto(url)) == NULL)
150 return NULL;
152 if ((t = strstr(s, "/")) == NULL)
153 return s + strlen(s);
154 return t;
157 int
158 url_trim(char *url)
160 const char *e = "\r\n";
161 char *s;
163 if ((s = strstr(url, e)) == NULL)
164 return 0;
165 s[0] = '\0';
166 s[1] = '\0';
168 if (s[2] != '\0') {
169 fprintf(stderr, "the request was longer than 1024 bytes\n");
170 return 0;
173 return 1;
176 void
177 adjust_path(char *path)
179 char *s;
180 size_t len;
182 /* /.. -> / */
183 len = strlen(path);
184 if (len >= 3) {
185 if (!strcmp(&path[len-3], "/..")) {
186 path[len-2] = '\0';
190 /* if the path is only `..` trim out and exit */
191 if (!strcmp(path, "..")) {
192 path[0] = '\0';
193 return;
196 /* remove every ../ in the path */
197 while (1) {
198 if ((s = strstr(path, "../")) == NULL)
199 return;
200 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
204 int
205 path_isdir(char *path)
207 if (*path == '\0')
208 return 1;
209 return path[strlen(path)-1] == '/';
212 int
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 */
216 int len;
217 int ret;
219 client->code = code;
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;
228 return 0;
231 if (ret == TLS_WANT_POLLOUT) {
232 pfd->events = POLLOUT;
233 return 0;
236 return 1;
239 int
240 isdir(int fd)
242 struct stat sb;
244 if (fstat(fd, &sb) == -1) {
245 warn("fstat");
246 return 1; /* we'll probably fail later on anyway */
249 return S_ISDIR(sb.st_mode);
252 ssize_t
253 filesize(int fd)
255 ssize_t len;
257 if ((len = lseek(fd, 0, SEEK_END)) == -1)
258 return -1;
259 if (lseek(fd, 0, SEEK_SET) == -1)
260 return -1;
261 return len;
264 const char *
265 path_ext(const char *path)
267 const char *end;
269 end = path + strlen(path)-1; /* the last byte before the NUL */
270 for (; end != path; --end) {
271 if (*end == '.')
272 return end+1;
273 if (*end == '/')
274 break;
277 return NULL;
280 const char *
281 mime(const char *path)
283 const char *ext, *def = "application/octet-stream";
284 struct etm *t;
286 if ((ext = path_ext(path)) == NULL)
287 return def;
289 for (t = filetypes; t->mime != NULL; ++t)
290 if (!strcmp(ext, t->ext))
291 return t->mime;
293 return def;
296 int
297 open_file(char *path, struct pollfd *fds, struct client *c)
299 char fpath[PATHBUF];
301 assert(path != NULL);
303 bzero(fpath, sizeof(fpath));
305 if (*path != '.')
306 fpath[0] = '.';
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"))
312 return 0;
313 goodbye(fds, c);
314 return 0;
317 if (isdir(c->fd)) {
318 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
319 close(c->fd);
320 c->fd = -1;
321 send_dir(fpath, fds, c);
322 return 0;
325 if ((c->len = filesize(c->fd)) == -1) {
326 warn("filesize: %s", fpath);
327 goodbye(fds, c);
328 return 0;
331 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
332 c->fd, 0)) == MAP_FAILED) {
333 warn("mmap: %s", fpath);
334 goodbye(fds, c);
335 return 0;
337 c->i = c->buf;
339 return start_reply(fds, c, SUCCESS, mime(fpath));
342 void
343 send_file(char *path, struct pollfd *fds, struct client *c)
345 ssize_t ret, len;
347 if (c->fd == -1) {
348 if (!open_file(path, fds, c))
349 return;
350 c->state = S_SENDING;
353 len = (c->buf + c->len) - c->i;
355 while (len > 0) {
356 switch (ret = tls_write(c->ctx, c->i, len)) {
357 case -1:
358 warnx("tls_write: %s", tls_error(c->ctx));
359 goodbye(fds, c);
360 return;
362 case TLS_WANT_POLLIN:
363 fds->events = POLLIN;
364 return;
366 case TLS_WANT_POLLOUT:
367 fds->events = POLLOUT;
368 return;
370 default:
371 c->i += ret;
372 len -= ret;
373 break;
377 goodbye(fds, c);
380 void
381 send_dir(char *path, struct pollfd *fds, struct client *client)
383 char fpath[PATHBUF];
384 size_t len;
386 bzero(fpath, PATHBUF);
388 if (path[0] != '.')
389 fpath[0] = '.';
391 /* this cannot fail since sizeof(fpath) > maxlen of path */
392 strlcat(fpath, path, PATHBUF);
393 len = strlen(fpath);
395 /* add a trailing / in case. */
396 if (fpath[len-1] != '/') {
397 fpath[len] = '/';
400 strlcat(fpath, "index.gmi", sizeof(fpath));
402 send_file(fpath, fds, client);
405 void
406 handle(struct pollfd *fds, struct client *client)
408 char buf[GEMINI_URL_LEN];
409 char *path;
411 switch (client->state) {
412 case S_OPEN:
413 bzero(buf, GEMINI_URL_LEN);
414 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
415 case -1:
416 warnx("tls_read: %s", tls_error(client->ctx));
417 goodbye(fds, client);
418 return;
420 case TLS_WANT_POLLIN:
421 fds->events = POLLIN;
422 return;
424 case TLS_WANT_POLLOUT:
425 fds->events = POLLOUT;
426 return;
429 if (!url_trim(buf)) {
430 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
431 return;
432 goodbye(fds, client);
433 return;
436 if ((path = url_start_of_request(buf)) == NULL) {
437 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
438 return;
439 goodbye(fds, client);
440 return;
443 adjust_path(path);
444 fprintf(stderr, "requested path: %s\n", path);
446 if (path_isdir(path))
447 send_dir(path, fds, client);
448 else
449 send_file(path, fds, client);
450 break;
452 case S_INITIALIZING:
453 if (!start_reply(fds, client, client->code, client->meta))
454 return;
456 if (client->code != SUCCESS) {
457 /* we don't need a body */
458 goodbye(fds, client);
459 return;
462 client->state = S_SENDING;
464 /* fallthrough */
466 case S_SENDING:
467 send_file(NULL, fds, client);
468 break;
470 case S_CLOSING:
471 goodbye(fds, client);
472 break;
474 default:
475 /* unreachable */
476 abort();
480 void
481 mark_nonblock(int fd)
483 int flags;
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)");
491 int
492 make_socket(int port, int family)
494 int sock, v;
495 struct sockaddr_in addr4;
496 struct sockaddr_in6 addr6;
497 struct sockaddr *addr;
498 socklen_t len;
500 switch (family) {
501 case AF_INET:
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;
507 len = sizeof(addr4);
508 break;
510 case AF_INET6:
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;
516 len = sizeof(addr6);
517 break;
519 default:
520 /* unreachable */
521 abort();
524 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
525 err(1, "socket");
527 v = 1;
528 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
529 err(1, "setsockopt(SO_REUSEADDR)");
531 v = 1;
532 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
533 err(1, "setsockopt(SO_REUSEPORT)");
535 mark_nonblock(sock);
537 if (bind(sock, addr, len) == -1)
538 err(1, "bind");
540 if (listen(sock, 16) == -1)
541 err(1, "listen");
543 return sock;
546 void
547 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
549 int i, fd;
550 struct sockaddr_in addr;
551 socklen_t len;
553 len = sizeof(addr);
554 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
555 if (errno == EWOULDBLOCK)
556 return;
557 err(1, "accept");
560 mark_nonblock(fd);
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! */
568 fds[i].fd = fd;
569 fds[i].events = POLLIN;
571 clients[i].state = S_OPEN;
572 clients[i].fd = -1;
573 clients[i].buf = MAP_FAILED;
575 return;
579 close(fd);
582 void
583 goodbye(struct pollfd *pfd, struct client *c)
585 ssize_t ret;
587 c->state = S_CLOSING;
589 ret = tls_close(c->ctx);
590 if (ret == TLS_WANT_POLLIN) {
591 pfd->events = POLLIN;
592 return;
594 if (ret == TLS_WANT_POLLOUT) {
595 pfd->events = POLLOUT;
596 return;
599 tls_free(c->ctx);
600 c->ctx = NULL;
602 if (c->buf != MAP_FAILED)
603 munmap(c->buf, c->len);
605 if (c->fd != -1)
606 close(c->fd);
608 close(pfd->fd);
609 pfd->fd = -1;
612 void
613 loop(struct tls *ctx, int sock)
615 int i, todo;
616 struct client clients[MAX_USERS];
617 struct pollfd fds[MAX_USERS];
619 for (i = 0; i < MAX_USERS; ++i) {
620 fds[i].fd = -1;
621 fds[i].events = POLLIN;
622 bzero(&clients[i], sizeof(struct client));
625 fds[0].fd = sock;
627 for (;;) {
628 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
629 err(1, "poll");
631 for (i = 0; i < MAX_USERS; i++) {
632 assert(i < MAX_USERS);
634 if (fds[i].revents == 0)
635 continue;
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]);
642 continue;
645 todo--;
647 if (i == 0) { /* new client */
648 do_accept(sock, ctx, fds, clients);
649 continue;
652 handle(&fds[i], &clients[i]);
657 void
658 usage(const char *me)
660 fprintf(stderr,
661 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
662 me);
665 int
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;
671 int sock, ch;
673 signal(SIGPIPE, SIG_IGN);
675 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
676 switch (ch) {
677 case 'c':
678 cert = optarg;
679 break;
681 case 'd':
682 dir = optarg;
683 break;
685 case 'h':
686 usage(*argv);
687 return 0;
689 case 'k':
690 key = optarg;
691 break;
693 default:
694 usage(*argv);
695 return 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)
724 err(1, "unveil");
726 if (pledge("stdio rpath inet", "") == -1)
727 err(1, "pledge");
729 loop(ctx, sock);
731 close(sock);
732 tls_free(ctx);
733 tls_config_free(conf);