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 <arpa/inet.h>
22 #include <netinet/in.h>
24 #include <assert.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <tls.h>
34 #include <unistd.h>
36 #ifndef __OpenBSD__
37 # define pledge(a, b) 0
38 # define unveil(a, b) 0
39 #endif /* __OpenBSD__ */
41 #ifndef INFTIM
42 # define INFTIM -1
43 #endif /* INFTIM */
45 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
47 /* large enough to hold a copy of a gemini URL and still have extra room */
48 #define PATHBUF 2048
50 #define SUCCESS 20
51 #define NOT_FOUND 51
52 #define BAD_REQUEST 59
54 #ifndef MAX_USERS
55 #define MAX_USERS 64
56 #endif
58 enum {
59 S_OPEN,
60 S_INITIALIZING,
61 S_SENDING,
62 S_CLOSING,
63 };
65 struct client {
66 struct tls *ctx;
67 int state;
68 int code;
69 const char *meta;
70 int fd;
71 void *buf, *i;
72 ssize_t len, off;
73 int af;
74 struct in_addr addr;
75 };
77 struct etm { /* file extension to mime */
78 const char *mime;
79 const char *ext;
80 } filetypes[] = {
81 {"application/pdf", "pdf"},
83 {"image/gif", "gif"},
84 {"image/jpeg", "jpg"},
85 {"image/jpeg", "jpeg"},
86 {"image/png", "png"},
87 {"image/svg+xml", "svg"},
89 {"text/gemini", "gemini"},
90 {"text/gemini", "gmi"},
91 {"text/markdown", "markdown"},
92 {"text/markdown", "md"},
93 {"text/plain", "txt"},
94 {"text/xml", "xml"},
96 {NULL, NULL}
97 };
99 #define LOG(c, fmt, ...) \
100 do { \
101 char buf[INET_ADDRSTRLEN]; \
102 if (inet_ntop((c)->af, &(c)->addr, buf, sizeof(buf)) == NULL) \
103 err(1, "inet_ntop"); \
104 dprintf(logfd, "[%s] " fmt "\n", buf, __VA_ARGS__); \
105 } while (0)
107 int dirfd, logfd;
109 char *url_after_proto(char*);
110 char *url_start_of_request(char*);
111 int url_trim(struct client*, char*);
112 void adjust_path(char*);
113 int path_isdir(char*);
114 ssize_t filesize(int);
116 int start_reply(struct pollfd*, struct client*, int, const char*);
117 int isdir(int);
118 const char *path_ext(const char*);
119 const char *mime(const char*);
120 int open_file(char*, struct pollfd*, struct client*);
121 void send_file(char*, struct pollfd*, struct client*);
122 void send_dir(char*, struct pollfd*, struct client*);
123 void handle(struct pollfd*, struct client*);
125 void mark_nonblock(int);
126 int make_soket(int);
127 void do_accept(int, struct tls*, struct pollfd*, struct client*);
128 void goodbye(struct pollfd*, struct client*);
129 void loop(struct tls*, int);
131 void usage(const char*);
133 char *
134 url_after_proto(char *url)
136 char *s;
137 const char *proto = "gemini";
138 const char *marker = "://";
140 if ((s = strstr(url, marker)) == NULL)
141 return url;
143 /* not a gemini:// URL */
145 if (s - strlen(proto) < url)
146 return NULL;
147 /* TODO: */
148 /* if (strcmp(s - strlen(proto), proto)) */
149 /* return NULL; */
151 /* a valid gemini:// URL */
152 return s + strlen(marker);
155 char *
156 url_start_of_request(char *url)
158 char *s, *t;
160 if ((s = url_after_proto(url)) == NULL)
161 return NULL;
163 if ((t = strstr(s, "/")) == NULL)
164 return s + strlen(s);
165 return t;
168 int
169 url_trim(struct client *c, char *url)
171 const char *e = "\r\n";
172 char *s;
174 if ((s = strstr(url, e)) == NULL)
175 return 0;
176 s[0] = '\0';
177 s[1] = '\0';
179 if (s[2] != '\0') {
180 LOG(c, "%s", "request longer than 1024 bytes\n");
181 return 0;
184 return 1;
187 void
188 adjust_path(char *path)
190 char *s;
191 size_t len;
193 /* /.. -> / */
194 len = strlen(path);
195 if (len >= 3) {
196 if (!strcmp(&path[len-3], "/..")) {
197 path[len-2] = '\0';
201 /* if the path is only `..` trim out and exit */
202 if (!strcmp(path, "..")) {
203 path[0] = '\0';
204 return;
207 /* remove every ../ in the path */
208 while (1) {
209 if ((s = strstr(path, "../")) == NULL)
210 return;
211 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
215 int
216 path_isdir(char *path)
218 if (*path == '\0')
219 return 1;
220 return path[strlen(path)-1] == '/';
223 int
224 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
226 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
227 int len;
228 int ret;
230 client->code = code;
231 client->meta = reason;
232 client->state = S_INITIALIZING;
234 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
235 assert(len < (int)sizeof(buf));
236 ret = tls_write(client->ctx, buf, len);
237 if (ret == TLS_WANT_POLLIN) {
238 pfd->events = POLLIN;
239 return 0;
242 if (ret == TLS_WANT_POLLOUT) {
243 pfd->events = POLLOUT;
244 return 0;
247 return 1;
250 int
251 isdir(int fd)
253 struct stat sb;
255 if (fstat(fd, &sb) == -1) {
256 warn("fstat");
257 return 1; /* we'll probably fail later on anyway */
260 return S_ISDIR(sb.st_mode);
263 ssize_t
264 filesize(int fd)
266 ssize_t len;
268 if ((len = lseek(fd, 0, SEEK_END)) == -1)
269 return -1;
270 if (lseek(fd, 0, SEEK_SET) == -1)
271 return -1;
272 return len;
275 const char *
276 path_ext(const char *path)
278 const char *end;
280 end = path + strlen(path)-1; /* the last byte before the NUL */
281 for (; end != path; --end) {
282 if (*end == '.')
283 return end+1;
284 if (*end == '/')
285 break;
288 return NULL;
291 const char *
292 mime(const char *path)
294 const char *ext, *def = "application/octet-stream";
295 struct etm *t;
297 if ((ext = path_ext(path)) == NULL)
298 return def;
300 for (t = filetypes; t->mime != NULL; ++t)
301 if (!strcmp(ext, t->ext))
302 return t->mime;
304 return def;
307 int
308 open_file(char *path, struct pollfd *fds, struct client *c)
310 char fpath[PATHBUF];
312 assert(path != NULL);
314 bzero(fpath, sizeof(fpath));
316 if (*path != '.')
317 fpath[0] = '.';
318 strlcat(fpath, path, PATHBUF);
320 if ((c->fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
321 LOG(c, "open failed: %s", fpath);
322 if (!start_reply(fds, c, NOT_FOUND, "not found"))
323 return 0;
324 goodbye(fds, c);
325 return 0;
328 if (isdir(c->fd)) {
329 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
330 close(c->fd);
331 c->fd = -1;
332 send_dir(fpath, fds, c);
333 return 0;
336 if ((c->len = filesize(c->fd)) == -1) {
337 LOG(c, "failed to get file size for %s", fpath);
338 goodbye(fds, c);
339 return 0;
342 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
343 c->fd, 0)) == MAP_FAILED) {
344 warn("mmap: %s", fpath);
345 goodbye(fds, c);
346 return 0;
348 c->i = c->buf;
350 return start_reply(fds, c, SUCCESS, mime(fpath));
353 void
354 send_file(char *path, struct pollfd *fds, struct client *c)
356 ssize_t ret, len;
358 if (c->fd == -1) {
359 if (!open_file(path, fds, c))
360 return;
361 c->state = S_SENDING;
364 len = (c->buf + c->len) - c->i;
366 while (len > 0) {
367 switch (ret = tls_write(c->ctx, c->i, len)) {
368 case -1:
369 LOG(c, "tls_write: %s", tls_error(c->ctx));
370 goodbye(fds, c);
371 return;
373 case TLS_WANT_POLLIN:
374 fds->events = POLLIN;
375 return;
377 case TLS_WANT_POLLOUT:
378 fds->events = POLLOUT;
379 return;
381 default:
382 c->i += ret;
383 len -= ret;
384 break;
388 goodbye(fds, c);
391 void
392 send_dir(char *path, struct pollfd *fds, struct client *client)
394 char fpath[PATHBUF];
395 size_t len;
397 bzero(fpath, PATHBUF);
399 if (path[0] != '.')
400 fpath[0] = '.';
402 /* this cannot fail since sizeof(fpath) > maxlen of path */
403 strlcat(fpath, path, PATHBUF);
404 len = strlen(fpath);
406 /* add a trailing / in case. */
407 if (fpath[len-1] != '/') {
408 fpath[len] = '/';
411 strlcat(fpath, "index.gmi", sizeof(fpath));
413 send_file(fpath, fds, client);
416 void
417 handle(struct pollfd *fds, struct client *client)
419 char buf[GEMINI_URL_LEN];
420 char *path;
422 switch (client->state) {
423 case S_OPEN:
424 bzero(buf, GEMINI_URL_LEN);
425 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
426 case -1:
427 LOG(client, "tls_read: %s", tls_error(client->ctx));
428 goodbye(fds, client);
429 return;
431 case TLS_WANT_POLLIN:
432 fds->events = POLLIN;
433 return;
435 case TLS_WANT_POLLOUT:
436 fds->events = POLLOUT;
437 return;
440 if (!url_trim(client, buf)) {
441 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
442 return;
443 goodbye(fds, client);
444 return;
447 if ((path = url_start_of_request(buf)) == NULL) {
448 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
449 return;
450 goodbye(fds, client);
451 return;
454 adjust_path(path);
455 LOG(client, "get %s", path);
457 if (path_isdir(path))
458 send_dir(path, fds, client);
459 else
460 send_file(path, fds, client);
461 break;
463 case S_INITIALIZING:
464 if (!start_reply(fds, client, client->code, client->meta))
465 return;
467 if (client->code != SUCCESS) {
468 /* we don't need a body */
469 goodbye(fds, client);
470 return;
473 client->state = S_SENDING;
475 /* fallthrough */
477 case S_SENDING:
478 send_file(NULL, fds, client);
479 break;
481 case S_CLOSING:
482 goodbye(fds, client);
483 break;
485 default:
486 /* unreachable */
487 abort();
491 void
492 mark_nonblock(int fd)
494 int flags;
496 if ((flags = fcntl(fd, F_GETFL)) == -1)
497 err(1, "fcntl(F_GETFL)");
498 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
499 err(1, "fcntl(F_SETFL)");
502 int
503 make_socket(int port, int family)
505 int sock, v;
506 struct sockaddr_in addr4;
507 struct sockaddr_in6 addr6;
508 struct sockaddr *addr;
509 socklen_t len;
511 switch (family) {
512 case AF_INET:
513 bzero(&addr4, sizeof(addr4));
514 addr4.sin_family = family;
515 addr4.sin_port = htons(port);
516 addr4.sin_addr.s_addr = INADDR_ANY;
517 addr = (struct sockaddr*)&addr4;
518 len = sizeof(addr4);
519 break;
521 case AF_INET6:
522 bzero(&addr6, sizeof(addr6));
523 addr6.sin6_family = AF_INET6;
524 addr6.sin6_port = htons(port);
525 addr6.sin6_addr = in6addr_any;
526 addr = (struct sockaddr*)&addr6;
527 len = sizeof(addr6);
528 break;
530 default:
531 /* unreachable */
532 abort();
535 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
536 err(1, "socket");
538 v = 1;
539 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
540 err(1, "setsockopt(SO_REUSEADDR)");
542 v = 1;
543 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
544 err(1, "setsockopt(SO_REUSEPORT)");
546 mark_nonblock(sock);
548 if (bind(sock, addr, len) == -1)
549 err(1, "bind");
551 if (listen(sock, 16) == -1)
552 err(1, "listen");
554 return sock;
557 void
558 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
560 int i, fd;
561 struct sockaddr_in addr;
562 socklen_t len;
564 len = sizeof(addr);
565 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
566 if (errno == EWOULDBLOCK)
567 return;
568 err(1, "accept");
571 mark_nonblock(fd);
573 for (i = 0; i < MAX_USERS; ++i) {
574 if (fds[i].fd == -1) {
575 bzero(&clients[i], sizeof(struct client));
576 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
577 break; /* goodbye fd! */
579 fds[i].fd = fd;
580 fds[i].events = POLLIN;
582 clients[i].state = S_OPEN;
583 clients[i].fd = -1;
584 clients[i].buf = MAP_FAILED;
585 clients[i].af = AF_INET;
586 clients[i].addr = addr.sin_addr;
588 return;
592 close(fd);
595 void
596 goodbye(struct pollfd *pfd, struct client *c)
598 ssize_t ret;
600 c->state = S_CLOSING;
602 ret = tls_close(c->ctx);
603 if (ret == TLS_WANT_POLLIN) {
604 pfd->events = POLLIN;
605 return;
607 if (ret == TLS_WANT_POLLOUT) {
608 pfd->events = POLLOUT;
609 return;
612 tls_free(c->ctx);
613 c->ctx = NULL;
615 if (c->buf != MAP_FAILED)
616 munmap(c->buf, c->len);
618 if (c->fd != -1)
619 close(c->fd);
621 close(pfd->fd);
622 pfd->fd = -1;
625 void
626 loop(struct tls *ctx, int sock)
628 int i, todo;
629 struct client clients[MAX_USERS];
630 struct pollfd fds[MAX_USERS];
632 for (i = 0; i < MAX_USERS; ++i) {
633 fds[i].fd = -1;
634 fds[i].events = POLLIN;
635 bzero(&clients[i], sizeof(struct client));
638 fds[0].fd = sock;
640 for (;;) {
641 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
642 err(1, "poll");
644 for (i = 0; i < MAX_USERS; i++) {
645 assert(i < MAX_USERS);
647 if (fds[i].revents == 0)
648 continue;
650 if (fds[i].revents & (POLLERR|POLLNVAL))
651 err(1, "bad fd %d", fds[i].fd);
653 if (fds[i].revents & POLLHUP) {
654 goodbye(&fds[i], &clients[i]);
655 continue;
658 todo--;
660 if (i == 0) { /* new client */
661 do_accept(sock, ctx, fds, clients);
662 continue;
665 handle(&fds[i], &clients[i]);
670 void
671 usage(const char *me)
673 fprintf(stderr,
674 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
675 me);
678 int
679 main(int argc, char **argv)
681 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
682 struct tls *ctx = NULL;
683 struct tls_config *conf;
684 int sock, ch;
686 signal(SIGPIPE, SIG_IGN);
688 logfd = 2; /* stderr */
690 while ((ch = getopt(argc, argv, "c:d:hk:l:")) != -1) {
691 switch (ch) {
692 case 'c':
693 cert = optarg;
694 break;
696 case 'd':
697 dir = optarg;
698 break;
700 case 'h':
701 usage(*argv);
702 return 0;
704 case 'k':
705 key = optarg;
706 break;
708 case 'l':
709 /* open log file or create it with 644 */
710 if ((logfd = open(optarg, O_WRONLY | O_CREAT,
711 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
712 err(1, "%s", optarg);
713 break;
715 default:
716 usage(*argv);
717 return 1;
721 if ((conf = tls_config_new()) == NULL)
722 err(1, "tls_config_new");
724 if (tls_config_set_protocols(conf,
725 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
726 err(1, "tls_config_set_protocols");
728 if (tls_config_set_cert_file(conf, cert) == -1)
729 err(1, "tls_config_set_cert_file: %s", cert);
731 if (tls_config_set_key_file(conf, key) == -1)
732 err(1, "tls_config_set_key_file: %s", key);
734 if ((ctx = tls_server()) == NULL)
735 err(1, "tls_server");
737 if (tls_configure(ctx, conf) == -1)
738 errx(1, "tls_configure: %s", tls_error(ctx));
740 sock = make_socket(1965, AF_INET);
742 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
743 err(1, "open: %s", dir);
745 if (unveil(dir, "r") == -1)
746 err(1, "unveil");
748 if (pledge("stdio rpath inet", "") == -1)
749 err(1, "pledge");
751 loop(ctx, sock);
753 close(sock);
754 tls_free(ctx);
755 tls_config_free(conf);