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 char *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 = "://";
144 size_t i;
146 /* a relative URL */
147 if ((s = strstr(url, marker)) == NULL)
148 return url;
150 if (s - strlen(proto) != url)
151 return NULL;
153 for (i = 0; proto[i] != '\0'; ++i)
154 if (url[i] != proto[i])
155 return NULL;
157 /* a valid gemini:// URL */
158 return s + strlen(marker);
161 char *
162 url_start_of_request(char *url)
164 char *s, *t;
166 if ((s = url_after_proto(url)) == NULL)
167 return NULL;
169 if ((t = strstr(s, "/")) == NULL)
170 return s + strlen(s);
171 return t;
174 int
175 url_trim(struct client *c, char *url)
177 const char *e = "\r\n";
178 char *s;
180 if ((s = strstr(url, e)) == NULL)
181 return 0;
182 s[0] = '\0';
183 s[1] = '\0';
185 if (s[2] != '\0') {
186 LOG(c, "%s", "request longer than 1024 bytes\n");
187 return 0;
190 return 1;
193 char *
194 adjust_path(char *path)
196 char *s, *query;
197 size_t len;
199 if ((query = strchr(path, '?')) != NULL) {
200 *query = '\0';
201 query++;
204 /* /.. -> / */
205 len = strlen(path);
206 if (len >= 3) {
207 if (!strcmp(&path[len-3], "/..")) {
208 path[len-2] = '\0';
212 /* if the path is only `..` trim out and exit */
213 if (!strcmp(path, "..")) {
214 path[0] = '\0';
215 return query;
218 /* remove every ../ in the path */
219 while (1) {
220 if ((s = strstr(path, "../")) == NULL)
221 return query;
222 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
226 int
227 path_isdir(char *path)
229 if (*path == '\0')
230 return 1;
231 return path[strlen(path)-1] == '/';
234 int
235 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
237 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
238 int len;
239 int ret;
241 client->code = code;
242 client->meta = reason;
243 client->state = S_INITIALIZING;
245 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
246 assert(len < (int)sizeof(buf));
247 ret = tls_write(client->ctx, buf, len);
248 if (ret == TLS_WANT_POLLIN) {
249 pfd->events = POLLIN;
250 return 0;
253 if (ret == TLS_WANT_POLLOUT) {
254 pfd->events = POLLOUT;
255 return 0;
258 return 1;
261 ssize_t
262 filesize(int fd)
264 ssize_t len;
266 if ((len = lseek(fd, 0, SEEK_END)) == -1)
267 return -1;
268 if (lseek(fd, 0, SEEK_SET) == -1)
269 return -1;
270 return len;
273 const char *
274 path_ext(const char *path)
276 const char *end;
278 end = path + strlen(path)-1; /* the last byte before the NUL */
279 for (; end != path; --end) {
280 if (*end == '.')
281 return end+1;
282 if (*end == '/')
283 break;
286 return NULL;
289 const char *
290 mime(const char *path)
292 const char *ext, *def = "application/octet-stream";
293 struct etm *t;
295 if ((ext = path_ext(path)) == NULL)
296 return def;
298 for (t = filetypes; t->mime != NULL; ++t)
299 if (!strcmp(ext, t->ext))
300 return t->mime;
302 return def;
305 int
306 open_file(char *path, struct pollfd *fds, struct client *c)
308 char fpath[PATHBUF];
309 struct stat sb;
311 assert(path != NULL);
313 bzero(fpath, sizeof(fpath));
315 if (*path != '.')
316 fpath[0] = '.';
317 strlcat(fpath, path, PATHBUF);
319 if ((c->fd = openat(dirfd, fpath,
320 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -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 (fstat(c->fd, &sb) == -1) {
329 LOG(c, "fstat failed for %s", fpath);
330 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
331 return 0;
332 goodbye(fds, c);
333 return 0;
336 if (S_ISDIR(sb.st_mode)) {
337 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
338 close(c->fd);
339 c->fd = -1;
340 send_dir(fpath, fds, c);
341 return 0;
344 if (cgi && (sb.st_mode & S_IXUSR)) {
345 start_cgi(fpath, fds, c);
346 return 0;
349 if ((c->len = filesize(c->fd)) == -1) {
350 LOG(c, "failed to get file size for %s", fpath);
351 goodbye(fds, c);
352 return 0;
355 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
356 c->fd, 0)) == MAP_FAILED) {
357 warn("mmap: %s", fpath);
358 goodbye(fds, c);
359 return 0;
361 c->i = c->buf;
363 return start_reply(fds, c, SUCCESS, mime(fpath));
366 void
367 start_cgi(const char *path, struct pollfd *fds, struct client *c)
369 pid_t pid;
370 int p[2];
372 if (pipe(p) == -1)
373 goto err;
375 switch (pid = fork()) {
376 case -1:
377 goto err;
379 case 0: { /* child */
380 char *expath;
381 char addr[INET_ADDRSTRLEN];
382 char *argv[] = { NULL, NULL, NULL };
383 char *envp[] = {
384 /* inherited */
385 "PATH=",
387 /* CGI */
388 "SERVER_SOFTWARE=gmid",
389 /* "SERVER_NAME=example.com", */
390 /* "GATEWAY_INTERFACE=CGI/version" */
391 "SERVER_PROTOCOL=gemini",
392 "SERVER_PORT=1965",
393 /* "PATH_INFO=" */
394 /* "PATH_TRANSLATED=" */
395 /* "SCRIPT_NAME=" */
396 /* "QUERY_STRING=" */
397 "REMOTE_ADDR=",
398 NULL,
399 };
400 size_t i;
402 close(p[0]); /* close the read end */
403 if (dup2(p[1], 1) == -1)
404 goto childerr;
406 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
407 goto childerr;
409 /* skip the ./ at the start of path*/
410 if (asprintf(&expath, "%s%s", dir, path+2) == -1)
411 goto childerr;
412 argv[0] = argv[1] = expath;
414 /* fix the envp */
415 for (i = 0; envp[i] != NULL; ++i) {
416 if (!strcmp(envp[i], "PATH="))
417 envp[i] = getenv("PATH");
418 else if (!strcmp(envp[i], "REMOTE_ADDR="))
419 envp[i] = addr;
420 /* else if (!strcmp(envp[i], "PATH_INFO")) */
421 /* ... */
424 execvpe(expath, argv, envp);
425 goto childerr;
428 default: /* parent */
429 close(p[1]); /* close the write end */
430 close(c->fd);
431 c->fd = p[0];
432 c->child = pid;
433 handle_cgi(fds, c);
434 return;
437 err:
438 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
439 return;
440 goodbye(fds, c);
441 return;
443 childerr:
444 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
445 close(p[1]);
446 _exit(1);
449 void
450 handle_cgi(struct pollfd *fds, struct client *c)
452 char buf[1024];
453 ssize_t r, todo;
455 while (1) {
456 r = read(c->fd, buf, sizeof(buf));
457 if (r == -1 || r == 0)
458 break;
459 todo = r;
460 while (todo > 0) {
461 switch (r = tls_write(c->ctx, buf, todo)) {
462 case -1:
463 goto end;
465 case TLS_WANT_POLLOUT:
466 case TLS_WANT_POLLIN:
467 /* evil! */
468 continue;
470 default:
471 todo -= r;
476 end:
477 goodbye(fds, c);
480 void
481 send_file(char *path, struct pollfd *fds, struct client *c)
483 ssize_t ret, len;
485 if (c->fd == -1) {
486 if (!open_file(path, fds, c))
487 return;
488 c->state = S_SENDING;
491 len = (c->buf + c->len) - c->i;
493 while (len > 0) {
494 switch (ret = tls_write(c->ctx, c->i, len)) {
495 case -1:
496 LOG(c, "tls_write: %s", tls_error(c->ctx));
497 goodbye(fds, c);
498 return;
500 case TLS_WANT_POLLIN:
501 fds->events = POLLIN;
502 return;
504 case TLS_WANT_POLLOUT:
505 fds->events = POLLOUT;
506 return;
508 default:
509 c->i += ret;
510 len -= ret;
511 break;
515 goodbye(fds, c);
518 void
519 send_dir(char *path, struct pollfd *fds, struct client *client)
521 char fpath[PATHBUF];
522 size_t len;
524 bzero(fpath, PATHBUF);
526 if (path[0] != '.')
527 fpath[0] = '.';
529 /* this cannot fail since sizeof(fpath) > maxlen of path */
530 strlcat(fpath, path, PATHBUF);
531 len = strlen(fpath);
533 /* add a trailing / in case. */
534 if (fpath[len-1] != '/') {
535 fpath[len] = '/';
538 strlcat(fpath, "index.gmi", sizeof(fpath));
540 send_file(fpath, fds, client);
543 void
544 handle(struct pollfd *fds, struct client *client)
546 char buf[GEMINI_URL_LEN];
547 char *path;
548 char *query;
550 switch (client->state) {
551 case S_OPEN:
552 bzero(buf, GEMINI_URL_LEN);
553 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
554 case -1:
555 LOG(client, "tls_read: %s", tls_error(client->ctx));
556 goodbye(fds, client);
557 return;
559 case TLS_WANT_POLLIN:
560 fds->events = POLLIN;
561 return;
563 case TLS_WANT_POLLOUT:
564 fds->events = POLLOUT;
565 return;
568 if (!url_trim(client, buf)) {
569 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
570 return;
571 goodbye(fds, client);
572 return;
575 if ((path = url_start_of_request(buf)) == NULL) {
576 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
577 return;
578 goodbye(fds, client);
579 return;
582 query = adjust_path(path);
583 LOG(client, "get %s%s%s", path,
584 query ? "?" : "",
585 query ? query : "");
587 if (path_isdir(path))
588 send_dir(path, fds, client);
589 else
590 send_file(path, fds, client);
591 break;
593 case S_INITIALIZING:
594 if (!start_reply(fds, client, client->code, client->meta))
595 return;
597 if (client->code != SUCCESS) {
598 /* we don't need a body */
599 goodbye(fds, client);
600 return;
603 client->state = S_SENDING;
605 /* fallthrough */
607 case S_SENDING:
608 send_file(NULL, fds, client);
609 break;
611 case S_CLOSING:
612 goodbye(fds, client);
613 break;
615 default:
616 /* unreachable */
617 abort();
621 void
622 mark_nonblock(int fd)
624 int flags;
626 if ((flags = fcntl(fd, F_GETFL)) == -1)
627 err(1, "fcntl(F_GETFL)");
628 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
629 err(1, "fcntl(F_SETFL)");
632 int
633 make_socket(int port, int family)
635 int sock, v;
636 struct sockaddr_in addr4;
637 struct sockaddr_in6 addr6;
638 struct sockaddr *addr;
639 socklen_t len;
641 switch (family) {
642 case AF_INET:
643 bzero(&addr4, sizeof(addr4));
644 addr4.sin_family = family;
645 addr4.sin_port = htons(port);
646 addr4.sin_addr.s_addr = INADDR_ANY;
647 addr = (struct sockaddr*)&addr4;
648 len = sizeof(addr4);
649 break;
651 case AF_INET6:
652 bzero(&addr6, sizeof(addr6));
653 addr6.sin6_family = AF_INET6;
654 addr6.sin6_port = htons(port);
655 addr6.sin6_addr = in6addr_any;
656 addr = (struct sockaddr*)&addr6;
657 len = sizeof(addr6);
658 break;
660 default:
661 /* unreachable */
662 abort();
665 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
666 err(1, "socket");
668 v = 1;
669 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
670 err(1, "setsockopt(SO_REUSEADDR)");
672 v = 1;
673 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
674 err(1, "setsockopt(SO_REUSEPORT)");
676 mark_nonblock(sock);
678 if (bind(sock, addr, len) == -1)
679 err(1, "bind");
681 if (listen(sock, 16) == -1)
682 err(1, "listen");
684 return sock;
687 void
688 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
690 int i, fd;
691 struct sockaddr_in addr;
692 socklen_t len;
694 len = sizeof(addr);
695 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
696 if (errno == EWOULDBLOCK)
697 return;
698 err(1, "accept");
701 mark_nonblock(fd);
703 for (i = 0; i < MAX_USERS; ++i) {
704 if (fds[i].fd == -1) {
705 bzero(&clients[i], sizeof(struct client));
706 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
707 break; /* goodbye fd! */
709 fds[i].fd = fd;
710 fds[i].events = POLLIN;
712 clients[i].state = S_OPEN;
713 clients[i].fd = -1;
714 clients[i].child = -1;
715 clients[i].buf = MAP_FAILED;
716 clients[i].af = AF_INET;
717 clients[i].addr = addr.sin_addr;
719 return;
723 close(fd);
726 void
727 goodbye(struct pollfd *pfd, struct client *c)
729 ssize_t ret;
731 c->state = S_CLOSING;
733 ret = tls_close(c->ctx);
734 if (ret == TLS_WANT_POLLIN) {
735 pfd->events = POLLIN;
736 return;
738 if (ret == TLS_WANT_POLLOUT) {
739 pfd->events = POLLOUT;
740 return;
743 tls_free(c->ctx);
744 c->ctx = NULL;
746 if (c->buf != MAP_FAILED)
747 munmap(c->buf, c->len);
749 if (c->fd != -1)
750 close(c->fd);
752 close(pfd->fd);
753 pfd->fd = -1;
756 void
757 loop(struct tls *ctx, int sock)
759 int i, todo;
760 struct client clients[MAX_USERS];
761 struct pollfd fds[MAX_USERS];
763 for (i = 0; i < MAX_USERS; ++i) {
764 fds[i].fd = -1;
765 fds[i].events = POLLIN;
766 bzero(&clients[i], sizeof(struct client));
769 fds[0].fd = sock;
771 for (;;) {
772 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
773 err(1, "poll");
775 for (i = 0; i < MAX_USERS; i++) {
776 assert(i < MAX_USERS);
778 if (fds[i].revents == 0)
779 continue;
781 if (fds[i].revents & (POLLERR|POLLNVAL))
782 err(1, "bad fd %d", fds[i].fd);
784 if (fds[i].revents & POLLHUP) {
785 goodbye(&fds[i], &clients[i]);
786 continue;
789 todo--;
791 if (i == 0) { /* new client */
792 do_accept(sock, ctx, fds, clients);
793 continue;
796 handle(&fds[i], &clients[i]);
801 void
802 usage(const char *me)
804 fprintf(stderr,
805 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
806 me);
809 int
810 main(int argc, char **argv)
812 const char *cert = "cert.pem", *key = "key.pem";
813 struct tls *ctx = NULL;
814 struct tls_config *conf;
815 int sock, ch;
817 signal(SIGPIPE, SIG_IGN);
818 signal(SIGCHLD, SIG_IGN);
820 dir = "docs/";
821 logfd = 2; /* stderr */
822 cgi = 0;
824 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
825 switch (ch) {
826 case 'c':
827 cert = optarg;
828 break;
830 case 'd':
831 dir = optarg;
832 break;
834 case 'h':
835 usage(*argv);
836 return 0;
838 case 'k':
839 key = optarg;
840 break;
842 case 'l':
843 /* open log file or create it with 644 */
844 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
845 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
846 err(1, "%s", optarg);
847 break;
849 case 'x':
850 cgi = 1;
851 break;
853 default:
854 usage(*argv);
855 return 1;
859 if ((conf = tls_config_new()) == NULL)
860 err(1, "tls_config_new");
862 if (tls_config_set_protocols(conf,
863 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
864 err(1, "tls_config_set_protocols");
866 if (tls_config_set_cert_file(conf, cert) == -1)
867 err(1, "tls_config_set_cert_file: %s", cert);
869 if (tls_config_set_key_file(conf, key) == -1)
870 err(1, "tls_config_set_key_file: %s", key);
872 if ((ctx = tls_server()) == NULL)
873 err(1, "tls_server");
875 if (tls_configure(ctx, conf) == -1)
876 errx(1, "tls_configure: %s", tls_error(ctx));
878 sock = make_socket(1965, AF_INET);
880 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
881 err(1, "open: %s", dir);
883 if (unveil(dir, cgi ? "rx" : "r") == -1)
884 err(1, "unveil");
886 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
887 err(1, "pledge");
889 loop(ctx, sock);
891 close(sock);
892 tls_free(ctx);
893 tls_config_free(conf);