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/socket.h>
18 #include <sys/stat.h>
20 #include <netinet/in.h>
22 #include <assert.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <poll.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <tls.h>
31 #include <unistd.h>
33 #ifndef __OpenBSD__
34 # define pledge(a, b) 0
35 # define unveil(a, b) 0
36 #endif /* __OpenBSD__ */
38 #ifndef INFTIM
39 # define INFTIM -1
40 #endif /* INFTIM */
42 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
44 /* large enough to hold a copy of a gemini URL and still have extra room */
45 #define PATHBUF 2048
47 #define FILEBUF 1024
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 };
72 struct etm { /* file extension to mime */
73 const char *mime;
74 const char *ext;
75 } filetypes[] = {
76 {"application/pdf", "pdf"},
78 {"image/gif", "gif"},
79 {"image/jpeg", "jpg"},
80 {"image/jpeg", "jpeg"},
81 {"image/png", "png"},
82 {"image/svg+xml", "svg"},
84 {"text/gemini", "gemini"},
85 {"text/gemini", "gmi"},
86 {"text/markdown", "markdown"},
87 {"text/markdown", "md"},
88 {"text/plain", "txt"},
90 {NULL, NULL}
91 };
93 int dirfd;
95 char *url_after_proto(char*);
96 char *url_start_of_request(char*);
97 int url_trim(char*);
98 void adjust_path(char*);
99 int path_isdir(char*);
101 int start_reply(struct pollfd*, struct client*, int, const char*);
102 int isdir(int);
103 const char *path_ext(const char*);
104 const char *mime(const char*);
105 void send_file(char*, struct pollfd*, struct client*);
106 void send_dir(char*, struct pollfd*, struct client*);
107 void handle(struct pollfd*, struct client*);
109 void mark_nonblock(int);
110 int make_soket(int);
111 void do_accept(int, struct tls*, struct pollfd*, struct client*);
112 void goodbye(struct pollfd*, struct client*);
113 void loop(struct tls*, int);
115 void usage(const char*);
117 char *
118 url_after_proto(char *url)
120 char *s;
121 const char *proto = "gemini";
122 const char *marker = "://";
124 if ((s = strstr(url, marker)) == NULL)
125 return url;
127 /* not a gemini:// URL */
129 if (s - strlen(proto) < url)
130 return NULL;
131 /* TODO: */
132 /* if (strcmp(s - strlen(proto), proto)) */
133 /* return NULL; */
135 /* a valid gemini:// URL */
136 return s + strlen(marker);
139 char *
140 url_start_of_request(char *url)
142 char *s, *t;
144 if ((s = url_after_proto(url)) == NULL)
145 return NULL;
147 if ((t = strstr(s, "/")) == NULL)
148 return s + strlen(s);
149 return t;
152 int
153 url_trim(char *url)
155 const char *e = "\r\n";
156 char *s;
158 if ((s = strstr(url, e)) == NULL)
159 return 0;
160 s[0] = '\0';
161 s[1] = '\0';
163 if (s[2] != '\0') {
164 fprintf(stderr, "the request was longer than 1024 bytes\n");
165 return 0;
168 return 1;
171 void
172 adjust_path(char *path)
174 char *s;
175 size_t len;
177 /* /.. -> / */
178 len = strlen(path);
179 if (len >= 3) {
180 if (!strcmp(&path[len-3], "/..")) {
181 path[len-2] = '\0';
185 /* if the path is only `..` trim out and exit */
186 if (!strcmp(path, "..")) {
187 path[0] = '\0';
188 return;
191 /* remove every ../ in the path */
192 while (1) {
193 if ((s = strstr(path, "../")) == NULL)
194 return;
195 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
199 int
200 path_isdir(char *path)
202 if (*path == '\0')
203 return 1;
204 return path[strlen(path)-1] == '/';
207 int
208 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
210 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
211 int len;
212 int ret;
214 client->code = code;
215 client->meta = reason;
216 client->state = S_INITIALIZING;
218 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
219 assert(len < (int)sizeof(buf));
220 ret = tls_write(client->ctx, buf, len);
221 if (ret == TLS_WANT_POLLIN) {
222 pfd->events = POLLIN;
223 return 0;
226 if (ret == TLS_WANT_POLLOUT) {
227 pfd->events = POLLOUT;
228 return 0;
231 return 1;
234 int
235 isdir(int fd)
237 struct stat sb;
239 if (fstat(fd, &sb) == -1) {
240 warn("fstat");
241 return 1; /* we'll probably fail later on anyway */
244 return S_ISDIR(sb.st_mode);
247 const char *
248 path_ext(const char *path)
250 const char *end;
252 end = path + strlen(path)-1; /* the last byte before the NUL */
253 for (; end != path; --end) {
254 if (*end == '.')
255 return end+1;
256 if (*end == '/')
257 break;
260 return NULL;
263 const char *
264 mime(const char *path)
266 const char *ext, *def = "application/octet-stream";
267 struct etm *t;
269 if ((ext = path_ext(path)) == NULL)
270 return def;
272 for (t = filetypes; t->mime != NULL; ++t)
273 if (!strcmp(ext, t->ext))
274 return t->mime;
276 return def;
279 void
280 send_file(char *path, struct pollfd *fds, struct client *client)
282 char fpath[PATHBUF];
283 char buf[FILEBUF];
284 size_t i;
285 ssize_t t, w;
287 if (client->fd == -1) {
288 assert(path != NULL);
290 bzero(fpath, sizeof(fpath));
292 if (*path != '.')
293 fpath[0] = '.';
294 strlcat(fpath, path, PATHBUF);
296 if ((client->fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
297 warn("open: %s", fpath);
298 if (!start_reply(fds, client, NOT_FOUND, "not found"))
299 return;
300 goodbye(fds, client);
301 return;
304 if (isdir(client->fd)) {
305 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
306 close(client->fd);
307 client->fd = -1;
308 send_dir(fpath, fds, client);
309 return;
312 if (!start_reply(fds, client, SUCCESS, mime(fpath)))
313 return;
316 while (1) {
317 w = read(client->fd, buf, sizeof(buf));
318 if (w == -1)
319 warn("read");
320 if (w == 0 || w == -1) {
321 goodbye(fds, client);
322 return;
325 t = w;
326 i = 0;
328 while (w > 0) {
329 t = tls_write(client->ctx, buf+i, w);
330 switch (t) {
331 case -1:
332 warnx("tls_write: %s", tls_error(client->ctx));
333 goodbye(fds, client);
334 return;
336 case TLS_WANT_POLLIN:
337 case TLS_WANT_POLLOUT:
338 fds->events = (t == TLS_WANT_POLLIN)
339 ? POLLIN
340 : POLLOUT;
341 return;
343 default:
344 w -= t;
345 i += t;
346 break;
352 void
353 send_dir(char *path, struct pollfd *fds, struct client *client)
355 char fpath[PATHBUF];
356 size_t len;
358 bzero(fpath, PATHBUF);
360 if (*path != '.')
361 fpath[0] = '.';
363 /* this cannot fail since sizeof(fpath) > maxlen of path */
364 strlcat(fpath, path, PATHBUF);
365 len = strlen(fpath);
367 /* add a trailing / in case. */
368 if (fpath[len-1] != '/') {
369 fpath[len] = '/';
372 strlcat(fpath, "index.gmi", sizeof(fpath));
374 send_file(fpath, fds, client);
377 void
378 handle(struct pollfd *fds, struct client *client)
380 char buf[GEMINI_URL_LEN];
381 char *path;
383 switch (client->state) {
384 case S_OPEN:
385 bzero(buf, GEMINI_URL_LEN);
386 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
387 case -1:
388 warnx("tls_read: %s", tls_error(client->ctx));
389 goodbye(fds, client);
390 return;
392 case TLS_WANT_POLLIN:
393 fds->events = POLLIN;
394 return;
396 case TLS_WANT_POLLOUT:
397 fds->events = POLLOUT;
398 return;
401 if (!url_trim(buf)) {
402 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
403 return;
404 goodbye(fds, client);
405 return;
408 if ((path = url_start_of_request(buf)) == NULL) {
409 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
410 return;
411 goodbye(fds, client);
412 return;
415 adjust_path(path);
416 fprintf(stderr, "requested path: %s\n", path);
418 if (path_isdir(path))
419 send_dir(path, fds, client);
420 else
421 send_file(path, fds, client);
422 break;
424 case S_INITIALIZING:
425 if (!start_reply(fds, client, client->code, client->meta))
426 return;
428 if (client->code != SUCCESS) {
429 /* we don't need a body */
430 goodbye(fds, client);
431 return;
434 client->state = S_SENDING;
436 /* fallthrough */
438 case S_SENDING:
439 send_file(NULL, fds, client);
440 break;
442 case S_CLOSING:
443 goodbye(fds, client);
444 break;
446 default:
447 /* unreachable */
448 abort();
452 void
453 mark_nonblock(int fd)
455 int flags;
457 if ((flags = fcntl(fd, F_GETFL)) == -1)
458 err(1, "fcntl(F_GETFL)");
459 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
460 err(1, "fcntl(F_SETFL)");
463 int
464 make_socket(int port)
466 int sock, v;
467 struct sockaddr_in addr;
469 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
470 err(1, "socket");
472 v = 1;
473 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
474 err(1, "setsockopt(SO_REUSEADDR)");
476 v = 1;
477 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
478 err(1, "setsockopt(SO_REUSEPORT)");
480 mark_nonblock(sock);
482 bzero(&addr, sizeof(addr));
483 addr.sin_family = AF_INET;
484 addr.sin_port = htons(port);
485 addr.sin_addr.s_addr = INADDR_ANY;
487 if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
488 err(1, "bind");
490 if (listen(sock, 16) == -1)
491 err(1, "listen");
493 return sock;
496 void
497 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
499 int i, fd;
500 struct sockaddr_in addr;
501 socklen_t len;
503 len = sizeof(addr);
504 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
505 if (errno == EWOULDBLOCK)
506 return;
507 err(1, "accept");
510 mark_nonblock(fd);
512 for (i = 0; i < MAX_USERS; ++i) {
513 if (fds[i].fd == -1) {
514 bzero(&clients[i], sizeof(struct client));
515 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
516 break; /* goodbye fd! */
518 fds[i].fd = fd;
519 fds[i].events = POLLIN;
521 clients[i].state = S_OPEN;
522 clients[i].fd = -1;
524 return;
528 printf("too much clients. goodbye bro!\n");
529 close(fd);
532 void
533 goodbye(struct pollfd *pfd, struct client *c)
535 ssize_t ret;
537 c->state = S_CLOSING;
539 ret = tls_close(c->ctx);
540 if (ret == TLS_WANT_POLLIN) {
541 pfd->events = POLLIN;
542 return;
544 if (ret == TLS_WANT_POLLOUT) {
545 pfd->events = POLLOUT;
546 return;
549 tls_free(c->ctx);
550 c->ctx = NULL;
552 if (c->fd != -1)
553 close(c->fd);
555 close(pfd->fd);
556 pfd->fd = -1;
559 void
560 loop(struct tls *ctx, int sock)
562 int i, todo;
563 struct client clients[MAX_USERS];
564 struct pollfd fds[MAX_USERS];
566 for (i = 0; i < MAX_USERS; ++i) {
567 fds[i].fd = -1;
568 fds[i].events = POLLIN;
569 bzero(&clients[i], sizeof(struct client));
572 fds[0].fd = sock;
574 for (;;) {
575 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
576 err(1, "poll");
578 for (i = 0; i < MAX_USERS; i++) {
579 assert(i < MAX_USERS);
581 if (fds[i].revents == 0)
582 continue;
584 if (fds[i].revents & (POLLERR|POLLNVAL))
585 err(1, "bad fd %d", fds[i].fd);
587 if (fds[i].revents & POLLHUP) {
588 goodbye(&fds[i], &clients[i]);
589 continue;
592 todo--;
594 if (i == 0) { /* new client */
595 do_accept(sock, ctx, fds, clients);
596 continue;
599 handle(&fds[i], &clients[i]);
605 void
606 usage(const char *me)
608 fprintf(stderr,
609 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
610 me);
613 int
614 main(int argc, char **argv)
616 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
617 struct tls *ctx = NULL;
618 struct tls_config *conf;
619 int sock, ch;
621 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
622 switch (ch) {
623 case 'c':
624 cert = optarg;
625 break;
627 case 'd':
628 dir = optarg;
629 break;
631 case 'h':
632 usage(*argv);
633 return 0;
635 case 'k':
636 key = optarg;
637 break;
639 default:
640 usage(*argv);
641 return 1;
645 if ((conf = tls_config_new()) == NULL)
646 err(1, "tls_config_new");
648 if (tls_config_set_protocols(conf,
649 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
650 err(1, "tls_config_set_protocols");
652 if (tls_config_set_cert_file(conf, cert) == -1)
653 err(1, "tls_config_set_cert_file: %s", cert);
655 if (tls_config_set_key_file(conf, key) == -1)
656 err(1, "tls_config_set_key_file: %s", key);
658 if ((ctx = tls_server()) == NULL)
659 err(1, "tls_server");
661 if (tls_configure(ctx, conf) == -1)
662 errx(1, "tls_configure: %s", tls_error(ctx));
664 sock = make_socket(1965);
666 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
667 err(1, "open: %s", dir);
669 if (unveil(dir, "r") == -1)
670 err(1, "unveil");
672 if (pledge("stdio rpath inet", "") == -1)
673 err(1, "pledge");
675 loop(ctx, sock);
677 close(sock);
678 tls_free(ctx);
679 tls_config_free(conf);