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 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);
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 = "://";
145 if ((s = strstr(url, marker)) == NULL)
148 /* not a gemini:// URL */
150 if (s - strlen(proto) < url)
153 /* if (strcmp(s - strlen(proto), proto)) */
156 /* a valid gemini:// URL */
157 return s + strlen(marker);
161 url_start_of_request(char *url)
165 if ((s = url_after_proto(url)) == NULL)
168 if ((t = strstr(s, "/")) == NULL)
169 return s + strlen(s);
174 url_trim(struct client *c, char *url)
176 const char *e = "\r\n";
179 if ((s = strstr(url, e)) == NULL)
185 LOG(c, "%s", "request longer than 1024 bytes\n");
193 adjust_path(char *path)
201 if (!strcmp(&path[len-3], "/..")) {
206 /* if the path is only `..` trim out and exit */
207 if (!strcmp(path, "..")) {
212 /* remove every ../ in the path */
214 if ((s = strstr(path, "../")) == NULL)
216 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
221 path_isdir(char *path)
225 return path[strlen(path)-1] == '/';
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 */
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;
247 if (ret == TLS_WANT_POLLOUT) {
248 pfd->events = POLLOUT;
260 if ((len = lseek(fd, 0, SEEK_END)) == -1)
262 if (lseek(fd, 0, SEEK_SET) == -1)
268 path_ext(const char *path)
272 end = path + strlen(path)-1; /* the last byte before the NUL */
273 for (; end != path; --end) {
284 mime(const char *path)
286 const char *ext, *def = "application/octet-stream";
289 if ((ext = path_ext(path)) == NULL)
292 for (t = filetypes; t->mime != NULL; ++t)
293 if (!strcmp(ext, t->ext))
300 open_file(char *path, struct pollfd *fds, struct client *c)
305 assert(path != NULL);
307 bzero(fpath, sizeof(fpath));
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"))
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"))
330 if (S_ISDIR(sb.st_mode)) {
331 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
334 send_dir(fpath, fds, c);
338 if (cgi && (sb.st_mode & S_IXUSR)) {
339 start_cgi(fpath, fds, c);
343 if ((c->len = filesize(c->fd)) == -1) {
344 LOG(c, "failed to get file size for %s", fpath);
349 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
350 c->fd, 0)) == MAP_FAILED) {
351 warn("mmap: %s", fpath);
357 return start_reply(fds, c, SUCCESS, mime(fpath));
361 start_cgi(const char *path, struct pollfd *fds, struct client *c)
369 switch (pid = fork()) {
373 case 0: { /* child */
375 char addr[INET_ADDRSTRLEN];
376 char *argv[] = { NULL, NULL, NULL };
382 "SERVER_SOFTWARE=gmid",
383 /* "SERVER_NAME=example.com", */
384 /* "GATEWAY_INTERFACE=CGI/version" */
385 "SERVER_PROTOCOL=gemini",
388 /* "PATH_TRANSLATED=" */
390 /* "QUERY_STRING=" */
396 close(p[0]); /* close the read end */
397 if (dup2(p[1], 1) == -1)
400 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
403 /* skip the ./ at the start of path*/
404 if (asprintf(&expath, "%s%s", dir, path+2) == -1)
406 argv[0] = argv[1] = expath;
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="))
414 /* else if (!strcmp(envp[i], "PATH_INFO")) */
418 execvpe(expath, argv, envp);
422 default: /* parent */
423 close(p[1]); /* close the write end */
432 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
438 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
444 handle_cgi(struct pollfd *fds, struct client *c)
450 r = read(c->fd, buf, sizeof(buf));
451 if (r == -1 || r == 0)
455 switch (r = tls_write(c->ctx, buf, todo)) {
459 case TLS_WANT_POLLOUT:
460 case TLS_WANT_POLLIN:
475 send_file(char *path, struct pollfd *fds, struct client *c)
480 if (!open_file(path, fds, c))
482 c->state = S_SENDING;
485 len = (c->buf + c->len) - c->i;
488 switch (ret = tls_write(c->ctx, c->i, len)) {
490 LOG(c, "tls_write: %s", tls_error(c->ctx));
494 case TLS_WANT_POLLIN:
495 fds->events = POLLIN;
498 case TLS_WANT_POLLOUT:
499 fds->events = POLLOUT;
513 send_dir(char *path, struct pollfd *fds, struct client *client)
518 bzero(fpath, PATHBUF);
523 /* this cannot fail since sizeof(fpath) > maxlen of path */
524 strlcat(fpath, path, PATHBUF);
527 /* add a trailing / in case. */
528 if (fpath[len-1] != '/') {
532 strlcat(fpath, "index.gmi", sizeof(fpath));
534 send_file(fpath, fds, client);
538 handle(struct pollfd *fds, struct client *client)
540 char buf[GEMINI_URL_LEN];
543 switch (client->state) {
545 bzero(buf, GEMINI_URL_LEN);
546 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
548 LOG(client, "tls_read: %s", tls_error(client->ctx));
549 goodbye(fds, client);
552 case TLS_WANT_POLLIN:
553 fds->events = POLLIN;
556 case TLS_WANT_POLLOUT:
557 fds->events = POLLOUT;
561 if (!url_trim(client, buf)) {
562 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
564 goodbye(fds, client);
568 if ((path = url_start_of_request(buf)) == NULL) {
569 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
571 goodbye(fds, client);
576 LOG(client, "get %s", path);
578 if (path_isdir(path))
579 send_dir(path, fds, client);
581 send_file(path, fds, client);
585 if (!start_reply(fds, client, client->code, client->meta))
588 if (client->code != SUCCESS) {
589 /* we don't need a body */
590 goodbye(fds, client);
594 client->state = S_SENDING;
599 send_file(NULL, fds, client);
603 goodbye(fds, client);
613 mark_nonblock(int fd)
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)");
624 make_socket(int port, int family)
627 struct sockaddr_in addr4;
628 struct sockaddr_in6 addr6;
629 struct sockaddr *addr;
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;
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;
656 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
660 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
661 err(1, "setsockopt(SO_REUSEADDR)");
664 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
665 err(1, "setsockopt(SO_REUSEPORT)");
669 if (bind(sock, addr, len) == -1)
672 if (listen(sock, 16) == -1)
679 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
682 struct sockaddr_in addr;
686 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
687 if (errno == EWOULDBLOCK)
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! */
701 fds[i].events = POLLIN;
703 clients[i].state = S_OPEN;
705 clients[i].child = -1;
706 clients[i].buf = MAP_FAILED;
707 clients[i].af = AF_INET;
708 clients[i].addr = addr.sin_addr;
718 goodbye(struct pollfd *pfd, struct client *c)
722 c->state = S_CLOSING;
724 ret = tls_close(c->ctx);
725 if (ret == TLS_WANT_POLLIN) {
726 pfd->events = POLLIN;
729 if (ret == TLS_WANT_POLLOUT) {
730 pfd->events = POLLOUT;
737 if (c->buf != MAP_FAILED)
738 munmap(c->buf, c->len);
748 loop(struct tls *ctx, int sock)
751 struct client clients[MAX_USERS];
752 struct pollfd fds[MAX_USERS];
754 for (i = 0; i < MAX_USERS; ++i) {
756 fds[i].events = POLLIN;
757 bzero(&clients[i], sizeof(struct client));
763 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
766 for (i = 0; i < MAX_USERS; i++) {
767 assert(i < MAX_USERS);
769 if (fds[i].revents == 0)
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]);
782 if (i == 0) { /* new client */
783 do_accept(sock, ctx, fds, clients);
787 handle(&fds[i], &clients[i]);
793 usage(const char *me)
796 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
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;
808 signal(SIGPIPE, SIG_IGN);
809 signal(SIGCHLD, SIG_IGN);
812 logfd = 2; /* stderr */
815 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
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);
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)
877 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
884 tls_config_free(conf);