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
71 int fd, waiting_on_child;
73 char sbuf[1024]; /* static buffer */
74 void *buf, *i; /* mmap buffer */
75 ssize_t len, off; /* mmap/static buffer */
80 struct etm { /* file extension to mime */
84 {"application/pdf", "pdf"},
87 {"image/jpeg", "jpg"},
88 {"image/jpeg", "jpeg"},
90 {"image/svg+xml", "svg"},
92 {"text/gemini", "gemini"},
93 {"text/gemini", "gmi"},
94 {"text/markdown", "markdown"},
95 {"text/markdown", "md"},
96 {"text/plain", "txt"},
102 #define LOG(c, fmt, ...) \
104 char buf[INET_ADDRSTRLEN]; \
105 if (inet_ntop((c)->af, &(c)->addr, buf, sizeof(buf)) == NULL) \
106 err(1, "inet_ntop"); \
107 dprintf(logfd, "[%s] " fmt "\n", buf, __VA_ARGS__); \
114 char *url_after_proto(char*);
115 char *url_start_of_request(char*);
116 int url_trim(struct client*, char*);
117 char *adjust_path(char*);
118 int path_isdir(char*);
119 ssize_t filesize(int);
121 int start_reply(struct pollfd*, struct client*, int, const char*);
122 const char *path_ext(const char*);
123 const char *mime(const char*);
124 int open_file(char*, char*, struct pollfd*, struct client*);
125 void start_cgi(const char*, const char*, struct pollfd*, struct client*);
126 void cgi_setpoll_on_child(struct pollfd*, struct client*);
127 void cgi_setpoll_on_client(struct pollfd*, struct client*);
128 void handle_cgi(struct pollfd*, struct client*);
129 void send_file(char*, char*, struct pollfd*, struct client*);
130 void send_dir(char*, struct pollfd*, struct client*);
131 void handle(struct pollfd*, struct client*);
133 void mark_nonblock(int);
135 void do_accept(int, struct tls*, struct pollfd*, struct client*);
136 void goodbye(struct pollfd*, struct client*);
137 void loop(struct tls*, int);
139 void usage(const char*);
142 url_after_proto(char *url)
145 const char *proto = "gemini";
146 const char *marker = "://";
150 if ((s = strstr(url, marker)) == NULL)
153 if (s - strlen(proto) != url)
156 for (i = 0; proto[i] != '\0'; ++i)
157 if (url[i] != proto[i])
160 /* a valid gemini:// URL */
161 return s + strlen(marker);
165 url_start_of_request(char *url)
169 if ((s = url_after_proto(url)) == NULL)
172 if ((t = strstr(s, "/")) == NULL)
173 return s + strlen(s);
178 url_trim(struct client *c, char *url)
180 const char *e = "\r\n";
183 if ((s = strstr(url, e)) == NULL)
189 LOG(c, "%s", "request longer than 1024 bytes\n");
197 adjust_path(char *path)
202 if ((query = strchr(path, '?')) != NULL) {
210 if (!strcmp(&path[len-3], "/..")) {
215 /* if the path is only `..` trim out and exit */
216 if (!strcmp(path, "..")) {
221 /* remove every ../ in the path */
223 if ((s = strstr(path, "../")) == NULL)
225 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
230 path_isdir(char *path)
234 return path[strlen(path)-1] == '/';
238 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
240 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
245 client->meta = reason;
246 client->state = S_INITIALIZING;
248 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
249 assert(len < (int)sizeof(buf));
250 ret = tls_write(client->ctx, buf, len);
251 if (ret == TLS_WANT_POLLIN) {
252 pfd->events = POLLIN;
256 if (ret == TLS_WANT_POLLOUT) {
257 pfd->events = POLLOUT;
269 if ((len = lseek(fd, 0, SEEK_END)) == -1)
271 if (lseek(fd, 0, SEEK_SET) == -1)
277 path_ext(const char *path)
281 end = path + strlen(path)-1; /* the last byte before the NUL */
282 for (; end != path; --end) {
293 mime(const char *path)
295 const char *ext, *def = "application/octet-stream";
298 if ((ext = path_ext(path)) == NULL)
301 for (t = filetypes; t->mime != NULL; ++t)
302 if (!strcmp(ext, t->ext))
309 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
314 assert(path != NULL);
316 bzero(fpath, sizeof(fpath));
320 strlcat(fpath, path, PATHBUF);
322 if ((c->fd = openat(dirfd, fpath,
323 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
324 LOG(c, "open failed: %s", fpath);
325 if (!start_reply(fds, c, NOT_FOUND, "not found"))
331 if (fstat(c->fd, &sb) == -1) {
332 LOG(c, "fstat failed for %s", fpath);
333 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
339 if (S_ISDIR(sb.st_mode)) {
340 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
343 send_dir(fpath, fds, c);
347 if (cgi && (sb.st_mode & S_IXUSR)) {
348 start_cgi(fpath, query, fds, c);
352 if ((c->len = filesize(c->fd)) == -1) {
353 LOG(c, "failed to get file size for %s", fpath);
358 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
359 c->fd, 0)) == MAP_FAILED) {
360 warn("mmap: %s", fpath);
366 return start_reply(fds, c, SUCCESS, mime(fpath));
370 start_cgi(const char *path, const char *query,
371 struct pollfd *fds, struct client *c)
379 switch (pid = fork()) {
383 case 0: { /* child */
385 char addr[INET_ADDRSTRLEN];
386 char *argv[] = { NULL, NULL, NULL };
388 /* skip the initial ./ */
391 close(p[0]); /* close the read end */
392 if (dup2(p[1], 1) == -1)
395 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
398 /* skip the ./ at the start of path*/
399 if (asprintf(&expath, "%s%s", dir, path) == -1)
401 argv[0] = argv[1] = expath;
404 setenv("SERVER_SOFTWARE", "gmid", 1);
405 /* setenv("SERVER_NAME", "", 1); */
406 /* setenv("GATEWAY_INTERFACE", "CGI/version", 1); */
407 setenv("SERVER_PROTOCOL", "gemini", 1);
408 setenv("SERVER_PORT", "1965", 1);
409 setenv("PATH_INFO", path, 1);
410 setenv("PATH_TRANSLATED", expath, 1);
411 setenv("QUERY_STRING", query ? query : "", 1);
412 setenv("REMOTE_ADDR", addr, 1);
414 execvp(expath, argv);
418 default: /* parent */
419 close(p[1]); /* close the write end */
423 mark_nonblock(c->fd);
424 c->state = S_SENDING;
430 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
436 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
439 /* don't call atexit stuff */
444 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
448 if (c->waiting_on_child)
450 c->waiting_on_child = 1;
452 fds->events = POLLIN;
460 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
464 if (!c->waiting_on_child)
466 c->waiting_on_child = 0;
474 handle_cgi(struct pollfd *fds, struct client *c)
478 /* ensure c->fd is the child and fds->fd the client */
479 cgi_setpoll_on_client(fds, c);
483 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
486 if (errno == EAGAIN || errno == EWOULDBLOCK) {
487 cgi_setpoll_on_child(fds, c);
497 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
501 case TLS_WANT_POLLOUT:
502 fds->events = POLLOUT;
505 case TLS_WANT_POLLIN:
506 fds->events = POLLIN;
522 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
527 if (!open_file(path, query, fds, c))
529 c->state = S_SENDING;
532 len = (c->buf + c->len) - c->i;
535 switch (ret = tls_write(c->ctx, c->i, len)) {
537 LOG(c, "tls_write: %s", tls_error(c->ctx));
541 case TLS_WANT_POLLIN:
542 fds->events = POLLIN;
545 case TLS_WANT_POLLOUT:
546 fds->events = POLLOUT;
560 send_dir(char *path, struct pollfd *fds, struct client *client)
565 bzero(fpath, PATHBUF);
570 /* this cannot fail since sizeof(fpath) > maxlen of path */
571 strlcat(fpath, path, PATHBUF);
574 /* add a trailing / in case. */
575 if (fpath[len-1] != '/') {
579 strlcat(fpath, "index.gmi", sizeof(fpath));
581 send_file(fpath, NULL, fds, client);
585 handle(struct pollfd *fds, struct client *client)
587 char buf[GEMINI_URL_LEN];
591 switch (client->state) {
593 bzero(buf, GEMINI_URL_LEN);
594 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
596 LOG(client, "tls_read: %s", tls_error(client->ctx));
597 goodbye(fds, client);
600 case TLS_WANT_POLLIN:
601 fds->events = POLLIN;
604 case TLS_WANT_POLLOUT:
605 fds->events = POLLOUT;
609 if (!url_trim(client, buf)) {
610 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
612 goodbye(fds, client);
616 if ((path = url_start_of_request(buf)) == NULL) {
617 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
619 goodbye(fds, client);
623 query = adjust_path(path);
624 LOG(client, "get %s%s%s", path,
628 if (path_isdir(path))
629 send_dir(path, fds, client);
631 send_file(path, query, fds, client);
635 if (!start_reply(fds, client, client->code, client->meta))
638 if (client->code != SUCCESS) {
639 /* we don't need a body */
640 goodbye(fds, client);
644 client->state = S_SENDING;
649 if (client->child != -1)
650 handle_cgi(fds, client);
652 send_file(NULL, NULL, fds, client);
656 goodbye(fds, client);
666 mark_nonblock(int fd)
670 if ((flags = fcntl(fd, F_GETFL)) == -1)
671 err(1, "fcntl(F_GETFL)");
672 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
673 err(1, "fcntl(F_SETFL)");
677 make_socket(int port, int family)
680 struct sockaddr_in addr4;
681 struct sockaddr_in6 addr6;
682 struct sockaddr *addr;
687 bzero(&addr4, sizeof(addr4));
688 addr4.sin_family = family;
689 addr4.sin_port = htons(port);
690 addr4.sin_addr.s_addr = INADDR_ANY;
691 addr = (struct sockaddr*)&addr4;
696 bzero(&addr6, sizeof(addr6));
697 addr6.sin6_family = AF_INET6;
698 addr6.sin6_port = htons(port);
699 addr6.sin6_addr = in6addr_any;
700 addr = (struct sockaddr*)&addr6;
709 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
713 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
714 err(1, "setsockopt(SO_REUSEADDR)");
717 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
718 err(1, "setsockopt(SO_REUSEPORT)");
722 if (bind(sock, addr, len) == -1)
725 if (listen(sock, 16) == -1)
732 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
735 struct sockaddr_in addr;
739 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
740 if (errno == EWOULDBLOCK)
747 for (i = 0; i < MAX_USERS; ++i) {
748 if (fds[i].fd == -1) {
749 bzero(&clients[i], sizeof(struct client));
750 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
751 break; /* goodbye fd! */
754 fds[i].events = POLLIN;
756 clients[i].state = S_OPEN;
758 clients[i].child = -1;
759 clients[i].buf = MAP_FAILED;
760 clients[i].af = AF_INET;
761 clients[i].addr = addr.sin_addr;
771 goodbye(struct pollfd *pfd, struct client *c)
775 c->state = S_CLOSING;
777 ret = tls_close(c->ctx);
778 if (ret == TLS_WANT_POLLIN) {
779 pfd->events = POLLIN;
782 if (ret == TLS_WANT_POLLOUT) {
783 pfd->events = POLLOUT;
790 if (c->buf != MAP_FAILED)
791 munmap(c->buf, c->len);
801 loop(struct tls *ctx, int sock)
804 struct client clients[MAX_USERS];
805 struct pollfd fds[MAX_USERS];
807 for (i = 0; i < MAX_USERS; ++i) {
809 fds[i].events = POLLIN;
810 bzero(&clients[i], sizeof(struct client));
816 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
819 for (i = 0; i < MAX_USERS; i++) {
820 assert(i < MAX_USERS);
822 if (fds[i].revents == 0)
825 if (fds[i].revents & (POLLERR|POLLNVAL))
826 err(1, "bad fd %d", fds[i].fd);
828 if (fds[i].revents & POLLHUP) {
829 /* fds[i] may be the fd of the stdin
830 * of a cgi script that has exited. */
831 if (!clients[i].waiting_on_child) {
832 goodbye(&fds[i], &clients[i]);
839 if (i == 0) { /* new client */
840 do_accept(sock, ctx, fds, clients);
844 handle(&fds[i], &clients[i]);
850 usage(const char *me)
853 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
858 main(int argc, char **argv)
860 const char *cert = "cert.pem", *key = "key.pem";
861 struct tls *ctx = NULL;
862 struct tls_config *conf;
865 signal(SIGPIPE, SIG_IGN);
866 signal(SIGCHLD, SIG_IGN);
869 logfd = 2; /* stderr */
872 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
891 /* open log file or create it with 644 */
892 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
893 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
894 err(1, "%s", optarg);
907 if ((conf = tls_config_new()) == NULL)
908 err(1, "tls_config_new");
910 if (tls_config_set_protocols(conf,
911 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
912 err(1, "tls_config_set_protocols");
914 if (tls_config_set_cert_file(conf, cert) == -1)
915 err(1, "tls_config_set_cert_file: %s", cert);
917 if (tls_config_set_key_file(conf, key) == -1)
918 err(1, "tls_config_set_key_file: %s", key);
920 if ((ctx = tls_server()) == NULL)
921 err(1, "tls_server");
923 if (tls_configure(ctx, conf) == -1)
924 errx(1, "tls_configure: %s", tls_error(ctx));
926 sock = make_socket(1965, AF_INET);
928 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
929 err(1, "open: %s", dir);
931 if (unveil(dir, cgi ? "rx" : "r") == -1)
934 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
941 tls_config_free(conf);