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__); \
113 int connected_clients;
115 void siginfo_handler(int);
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 url_after_proto(char *url)
154 const char *proto = "gemini";
155 const char *marker = "://";
159 if ((s = strstr(url, marker)) == NULL)
162 if (s - strlen(proto) != url)
165 for (i = 0; proto[i] != '\0'; ++i)
166 if (url[i] != proto[i])
169 /* a valid gemini:// URL */
170 return s + strlen(marker);
174 url_start_of_request(char *url)
178 if ((s = url_after_proto(url)) == NULL)
181 if ((t = strstr(s, "/")) == NULL)
182 return s + strlen(s);
187 url_trim(struct client *c, char *url)
189 const char *e = "\r\n";
192 if ((s = strstr(url, e)) == NULL)
198 LOG(c, "%s", "request longer than 1024 bytes\n");
206 adjust_path(char *path)
211 if ((query = strchr(path, '?')) != NULL) {
219 if (!strcmp(&path[len-3], "/..")) {
224 /* if the path is only `..` trim out and exit */
225 if (!strcmp(path, "..")) {
230 /* remove every ../ in the path */
232 if ((s = strstr(path, "../")) == NULL)
234 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
239 path_isdir(char *path)
243 return path[strlen(path)-1] == '/';
247 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
249 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
254 client->meta = reason;
255 client->state = S_INITIALIZING;
257 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
258 assert(len < (int)sizeof(buf));
259 ret = tls_write(client->ctx, buf, len);
260 if (ret == TLS_WANT_POLLIN) {
261 pfd->events = POLLIN;
265 if (ret == TLS_WANT_POLLOUT) {
266 pfd->events = POLLOUT;
278 if ((len = lseek(fd, 0, SEEK_END)) == -1)
280 if (lseek(fd, 0, SEEK_SET) == -1)
286 path_ext(const char *path)
290 end = path + strlen(path)-1; /* the last byte before the NUL */
291 for (; end != path; --end) {
302 mime(const char *path)
304 const char *ext, *def = "application/octet-stream";
307 if ((ext = path_ext(path)) == NULL)
310 for (t = filetypes; t->mime != NULL; ++t)
311 if (!strcmp(ext, t->ext))
318 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
323 assert(path != NULL);
325 bzero(fpath, sizeof(fpath));
329 strlcat(fpath, path, PATHBUF);
331 if ((c->fd = openat(dirfd, fpath,
332 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
333 LOG(c, "open failed: %s", fpath);
334 if (!start_reply(fds, c, NOT_FOUND, "not found"))
340 if (fstat(c->fd, &sb) == -1) {
341 LOG(c, "fstat failed for %s", fpath);
342 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
348 if (S_ISDIR(sb.st_mode)) {
349 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
352 send_dir(fpath, fds, c);
356 if (cgi && (sb.st_mode & S_IXUSR)) {
357 start_cgi(fpath, query, fds, c);
361 if ((c->len = filesize(c->fd)) == -1) {
362 LOG(c, "failed to get file size for %s", fpath);
367 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
368 c->fd, 0)) == MAP_FAILED) {
369 warn("mmap: %s", fpath);
375 return start_reply(fds, c, SUCCESS, mime(fpath));
379 start_cgi(const char *path, const char *query,
380 struct pollfd *fds, struct client *c)
388 switch (pid = fork()) {
392 case 0: { /* child */
394 char addr[INET_ADDRSTRLEN];
395 char *argv[] = { NULL, NULL, NULL };
397 /* skip the initial ./ */
400 close(p[0]); /* close the read end */
401 if (dup2(p[1], 1) == -1)
404 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
407 /* skip the ./ at the start of path*/
408 if (asprintf(&expath, "%s%s", dir, path) == -1)
410 argv[0] = argv[1] = expath;
413 setenv("SERVER_SOFTWARE", "gmid", 1);
414 /* setenv("SERVER_NAME", "", 1); */
415 /* setenv("GATEWAY_INTERFACE", "CGI/version", 1); */
416 setenv("SERVER_PROTOCOL", "gemini", 1);
417 setenv("SERVER_PORT", "1965", 1);
418 setenv("PATH_INFO", path, 1);
419 setenv("PATH_TRANSLATED", expath, 1);
421 setenv("QUERY_STRING", query, 1);
422 setenv("REMOTE_ADDR", addr, 1);
424 execvp(expath, argv);
428 default: /* parent */
429 close(p[1]); /* close the write end */
433 mark_nonblock(c->fd);
434 c->state = S_SENDING;
440 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
446 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
449 /* don't call atexit stuff */
454 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
458 if (c->waiting_on_child)
460 c->waiting_on_child = 1;
462 fds->events = POLLIN;
470 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
474 if (!c->waiting_on_child)
476 c->waiting_on_child = 0;
484 handle_cgi(struct pollfd *fds, struct client *c)
488 /* ensure c->fd is the child and fds->fd the client */
489 cgi_setpoll_on_client(fds, c);
493 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
496 if (errno == EAGAIN || errno == EWOULDBLOCK) {
497 cgi_setpoll_on_child(fds, c);
507 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
511 case TLS_WANT_POLLOUT:
512 fds->events = POLLOUT;
515 case TLS_WANT_POLLIN:
516 fds->events = POLLIN;
532 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
537 if (!open_file(path, query, fds, c))
539 c->state = S_SENDING;
542 len = (c->buf + c->len) - c->i;
545 switch (ret = tls_write(c->ctx, c->i, len)) {
547 LOG(c, "tls_write: %s", tls_error(c->ctx));
551 case TLS_WANT_POLLIN:
552 fds->events = POLLIN;
555 case TLS_WANT_POLLOUT:
556 fds->events = POLLOUT;
570 send_dir(char *path, struct pollfd *fds, struct client *client)
575 bzero(fpath, PATHBUF);
580 /* this cannot fail since sizeof(fpath) > maxlen of path */
581 strlcat(fpath, path, PATHBUF);
584 /* add a trailing / in case. */
585 if (fpath[len-1] != '/') {
589 strlcat(fpath, "index.gmi", sizeof(fpath));
591 send_file(fpath, NULL, fds, client);
595 handle(struct pollfd *fds, struct client *client)
597 char buf[GEMINI_URL_LEN];
601 switch (client->state) {
603 bzero(buf, GEMINI_URL_LEN);
604 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
606 LOG(client, "tls_read: %s", tls_error(client->ctx));
607 goodbye(fds, client);
610 case TLS_WANT_POLLIN:
611 fds->events = POLLIN;
614 case TLS_WANT_POLLOUT:
615 fds->events = POLLOUT;
619 if (!url_trim(client, buf)) {
620 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
622 goodbye(fds, client);
626 if ((path = url_start_of_request(buf)) == NULL) {
627 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
629 goodbye(fds, client);
633 query = adjust_path(path);
634 LOG(client, "get %s%s%s", path,
638 if (path_isdir(path))
639 send_dir(path, fds, client);
641 send_file(path, query, fds, client);
645 if (!start_reply(fds, client, client->code, client->meta))
648 if (client->code != SUCCESS) {
649 /* we don't need a body */
650 goodbye(fds, client);
654 client->state = S_SENDING;
659 if (client->child != -1)
660 handle_cgi(fds, client);
662 send_file(NULL, NULL, fds, client);
666 goodbye(fds, client);
676 mark_nonblock(int fd)
680 if ((flags = fcntl(fd, F_GETFL)) == -1)
681 err(1, "fcntl(F_GETFL)");
682 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
683 err(1, "fcntl(F_SETFL)");
687 make_socket(int port, int family)
690 struct sockaddr_in addr4;
691 struct sockaddr_in6 addr6;
692 struct sockaddr *addr;
697 bzero(&addr4, sizeof(addr4));
698 addr4.sin_family = family;
699 addr4.sin_port = htons(port);
700 addr4.sin_addr.s_addr = INADDR_ANY;
701 addr = (struct sockaddr*)&addr4;
706 bzero(&addr6, sizeof(addr6));
707 addr6.sin6_family = AF_INET6;
708 addr6.sin6_port = htons(port);
709 addr6.sin6_addr = in6addr_any;
710 addr = (struct sockaddr*)&addr6;
719 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
723 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
724 err(1, "setsockopt(SO_REUSEADDR)");
727 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
728 err(1, "setsockopt(SO_REUSEPORT)");
732 if (bind(sock, addr, len) == -1)
735 if (listen(sock, 16) == -1)
742 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
745 struct sockaddr_in addr;
749 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
750 if (errno == EWOULDBLOCK)
757 for (i = 0; i < MAX_USERS; ++i) {
758 if (fds[i].fd == -1) {
759 bzero(&clients[i], sizeof(struct client));
760 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
761 break; /* goodbye fd! */
764 fds[i].events = POLLIN;
766 clients[i].state = S_OPEN;
768 clients[i].child = -1;
769 clients[i].buf = MAP_FAILED;
770 clients[i].af = AF_INET;
771 clients[i].addr = addr.sin_addr;
782 goodbye(struct pollfd *pfd, struct client *c)
786 c->state = S_CLOSING;
788 ret = tls_close(c->ctx);
789 if (ret == TLS_WANT_POLLIN) {
790 pfd->events = POLLIN;
793 if (ret == TLS_WANT_POLLOUT) {
794 pfd->events = POLLOUT;
803 if (c->buf != MAP_FAILED)
804 munmap(c->buf, c->len);
814 loop(struct tls *ctx, int sock)
817 struct client clients[MAX_USERS];
818 struct pollfd fds[MAX_USERS];
820 for (i = 0; i < MAX_USERS; ++i) {
822 fds[i].events = POLLIN;
823 bzero(&clients[i], sizeof(struct client));
829 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
830 if (errno == EINTR) {
831 warnx("connected clients: %d", connected_clients);
837 for (i = 0; i < MAX_USERS; i++) {
838 assert(i < MAX_USERS);
840 if (fds[i].revents == 0)
843 if (fds[i].revents & (POLLERR|POLLNVAL))
844 err(1, "bad fd %d", fds[i].fd);
846 if (fds[i].revents & POLLHUP) {
847 /* fds[i] may be the fd of the stdin
848 * of a cgi script that has exited. */
849 if (!clients[i].waiting_on_child) {
850 goodbye(&fds[i], &clients[i]);
857 if (i == 0) { /* new client */
858 do_accept(sock, ctx, fds, clients);
862 handle(&fds[i], &clients[i]);
868 usage(const char *me)
871 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
876 main(int argc, char **argv)
878 const char *cert = "cert.pem", *key = "key.pem";
879 struct tls *ctx = NULL;
880 struct tls_config *conf;
883 signal(SIGPIPE, SIG_IGN);
884 signal(SIGCHLD, SIG_IGN);
887 signal(SIGINFO, siginfo_handler);
889 signal(SIGUSR2, siginfo_handler);
891 connected_clients = 0;
894 logfd = 2; /* stderr */
897 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
916 /* open log file or create it with 644 */
917 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
918 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
919 err(1, "%s", optarg);
932 if ((conf = tls_config_new()) == NULL)
933 err(1, "tls_config_new");
935 if (tls_config_set_protocols(conf,
936 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
937 err(1, "tls_config_set_protocols");
939 if (tls_config_set_cert_file(conf, cert) == -1)
940 err(1, "tls_config_set_cert_file: %s", cert);
942 if (tls_config_set_key_file(conf, key) == -1)
943 err(1, "tls_config_set_key_file: %s", key);
945 if ((ctx = tls_server()) == NULL)
946 err(1, "tls_server");
948 if (tls_configure(ctx, conf) == -1)
949 errx(1, "tls_configure: %s", tls_error(ctx));
951 sock = make_socket(1965, AF_INET);
953 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
954 err(1, "open: %s", dir);
956 if (unveil(dir, cgi ? "rx" : "r") == -1)
959 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
966 tls_config_free(conf);