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*, char*, struct pollfd*, struct client*);
124 void start_cgi(const char*, const char*, struct pollfd*, struct client*);
125 void handle_cgi(struct pollfd*, struct client*);
126 void send_file(char*, 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, char *query, 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, query, 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, const char *query,
368 struct pollfd *fds, struct client *c)
376 switch (pid = fork()) {
380 case 0: { /* child */
382 char addr[INET_ADDRSTRLEN];
383 char *argv[] = { NULL, NULL, NULL };
389 "SERVER_SOFTWARE=gmid",
390 /* "SERVER_NAME=example.com", */
391 /* "GATEWAY_INTERFACE=CGI/version" */
392 "SERVER_PROTOCOL=gemini",
395 /* "PATH_TRANSLATED=" */
397 /* "QUERY_STRING=" */
403 close(p[0]); /* close the read end */
404 if (dup2(p[1], 1) == -1)
407 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
410 /* skip the ./ at the start of path*/
411 if (asprintf(&expath, "%s%s", dir, path+2) == -1)
413 argv[0] = argv[1] = expath;
416 for (i = 0; envp[i] != NULL; ++i) {
417 if (!strcmp(envp[i], "PATH="))
418 envp[i] = getenv("PATH");
419 else if (!strcmp(envp[i], "REMOTE_ADDR="))
421 /* else if (!strcmp(envp[i], "PATH_INFO")) */
425 execvpe(expath, argv, envp);
429 default: /* parent */
430 close(p[1]); /* close the write end */
439 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
445 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
451 handle_cgi(struct pollfd *fds, struct client *c)
457 r = read(c->fd, buf, sizeof(buf));
458 if (r == -1 || r == 0)
462 switch (r = tls_write(c->ctx, buf, todo)) {
466 case TLS_WANT_POLLOUT:
467 case TLS_WANT_POLLIN:
482 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
487 if (!open_file(path, query, fds, c))
489 c->state = S_SENDING;
492 len = (c->buf + c->len) - c->i;
495 switch (ret = tls_write(c->ctx, c->i, len)) {
497 LOG(c, "tls_write: %s", tls_error(c->ctx));
501 case TLS_WANT_POLLIN:
502 fds->events = POLLIN;
505 case TLS_WANT_POLLOUT:
506 fds->events = POLLOUT;
520 send_dir(char *path, struct pollfd *fds, struct client *client)
525 bzero(fpath, PATHBUF);
530 /* this cannot fail since sizeof(fpath) > maxlen of path */
531 strlcat(fpath, path, PATHBUF);
534 /* add a trailing / in case. */
535 if (fpath[len-1] != '/') {
539 strlcat(fpath, "index.gmi", sizeof(fpath));
541 send_file(fpath, NULL, fds, client);
545 handle(struct pollfd *fds, struct client *client)
547 char buf[GEMINI_URL_LEN];
551 switch (client->state) {
553 bzero(buf, GEMINI_URL_LEN);
554 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
556 LOG(client, "tls_read: %s", tls_error(client->ctx));
557 goodbye(fds, client);
560 case TLS_WANT_POLLIN:
561 fds->events = POLLIN;
564 case TLS_WANT_POLLOUT:
565 fds->events = POLLOUT;
569 if (!url_trim(client, buf)) {
570 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
572 goodbye(fds, client);
576 if ((path = url_start_of_request(buf)) == NULL) {
577 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
579 goodbye(fds, client);
583 query = adjust_path(path);
584 LOG(client, "get %s%s%s", path,
588 if (path_isdir(path))
589 send_dir(path, fds, client);
591 send_file(path, query, fds, client);
595 if (!start_reply(fds, client, client->code, client->meta))
598 if (client->code != SUCCESS) {
599 /* we don't need a body */
600 goodbye(fds, client);
604 client->state = S_SENDING;
609 send_file(NULL, NULL, fds, client);
613 goodbye(fds, client);
623 mark_nonblock(int fd)
627 if ((flags = fcntl(fd, F_GETFL)) == -1)
628 err(1, "fcntl(F_GETFL)");
629 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
630 err(1, "fcntl(F_SETFL)");
634 make_socket(int port, int family)
637 struct sockaddr_in addr4;
638 struct sockaddr_in6 addr6;
639 struct sockaddr *addr;
644 bzero(&addr4, sizeof(addr4));
645 addr4.sin_family = family;
646 addr4.sin_port = htons(port);
647 addr4.sin_addr.s_addr = INADDR_ANY;
648 addr = (struct sockaddr*)&addr4;
653 bzero(&addr6, sizeof(addr6));
654 addr6.sin6_family = AF_INET6;
655 addr6.sin6_port = htons(port);
656 addr6.sin6_addr = in6addr_any;
657 addr = (struct sockaddr*)&addr6;
666 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
670 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
671 err(1, "setsockopt(SO_REUSEADDR)");
674 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
675 err(1, "setsockopt(SO_REUSEPORT)");
679 if (bind(sock, addr, len) == -1)
682 if (listen(sock, 16) == -1)
689 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
692 struct sockaddr_in addr;
696 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
697 if (errno == EWOULDBLOCK)
704 for (i = 0; i < MAX_USERS; ++i) {
705 if (fds[i].fd == -1) {
706 bzero(&clients[i], sizeof(struct client));
707 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
708 break; /* goodbye fd! */
711 fds[i].events = POLLIN;
713 clients[i].state = S_OPEN;
715 clients[i].child = -1;
716 clients[i].buf = MAP_FAILED;
717 clients[i].af = AF_INET;
718 clients[i].addr = addr.sin_addr;
728 goodbye(struct pollfd *pfd, struct client *c)
732 c->state = S_CLOSING;
734 ret = tls_close(c->ctx);
735 if (ret == TLS_WANT_POLLIN) {
736 pfd->events = POLLIN;
739 if (ret == TLS_WANT_POLLOUT) {
740 pfd->events = POLLOUT;
747 if (c->buf != MAP_FAILED)
748 munmap(c->buf, c->len);
758 loop(struct tls *ctx, int sock)
761 struct client clients[MAX_USERS];
762 struct pollfd fds[MAX_USERS];
764 for (i = 0; i < MAX_USERS; ++i) {
766 fds[i].events = POLLIN;
767 bzero(&clients[i], sizeof(struct client));
773 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
776 for (i = 0; i < MAX_USERS; i++) {
777 assert(i < MAX_USERS);
779 if (fds[i].revents == 0)
782 if (fds[i].revents & (POLLERR|POLLNVAL))
783 err(1, "bad fd %d", fds[i].fd);
785 if (fds[i].revents & POLLHUP) {
786 goodbye(&fds[i], &clients[i]);
792 if (i == 0) { /* new client */
793 do_accept(sock, ctx, fds, clients);
797 handle(&fds[i], &clients[i]);
803 usage(const char *me)
806 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
811 main(int argc, char **argv)
813 const char *cert = "cert.pem", *key = "key.pem";
814 struct tls *ctx = NULL;
815 struct tls_config *conf;
818 signal(SIGPIPE, SIG_IGN);
819 signal(SIGCHLD, SIG_IGN);
822 logfd = 2; /* stderr */
825 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
844 /* open log file or create it with 644 */
845 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
846 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
847 err(1, "%s", optarg);
860 if ((conf = tls_config_new()) == NULL)
861 err(1, "tls_config_new");
863 if (tls_config_set_protocols(conf,
864 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
865 err(1, "tls_config_set_protocols");
867 if (tls_config_set_cert_file(conf, cert) == -1)
868 err(1, "tls_config_set_cert_file: %s", cert);
870 if (tls_config_set_key_file(conf, key) == -1)
871 err(1, "tls_config_set_key_file: %s", key);
873 if ((ctx = tls_server()) == NULL)
874 err(1, "tls_server");
876 if (tls_configure(ctx, conf) == -1)
877 errx(1, "tls_configure: %s", tls_error(ctx));
879 sock = make_socket(1965, AF_INET);
881 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
882 err(1, "open: %s", dir);
884 if (unveil(dir, cgi ? "rx" : "r") == -1)
887 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
894 tls_config_free(conf);