2 * Copyright (c) 2020 Omar Polo <op@omarpolo.com>
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.
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.
18 #include <sys/socket.h>
21 #include <arpa/inet.h>
22 #include <netinet/in.h>
37 # define pledge(a, b) 0
38 # define unveil(a, b) 0
39 #endif /* __OpenBSD__ */
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 */
51 #define TEMP_FAILURE 40
53 #define BAD_REQUEST 59
79 struct etm { /* file extension to mime */
83 {"application/pdf", "pdf"},
86 {"image/jpeg", "jpg"},
87 {"image/jpeg", "jpeg"},
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"},
101 #define LOG(c, fmt, ...) \
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__); \
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);
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*);
139 url_after_proto(char *url)
142 const char *proto = "gemini";
143 const char *marker = "://";
147 if ((s = strstr(url, marker)) == NULL)
150 if (s - strlen(proto) != url)
153 for (i = 0; proto[i] != '\0'; ++i)
154 if (url[i] != proto[i])
157 /* a valid gemini:// URL */
158 return s + strlen(marker);
162 url_start_of_request(char *url)
166 if ((s = url_after_proto(url)) == NULL)
169 if ((t = strstr(s, "/")) == NULL)
170 return s + strlen(s);
175 url_trim(struct client *c, char *url)
177 const char *e = "\r\n";
180 if ((s = strstr(url, e)) == NULL)
186 LOG(c, "%s", "request longer than 1024 bytes\n");
194 adjust_path(char *path)
199 if ((query = strchr(path, '?')) != NULL) {
207 if (!strcmp(&path[len-3], "/..")) {
212 /* if the path is only `..` trim out and exit */
213 if (!strcmp(path, "..")) {
218 /* remove every ../ in the path */
220 if ((s = strstr(path, "../")) == NULL)
222 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
227 path_isdir(char *path)
231 return path[strlen(path)-1] == '/';
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 */
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;
253 if (ret == TLS_WANT_POLLOUT) {
254 pfd->events = POLLOUT;
266 if ((len = lseek(fd, 0, SEEK_END)) == -1)
268 if (lseek(fd, 0, SEEK_SET) == -1)
274 path_ext(const char *path)
278 end = path + strlen(path)-1; /* the last byte before the NUL */
279 for (; end != path; --end) {
290 mime(const char *path)
292 const char *ext, *def = "application/octet-stream";
295 if ((ext = path_ext(path)) == NULL)
298 for (t = filetypes; t->mime != NULL; ++t)
299 if (!strcmp(ext, t->ext))
306 open_file(char *path, struct pollfd *fds, struct client *c)
311 assert(path != NULL);
313 bzero(fpath, sizeof(fpath));
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"))
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"))
336 if (S_ISDIR(sb.st_mode)) {
337 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
340 send_dir(fpath, fds, c);
344 if (cgi && (sb.st_mode & S_IXUSR)) {
345 start_cgi(fpath, fds, c);
349 if ((c->len = filesize(c->fd)) == -1) {
350 LOG(c, "failed to get file size for %s", fpath);
355 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
356 c->fd, 0)) == MAP_FAILED) {
357 warn("mmap: %s", fpath);
363 return start_reply(fds, c, SUCCESS, mime(fpath));
367 start_cgi(const char *path, struct pollfd *fds, struct client *c)
375 switch (pid = fork()) {
379 case 0: { /* child */
381 char addr[INET_ADDRSTRLEN];
382 char *argv[] = { NULL, NULL, NULL };
388 "SERVER_SOFTWARE=gmid",
389 /* "SERVER_NAME=example.com", */
390 /* "GATEWAY_INTERFACE=CGI/version" */
391 "SERVER_PROTOCOL=gemini",
394 /* "PATH_TRANSLATED=" */
396 /* "QUERY_STRING=" */
402 close(p[0]); /* close the read end */
403 if (dup2(p[1], 1) == -1)
406 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
409 /* skip the ./ at the start of path*/
410 if (asprintf(&expath, "%s%s", dir, path+2) == -1)
412 argv[0] = argv[1] = expath;
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="))
420 /* else if (!strcmp(envp[i], "PATH_INFO")) */
424 execvpe(expath, argv, envp);
428 default: /* parent */
429 close(p[1]); /* close the write end */
438 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
444 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
450 handle_cgi(struct pollfd *fds, struct client *c)
456 r = read(c->fd, buf, sizeof(buf));
457 if (r == -1 || r == 0)
461 switch (r = tls_write(c->ctx, buf, todo)) {
465 case TLS_WANT_POLLOUT:
466 case TLS_WANT_POLLIN:
481 send_file(char *path, struct pollfd *fds, struct client *c)
486 if (!open_file(path, fds, c))
488 c->state = S_SENDING;
491 len = (c->buf + c->len) - c->i;
494 switch (ret = tls_write(c->ctx, c->i, len)) {
496 LOG(c, "tls_write: %s", tls_error(c->ctx));
500 case TLS_WANT_POLLIN:
501 fds->events = POLLIN;
504 case TLS_WANT_POLLOUT:
505 fds->events = POLLOUT;
519 send_dir(char *path, struct pollfd *fds, struct client *client)
524 bzero(fpath, PATHBUF);
529 /* this cannot fail since sizeof(fpath) > maxlen of path */
530 strlcat(fpath, path, PATHBUF);
533 /* add a trailing / in case. */
534 if (fpath[len-1] != '/') {
538 strlcat(fpath, "index.gmi", sizeof(fpath));
540 send_file(fpath, fds, client);
544 handle(struct pollfd *fds, struct client *client)
546 char buf[GEMINI_URL_LEN];
550 switch (client->state) {
552 bzero(buf, GEMINI_URL_LEN);
553 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
555 LOG(client, "tls_read: %s", tls_error(client->ctx));
556 goodbye(fds, client);
559 case TLS_WANT_POLLIN:
560 fds->events = POLLIN;
563 case TLS_WANT_POLLOUT:
564 fds->events = POLLOUT;
568 if (!url_trim(client, buf)) {
569 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
571 goodbye(fds, client);
575 if ((path = url_start_of_request(buf)) == NULL) {
576 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
578 goodbye(fds, client);
582 query = adjust_path(path);
583 LOG(client, "get %s%s%s", path,
587 if (path_isdir(path))
588 send_dir(path, fds, client);
590 send_file(path, fds, client);
594 if (!start_reply(fds, client, client->code, client->meta))
597 if (client->code != SUCCESS) {
598 /* we don't need a body */
599 goodbye(fds, client);
603 client->state = S_SENDING;
608 send_file(NULL, fds, client);
612 goodbye(fds, client);
622 mark_nonblock(int fd)
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)");
633 make_socket(int port, int family)
636 struct sockaddr_in addr4;
637 struct sockaddr_in6 addr6;
638 struct sockaddr *addr;
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;
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;
665 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
669 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
670 err(1, "setsockopt(SO_REUSEADDR)");
673 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
674 err(1, "setsockopt(SO_REUSEPORT)");
678 if (bind(sock, addr, len) == -1)
681 if (listen(sock, 16) == -1)
688 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
691 struct sockaddr_in addr;
695 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
696 if (errno == EWOULDBLOCK)
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! */
710 fds[i].events = POLLIN;
712 clients[i].state = S_OPEN;
714 clients[i].child = -1;
715 clients[i].buf = MAP_FAILED;
716 clients[i].af = AF_INET;
717 clients[i].addr = addr.sin_addr;
727 goodbye(struct pollfd *pfd, struct client *c)
731 c->state = S_CLOSING;
733 ret = tls_close(c->ctx);
734 if (ret == TLS_WANT_POLLIN) {
735 pfd->events = POLLIN;
738 if (ret == TLS_WANT_POLLOUT) {
739 pfd->events = POLLOUT;
746 if (c->buf != MAP_FAILED)
747 munmap(c->buf, c->len);
757 loop(struct tls *ctx, int sock)
760 struct client clients[MAX_USERS];
761 struct pollfd fds[MAX_USERS];
763 for (i = 0; i < MAX_USERS; ++i) {
765 fds[i].events = POLLIN;
766 bzero(&clients[i], sizeof(struct client));
772 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
775 for (i = 0; i < MAX_USERS; i++) {
776 assert(i < MAX_USERS);
778 if (fds[i].revents == 0)
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]);
791 if (i == 0) { /* new client */
792 do_accept(sock, ctx, fds, clients);
796 handle(&fds[i], &clients[i]);
802 usage(const char *me)
805 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
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;
817 signal(SIGPIPE, SIG_IGN);
818 signal(SIGCHLD, SIG_IGN);
821 logfd = 2; /* stderr */
824 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
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);
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)
886 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
893 tls_config_free(conf);