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__); \
110 const char *dir, *cgi;
112 int connected_clients;
114 void siginfo_handler(int);
115 int starts_with(const char*, const char*);
117 char *url_after_proto(char*);
118 char *url_start_of_request(char*);
119 int url_trim(struct client*, char*);
120 char *adjust_path(char*);
121 int path_isdir(char*);
122 ssize_t filesize(int);
124 int start_reply(struct pollfd*, struct client*, int, const char*);
125 const char *path_ext(const char*);
126 const char *mime(const char*);
127 int open_file(char*, char*, struct pollfd*, struct client*);
128 void start_cgi(const char*, const char*, struct pollfd*, struct client*);
129 void cgi_setpoll_on_child(struct pollfd*, struct client*);
130 void cgi_setpoll_on_client(struct pollfd*, struct client*);
131 void handle_cgi(struct pollfd*, struct client*);
132 void send_file(char*, char*, struct pollfd*, struct client*);
133 void send_dir(char*, struct pollfd*, struct client*);
134 void handle(struct pollfd*, struct client*);
136 void mark_nonblock(int);
138 void do_accept(int, struct tls*, struct pollfd*, struct client*);
139 void goodbye(struct pollfd*, struct client*);
140 void loop(struct tls*, int);
142 void usage(const char*);
145 siginfo_handler(int sig)
151 starts_with(const char *str, const char *prefix)
155 for (i = 0; prefix[i] != '\0'; ++i)
156 if (str[i] != prefix[i])
162 url_after_proto(char *url)
165 const char *proto = "gemini";
166 const char *marker = "://";
169 if ((s = strstr(url, marker)) == NULL)
172 if (s - strlen(proto) != url)
175 if (!starts_with(url, proto))
178 /* a valid gemini:// URL */
179 return s + strlen(marker);
183 url_start_of_request(char *url)
187 if ((s = url_after_proto(url)) == NULL)
190 if ((t = strstr(s, "/")) == NULL)
191 return s + strlen(s);
196 url_trim(struct client *c, char *url)
198 const char *e = "\r\n";
201 if ((s = strstr(url, e)) == NULL)
207 LOG(c, "%s", "request longer than 1024 bytes\n");
215 adjust_path(char *path)
220 if ((query = strchr(path, '?')) != NULL) {
228 if (!strcmp(&path[len-3], "/..")) {
233 /* if the path is only `..` trim out and exit */
234 if (!strcmp(path, "..")) {
239 /* remove every ../ in the path */
241 if ((s = strstr(path, "../")) == NULL)
243 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
248 path_isdir(char *path)
252 return path[strlen(path)-1] == '/';
256 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
258 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
263 client->meta = reason;
264 client->state = S_INITIALIZING;
266 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
267 assert(len < (int)sizeof(buf));
268 ret = tls_write(client->ctx, buf, len);
269 if (ret == TLS_WANT_POLLIN) {
270 pfd->events = POLLIN;
274 if (ret == TLS_WANT_POLLOUT) {
275 pfd->events = POLLOUT;
287 if ((len = lseek(fd, 0, SEEK_END)) == -1)
289 if (lseek(fd, 0, SEEK_SET) == -1)
295 path_ext(const char *path)
299 end = path + strlen(path)-1; /* the last byte before the NUL */
300 for (; end != path; --end) {
311 mime(const char *path)
313 const char *ext, *def = "application/octet-stream";
316 if ((ext = path_ext(path)) == NULL)
319 for (t = filetypes; t->mime != NULL; ++t)
320 if (!strcmp(ext, t->ext))
327 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
332 assert(path != NULL);
334 bzero(fpath, sizeof(fpath));
338 strlcat(fpath, path, PATHBUF);
340 if ((c->fd = openat(dirfd, fpath,
341 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
342 LOG(c, "open failed: %s", fpath);
343 if (!start_reply(fds, c, NOT_FOUND, "not found"))
349 if (fstat(c->fd, &sb) == -1) {
350 LOG(c, "fstat failed for %s", fpath);
351 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
357 if (S_ISDIR(sb.st_mode)) {
358 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
361 send_dir(fpath, fds, c);
365 /* +2 to skip the ./ */
366 if ((sb.st_mode & S_IXUSR) && cgi != NULL && starts_with(fpath+2, cgi)) {
367 start_cgi(fpath, query, fds, c);
371 if ((c->len = filesize(c->fd)) == -1) {
372 LOG(c, "failed to get file size for %s", fpath);
377 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
378 c->fd, 0)) == MAP_FAILED) {
379 warn("mmap: %s", fpath);
385 return start_reply(fds, c, SUCCESS, mime(fpath));
389 start_cgi(const char *path, const char *query,
390 struct pollfd *fds, struct client *c)
398 switch (pid = fork()) {
402 case 0: { /* child */
404 char addr[INET_ADDRSTRLEN];
405 char *argv[] = { NULL, NULL, NULL };
407 /* skip the initial ./ */
410 close(p[0]); /* close the read end */
411 if (dup2(p[1], 1) == -1)
414 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
417 /* skip the ./ at the start of path*/
418 if (asprintf(&expath, "%s%s", dir, path) == -1)
420 argv[0] = argv[1] = expath;
423 setenv("SERVER_SOFTWARE", "gmid", 1);
424 /* setenv("SERVER_NAME", "", 1); */
425 /* setenv("GATEWAY_INTERFACE", "CGI/version", 1); */
426 setenv("SERVER_PROTOCOL", "gemini", 1);
427 setenv("SERVER_PORT", "1965", 1);
428 setenv("PATH_INFO", path, 1);
429 setenv("PATH_TRANSLATED", expath, 1);
431 setenv("QUERY_STRING", query, 1);
432 setenv("REMOTE_ADDR", addr, 1);
434 execvp(expath, argv);
438 default: /* parent */
439 close(p[1]); /* close the write end */
443 mark_nonblock(c->fd);
444 c->state = S_SENDING;
450 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
456 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
459 /* don't call atexit stuff */
464 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
468 if (c->waiting_on_child)
470 c->waiting_on_child = 1;
472 fds->events = POLLIN;
480 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
484 if (!c->waiting_on_child)
486 c->waiting_on_child = 0;
494 handle_cgi(struct pollfd *fds, struct client *c)
498 /* ensure c->fd is the child and fds->fd the client */
499 cgi_setpoll_on_client(fds, c);
503 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
506 if (errno == EAGAIN || errno == EWOULDBLOCK) {
507 cgi_setpoll_on_child(fds, c);
517 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
521 case TLS_WANT_POLLOUT:
522 fds->events = POLLOUT;
525 case TLS_WANT_POLLIN:
526 fds->events = POLLIN;
542 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
547 if (!open_file(path, query, fds, c))
549 c->state = S_SENDING;
552 len = (c->buf + c->len) - c->i;
555 switch (ret = tls_write(c->ctx, c->i, len)) {
557 LOG(c, "tls_write: %s", tls_error(c->ctx));
561 case TLS_WANT_POLLIN:
562 fds->events = POLLIN;
565 case TLS_WANT_POLLOUT:
566 fds->events = POLLOUT;
580 send_dir(char *path, struct pollfd *fds, struct client *client)
585 bzero(fpath, PATHBUF);
590 /* this cannot fail since sizeof(fpath) > maxlen of path */
591 strlcat(fpath, path, PATHBUF);
594 /* add a trailing / in case. */
595 if (fpath[len-1] != '/') {
599 strlcat(fpath, "index.gmi", sizeof(fpath));
601 send_file(fpath, NULL, fds, client);
605 handle(struct pollfd *fds, struct client *client)
607 char buf[GEMINI_URL_LEN];
611 switch (client->state) {
613 bzero(buf, GEMINI_URL_LEN);
614 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
616 LOG(client, "tls_read: %s", tls_error(client->ctx));
617 goodbye(fds, client);
620 case TLS_WANT_POLLIN:
621 fds->events = POLLIN;
624 case TLS_WANT_POLLOUT:
625 fds->events = POLLOUT;
629 if (!url_trim(client, buf)) {
630 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
632 goodbye(fds, client);
636 if ((path = url_start_of_request(buf)) == NULL) {
637 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
639 goodbye(fds, client);
643 query = adjust_path(path);
644 LOG(client, "get %s%s%s", path,
648 if (path_isdir(path))
649 send_dir(path, fds, client);
651 send_file(path, query, fds, client);
655 if (!start_reply(fds, client, client->code, client->meta))
658 if (client->code != SUCCESS) {
659 /* we don't need a body */
660 goodbye(fds, client);
664 client->state = S_SENDING;
669 if (client->child != -1)
670 handle_cgi(fds, client);
672 send_file(NULL, NULL, fds, client);
676 goodbye(fds, client);
686 mark_nonblock(int fd)
690 if ((flags = fcntl(fd, F_GETFL)) == -1)
691 err(1, "fcntl(F_GETFL)");
692 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
693 err(1, "fcntl(F_SETFL)");
697 make_socket(int port, int family)
700 struct sockaddr_in addr4;
701 struct sockaddr_in6 addr6;
702 struct sockaddr *addr;
707 bzero(&addr4, sizeof(addr4));
708 addr4.sin_family = family;
709 addr4.sin_port = htons(port);
710 addr4.sin_addr.s_addr = INADDR_ANY;
711 addr = (struct sockaddr*)&addr4;
716 bzero(&addr6, sizeof(addr6));
717 addr6.sin6_family = AF_INET6;
718 addr6.sin6_port = htons(port);
719 addr6.sin6_addr = in6addr_any;
720 addr = (struct sockaddr*)&addr6;
729 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
733 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
734 err(1, "setsockopt(SO_REUSEADDR)");
737 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
738 err(1, "setsockopt(SO_REUSEPORT)");
742 if (bind(sock, addr, len) == -1)
745 if (listen(sock, 16) == -1)
752 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
755 struct sockaddr_in addr;
759 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
760 if (errno == EWOULDBLOCK)
767 for (i = 0; i < MAX_USERS; ++i) {
768 if (fds[i].fd == -1) {
769 bzero(&clients[i], sizeof(struct client));
770 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
771 break; /* goodbye fd! */
774 fds[i].events = POLLIN;
776 clients[i].state = S_OPEN;
778 clients[i].child = -1;
779 clients[i].buf = MAP_FAILED;
780 clients[i].af = AF_INET;
781 clients[i].addr = addr.sin_addr;
792 goodbye(struct pollfd *pfd, struct client *c)
796 c->state = S_CLOSING;
798 ret = tls_close(c->ctx);
799 if (ret == TLS_WANT_POLLIN) {
800 pfd->events = POLLIN;
803 if (ret == TLS_WANT_POLLOUT) {
804 pfd->events = POLLOUT;
813 if (c->buf != MAP_FAILED)
814 munmap(c->buf, c->len);
824 loop(struct tls *ctx, int sock)
827 struct client clients[MAX_USERS];
828 struct pollfd fds[MAX_USERS];
830 for (i = 0; i < MAX_USERS; ++i) {
832 fds[i].events = POLLIN;
833 bzero(&clients[i], sizeof(struct client));
839 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
840 if (errno == EINTR) {
841 warnx("connected clients: %d", connected_clients);
847 for (i = 0; i < MAX_USERS; i++) {
848 assert(i < MAX_USERS);
850 if (fds[i].revents == 0)
853 if (fds[i].revents & (POLLERR|POLLNVAL))
854 err(1, "bad fd %d", fds[i].fd);
856 if (fds[i].revents & POLLHUP) {
857 /* fds[i] may be the fd of the stdin
858 * of a cgi script that has exited. */
859 if (!clients[i].waiting_on_child) {
860 goodbye(&fds[i], &clients[i]);
867 if (i == 0) { /* new client */
868 do_accept(sock, ctx, fds, clients);
872 handle(&fds[i], &clients[i]);
878 usage(const char *me)
881 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
882 "[-l logfile] [-x cgi-bin]\n",
887 main(int argc, char **argv)
889 const char *cert = "cert.pem", *key = "key.pem";
890 struct tls *ctx = NULL;
891 struct tls_config *conf;
894 signal(SIGPIPE, SIG_IGN);
895 signal(SIGCHLD, SIG_IGN);
898 signal(SIGINFO, siginfo_handler);
900 signal(SIGUSR2, siginfo_handler);
902 connected_clients = 0;
905 logfd = 2; /* stderr */
908 while ((ch = getopt(argc, argv, "c:d:hk:l:x:")) != -1) {
927 /* open log file or create it with 644 */
928 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
929 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
930 err(1, "%s", optarg);
943 if ((conf = tls_config_new()) == NULL)
944 err(1, "tls_config_new");
946 if (tls_config_set_protocols(conf,
947 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
948 err(1, "tls_config_set_protocols");
950 if (tls_config_set_cert_file(conf, cert) == -1)
951 err(1, "tls_config_set_cert_file: %s", cert);
953 if (tls_config_set_key_file(conf, key) == -1)
954 err(1, "tls_config_set_key_file: %s", key);
956 if ((ctx = tls_server()) == NULL)
957 err(1, "tls_server");
959 if (tls_configure(ctx, conf) == -1)
960 errx(1, "tls_configure: %s", tls_error(ctx));
962 sock = make_socket(1965, AF_INET);
964 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
965 err(1, "open: %s", dir);
968 if (unveil(dir, "rx") == -1)
970 if (pledge("stdio rpath inet proc exec", NULL) == -1)
973 if (unveil(dir, "r") == -1)
975 if (pledge("stdio rpath inet", NULL) == -1)
983 tls_config_free(conf);