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 TEMP_FAILURE 40
52 #define NOT_FOUND 51
53 #define BAD_REQUEST 59
55 #ifndef MAX_USERS
56 #define MAX_USERS 64
57 #endif
59 enum {
60 S_OPEN,
61 S_INITIALIZING,
62 S_SENDING,
63 S_CLOSING,
64 };
66 struct client {
67 struct tls *ctx;
68 int state;
69 int code;
70 const char *meta;
71 int fd;
72 pid_t child;
73 void *buf, *i;
74 ssize_t len, off;
75 int af;
76 struct in_addr addr;
77 };
79 struct etm { /* file extension to mime */
80 const char *mime;
81 const char *ext;
82 } filetypes[] = {
83 {"application/pdf", "pdf"},
85 {"image/gif", "gif"},
86 {"image/jpeg", "jpg"},
87 {"image/jpeg", "jpeg"},
88 {"image/png", "png"},
89 {"image/svg+xml", "svg"},
91 {"text/gemini", "gemini"},
92 {"text/gemini", "gmi"},
93 {"text/markdown", "markdown"},
94 {"text/markdown", "md"},
95 {"text/plain", "txt"},
96 {"text/xml", "xml"},
98 {NULL, NULL}
99 };
101 #define LOG(c, fmt, ...) \
102 do { \
103 char buf[INET_ADDRSTRLEN]; \
104 if (inet_ntop((c)->af, &(c)->addr, buf, sizeof(buf)) == NULL) \
105 err(1, "inet_ntop"); \
106 dprintf(logfd, "[%s] " fmt "\n", buf, __VA_ARGS__); \
107 } while (0)
109 const char *dir;
110 int dirfd, logfd;
111 int cgi;
113 char *url_after_proto(char*);
114 char *url_start_of_request(char*);
115 int url_trim(struct client*, char*);
116 void adjust_path(char*);
117 int path_isdir(char*);
118 ssize_t filesize(int);
120 int start_reply(struct pollfd*, struct client*, int, const char*);
121 const char *path_ext(const char*);
122 const char *mime(const char*);
123 int open_file(char*, struct pollfd*, struct client*);
124 void start_cgi(const char*, struct pollfd*, struct client*);
125 void handle_cgi(struct pollfd*, struct client*);
126 void send_file(char*, struct pollfd*, struct client*);
127 void send_dir(char*, struct pollfd*, struct client*);
128 void handle(struct pollfd*, struct client*);
130 void mark_nonblock(int);
131 int make_soket(int);
132 void do_accept(int, struct tls*, struct pollfd*, struct client*);
133 void goodbye(struct pollfd*, struct client*);
134 void loop(struct tls*, int);
136 void usage(const char*);
138 char *
139 url_after_proto(char *url)
141 char *s;
142 const char *proto = "gemini";
143 const char *marker = "://";
145 if ((s = strstr(url, marker)) == NULL)
146 return url;
148 /* not a gemini:// URL */
150 if (s - strlen(proto) < url)
151 return NULL;
152 /* TODO: */
153 /* if (strcmp(s - strlen(proto), proto)) */
154 /* return NULL; */
156 /* a valid gemini:// URL */
157 return s + strlen(marker);
160 char *
161 url_start_of_request(char *url)
163 char *s, *t;
165 if ((s = url_after_proto(url)) == NULL)
166 return NULL;
168 if ((t = strstr(s, "/")) == NULL)
169 return s + strlen(s);
170 return t;
173 int
174 url_trim(struct client *c, char *url)
176 const char *e = "\r\n";
177 char *s;
179 if ((s = strstr(url, e)) == NULL)
180 return 0;
181 s[0] = '\0';
182 s[1] = '\0';
184 if (s[2] != '\0') {
185 LOG(c, "%s", "request longer than 1024 bytes\n");
186 return 0;
189 return 1;
192 void
193 adjust_path(char *path)
195 char *s;
196 size_t len;
198 /* /.. -> / */
199 len = strlen(path);
200 if (len >= 3) {
201 if (!strcmp(&path[len-3], "/..")) {
202 path[len-2] = '\0';
206 /* if the path is only `..` trim out and exit */
207 if (!strcmp(path, "..")) {
208 path[0] = '\0';
209 return;
212 /* remove every ../ in the path */
213 while (1) {
214 if ((s = strstr(path, "../")) == NULL)
215 return;
216 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
220 int
221 path_isdir(char *path)
223 if (*path == '\0')
224 return 1;
225 return path[strlen(path)-1] == '/';
228 int
229 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
231 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
232 int len;
233 int ret;
235 client->code = code;
236 client->meta = reason;
237 client->state = S_INITIALIZING;
239 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
240 assert(len < (int)sizeof(buf));
241 ret = tls_write(client->ctx, buf, len);
242 if (ret == TLS_WANT_POLLIN) {
243 pfd->events = POLLIN;
244 return 0;
247 if (ret == TLS_WANT_POLLOUT) {
248 pfd->events = POLLOUT;
249 return 0;
252 return 1;
255 ssize_t
256 filesize(int fd)
258 ssize_t len;
260 if ((len = lseek(fd, 0, SEEK_END)) == -1)
261 return -1;
262 if (lseek(fd, 0, SEEK_SET) == -1)
263 return -1;
264 return len;
267 const char *
268 path_ext(const char *path)
270 const char *end;
272 end = path + strlen(path)-1; /* the last byte before the NUL */
273 for (; end != path; --end) {
274 if (*end == '.')
275 return end+1;
276 if (*end == '/')
277 break;
280 return NULL;
283 const char *
284 mime(const char *path)
286 const char *ext, *def = "application/octet-stream";
287 struct etm *t;
289 if ((ext = path_ext(path)) == NULL)
290 return def;
292 for (t = filetypes; t->mime != NULL; ++t)
293 if (!strcmp(ext, t->ext))
294 return t->mime;
296 return def;
299 int
300 open_file(char *path, struct pollfd *fds, struct client *c)
302 char fpath[PATHBUF];
303 struct stat sb;
305 assert(path != NULL);
307 bzero(fpath, sizeof(fpath));
309 if (*path != '.')
310 fpath[0] = '.';
311 strlcat(fpath, path, PATHBUF);
313 if ((c->fd = openat(dirfd, fpath,
314 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
315 LOG(c, "open failed: %s", fpath);
316 if (!start_reply(fds, c, NOT_FOUND, "not found"))
317 return 0;
318 goodbye(fds, c);
319 return 0;
322 if (fstat(c->fd, &sb) == -1) {
323 LOG(c, "fstat failed for %s", fpath);
324 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
325 return 0;
326 goodbye(fds, c);
327 return 0;
330 if (S_ISDIR(sb.st_mode)) {
331 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
332 close(c->fd);
333 c->fd = -1;
334 send_dir(fpath, fds, c);
335 return 0;
338 if (cgi && (sb.st_mode & S_IXUSR)) {
339 start_cgi(fpath, fds, c);
340 return 0;
343 if ((c->len = filesize(c->fd)) == -1) {
344 LOG(c, "failed to get file size for %s", fpath);
345 goodbye(fds, c);
346 return 0;
349 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
350 c->fd, 0)) == MAP_FAILED) {
351 warn("mmap: %s", fpath);
352 goodbye(fds, c);
353 return 0;
355 c->i = c->buf;
357 return start_reply(fds, c, SUCCESS, mime(fpath));
360 void
361 start_cgi(const char *path, struct pollfd *fds, struct client *c)
363 pid_t pid;
364 int p[2];
366 if (pipe(p) == -1)
367 goto err;
369 switch (pid = fork()) {
370 case -1:
371 goto err;
373 case 0: { /* child */
374 char *expath;
375 char addr[INET_ADDRSTRLEN];
376 char *argv[] = { NULL, NULL, NULL };
377 char *envp[] = {
378 /* inherited */
379 "PATH=",
381 /* CGI */
382 "SERVER_SOFTWARE=gmid",
383 /* "SERVER_NAME=example.com", */
384 /* "GATEWAY_INTERFACE=CGI/version" */
385 "SERVER_PROTOCOL=gemini",
386 "SERVER_PORT=1965",
387 /* "PATH_INFO=" */
388 /* "PATH_TRANSLATED=" */
389 /* "SCRIPT_NAME=" */
390 /* "QUERY_STRING=" */
391 "REMOTE_ADDR=",
392 NULL,
393 };
394 size_t i;
396 close(p[0]); /* close the read end */
397 if (dup2(p[1], 1) == -1)
398 goto childerr;
400 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
401 goto childerr;
403 /* skip the ./ at the start of path*/
404 if (asprintf(&expath, "%s%s", dir, path+2) == -1)
405 goto childerr;
406 argv[0] = argv[1] = expath;
408 /* fix the envp */
409 for (i = 0; envp[i] != NULL; ++i) {
410 if (!strcmp(envp[i], "PATH="))
411 envp[i] = getenv("PATH");
412 else if (!strcmp(envp[i], "REMOTE_ADDR="))
413 envp[i] = addr;
414 /* else if (!strcmp(envp[i], "PATH_INFO")) */
415 /* ... */
418 execvpe(expath, argv, envp);
419 goto childerr;
422 default: /* parent */
423 close(p[1]); /* close the write end */
424 close(c->fd);
425 c->fd = p[0];
426 c->child = pid;
427 handle_cgi(fds, c);
428 return;
431 err:
432 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
433 return;
434 goodbye(fds, c);
435 return;
437 childerr:
438 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
439 close(p[1]);
440 _exit(1);
443 void
444 handle_cgi(struct pollfd *fds, struct client *c)
446 char buf[1024];
447 ssize_t r, todo;
449 while (1) {
450 r = read(c->fd, buf, sizeof(buf));
451 if (r == -1 || r == 0)
452 break;
453 todo = r;
454 while (todo > 0) {
455 switch (r = tls_write(c->ctx, buf, todo)) {
456 case -1:
457 goto end;
459 case TLS_WANT_POLLOUT:
460 case TLS_WANT_POLLIN:
461 /* evil! */
462 continue;
464 default:
465 todo -= r;
470 end:
471 goodbye(fds, c);
474 void
475 send_file(char *path, struct pollfd *fds, struct client *c)
477 ssize_t ret, len;
479 if (c->fd == -1) {
480 if (!open_file(path, fds, c))
481 return;
482 c->state = S_SENDING;
485 len = (c->buf + c->len) - c->i;
487 while (len > 0) {
488 switch (ret = tls_write(c->ctx, c->i, len)) {
489 case -1:
490 LOG(c, "tls_write: %s", tls_error(c->ctx));
491 goodbye(fds, c);
492 return;
494 case TLS_WANT_POLLIN:
495 fds->events = POLLIN;
496 return;
498 case TLS_WANT_POLLOUT:
499 fds->events = POLLOUT;
500 return;
502 default:
503 c->i += ret;
504 len -= ret;
505 break;
509 goodbye(fds, c);
512 void
513 send_dir(char *path, struct pollfd *fds, struct client *client)
515 char fpath[PATHBUF];
516 size_t len;
518 bzero(fpath, PATHBUF);
520 if (path[0] != '.')
521 fpath[0] = '.';
523 /* this cannot fail since sizeof(fpath) > maxlen of path */
524 strlcat(fpath, path, PATHBUF);
525 len = strlen(fpath);
527 /* add a trailing / in case. */
528 if (fpath[len-1] != '/') {
529 fpath[len] = '/';
532 strlcat(fpath, "index.gmi", sizeof(fpath));
534 send_file(fpath, fds, client);
537 void
538 handle(struct pollfd *fds, struct client *client)
540 char buf[GEMINI_URL_LEN];
541 char *path;
543 switch (client->state) {
544 case S_OPEN:
545 bzero(buf, GEMINI_URL_LEN);
546 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
547 case -1:
548 LOG(client, "tls_read: %s", tls_error(client->ctx));
549 goodbye(fds, client);
550 return;
552 case TLS_WANT_POLLIN:
553 fds->events = POLLIN;
554 return;
556 case TLS_WANT_POLLOUT:
557 fds->events = POLLOUT;
558 return;
561 if (!url_trim(client, buf)) {
562 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
563 return;
564 goodbye(fds, client);
565 return;
568 if ((path = url_start_of_request(buf)) == NULL) {
569 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
570 return;
571 goodbye(fds, client);
572 return;
575 adjust_path(path);
576 LOG(client, "get %s", path);
578 if (path_isdir(path))
579 send_dir(path, fds, client);
580 else
581 send_file(path, fds, client);
582 break;
584 case S_INITIALIZING:
585 if (!start_reply(fds, client, client->code, client->meta))
586 return;
588 if (client->code != SUCCESS) {
589 /* we don't need a body */
590 goodbye(fds, client);
591 return;
594 client->state = S_SENDING;
596 /* fallthrough */
598 case S_SENDING:
599 send_file(NULL, fds, client);
600 break;
602 case S_CLOSING:
603 goodbye(fds, client);
604 break;
606 default:
607 /* unreachable */
608 abort();
612 void
613 mark_nonblock(int fd)
615 int flags;
617 if ((flags = fcntl(fd, F_GETFL)) == -1)
618 err(1, "fcntl(F_GETFL)");
619 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
620 err(1, "fcntl(F_SETFL)");
623 int
624 make_socket(int port, int family)
626 int sock, v;
627 struct sockaddr_in addr4;
628 struct sockaddr_in6 addr6;
629 struct sockaddr *addr;
630 socklen_t len;
632 switch (family) {
633 case AF_INET:
634 bzero(&addr4, sizeof(addr4));
635 addr4.sin_family = family;
636 addr4.sin_port = htons(port);
637 addr4.sin_addr.s_addr = INADDR_ANY;
638 addr = (struct sockaddr*)&addr4;
639 len = sizeof(addr4);
640 break;
642 case AF_INET6:
643 bzero(&addr6, sizeof(addr6));
644 addr6.sin6_family = AF_INET6;
645 addr6.sin6_port = htons(port);
646 addr6.sin6_addr = in6addr_any;
647 addr = (struct sockaddr*)&addr6;
648 len = sizeof(addr6);
649 break;
651 default:
652 /* unreachable */
653 abort();
656 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
657 err(1, "socket");
659 v = 1;
660 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
661 err(1, "setsockopt(SO_REUSEADDR)");
663 v = 1;
664 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
665 err(1, "setsockopt(SO_REUSEPORT)");
667 mark_nonblock(sock);
669 if (bind(sock, addr, len) == -1)
670 err(1, "bind");
672 if (listen(sock, 16) == -1)
673 err(1, "listen");
675 return sock;
678 void
679 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
681 int i, fd;
682 struct sockaddr_in addr;
683 socklen_t len;
685 len = sizeof(addr);
686 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
687 if (errno == EWOULDBLOCK)
688 return;
689 err(1, "accept");
692 mark_nonblock(fd);
694 for (i = 0; i < MAX_USERS; ++i) {
695 if (fds[i].fd == -1) {
696 bzero(&clients[i], sizeof(struct client));
697 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
698 break; /* goodbye fd! */
700 fds[i].fd = fd;
701 fds[i].events = POLLIN;
703 clients[i].state = S_OPEN;
704 clients[i].fd = -1;
705 clients[i].child = -1;
706 clients[i].buf = MAP_FAILED;
707 clients[i].af = AF_INET;
708 clients[i].addr = addr.sin_addr;
710 return;
714 close(fd);
717 void
718 goodbye(struct pollfd *pfd, struct client *c)
720 ssize_t ret;
722 c->state = S_CLOSING;
724 ret = tls_close(c->ctx);
725 if (ret == TLS_WANT_POLLIN) {
726 pfd->events = POLLIN;
727 return;
729 if (ret == TLS_WANT_POLLOUT) {
730 pfd->events = POLLOUT;
731 return;
734 tls_free(c->ctx);
735 c->ctx = NULL;
737 if (c->buf != MAP_FAILED)
738 munmap(c->buf, c->len);
740 if (c->fd != -1)
741 close(c->fd);
743 close(pfd->fd);
744 pfd->fd = -1;
747 void
748 loop(struct tls *ctx, int sock)
750 int i, todo;
751 struct client clients[MAX_USERS];
752 struct pollfd fds[MAX_USERS];
754 for (i = 0; i < MAX_USERS; ++i) {
755 fds[i].fd = -1;
756 fds[i].events = POLLIN;
757 bzero(&clients[i], sizeof(struct client));
760 fds[0].fd = sock;
762 for (;;) {
763 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
764 err(1, "poll");
766 for (i = 0; i < MAX_USERS; i++) {
767 assert(i < MAX_USERS);
769 if (fds[i].revents == 0)
770 continue;
772 if (fds[i].revents & (POLLERR|POLLNVAL))
773 err(1, "bad fd %d", fds[i].fd);
775 if (fds[i].revents & POLLHUP) {
776 goodbye(&fds[i], &clients[i]);
777 continue;
780 todo--;
782 if (i == 0) { /* new client */
783 do_accept(sock, ctx, fds, clients);
784 continue;
787 handle(&fds[i], &clients[i]);
792 void
793 usage(const char *me)
795 fprintf(stderr,
796 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
797 me);
800 int
801 main(int argc, char **argv)
803 const char *cert = "cert.pem", *key = "key.pem";
804 struct tls *ctx = NULL;
805 struct tls_config *conf;
806 int sock, ch;
808 signal(SIGPIPE, SIG_IGN);
809 signal(SIGCHLD, SIG_IGN);
811 dir = "docs/";
812 logfd = 2; /* stderr */
813 cgi = 0;
815 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
816 switch (ch) {
817 case 'c':
818 cert = optarg;
819 break;
821 case 'd':
822 dir = optarg;
823 break;
825 case 'h':
826 usage(*argv);
827 return 0;
829 case 'k':
830 key = optarg;
831 break;
833 case 'l':
834 /* open log file or create it with 644 */
835 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
836 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
837 err(1, "%s", optarg);
838 break;
840 case 'x':
841 cgi = 1;
842 break;
844 default:
845 usage(*argv);
846 return 1;
850 if ((conf = tls_config_new()) == NULL)
851 err(1, "tls_config_new");
853 if (tls_config_set_protocols(conf,
854 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
855 err(1, "tls_config_set_protocols");
857 if (tls_config_set_cert_file(conf, cert) == -1)
858 err(1, "tls_config_set_cert_file: %s", cert);
860 if (tls_config_set_key_file(conf, key) == -1)
861 err(1, "tls_config_set_key_file: %s", key);
863 if ((ctx = tls_server()) == NULL)
864 err(1, "tls_server");
866 if (tls_configure(ctx, conf) == -1)
867 errx(1, "tls_configure: %s", tls_error(ctx));
869 sock = make_socket(1965, AF_INET);
871 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
872 err(1, "open: %s", dir);
874 if (unveil(dir, cgi ? "rx" : "r") == -1)
875 err(1, "unveil");
877 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
878 err(1, "pledge");
880 loop(ctx, sock);
882 close(sock);
883 tls_free(ctx);
884 tls_config_free(conf);