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>
31 const char *dir, *cgi;
35 int connected_clients;
38 siginfo_handler(int sig)
44 starts_with(const char *str, const char *prefix)
48 for (i = 0; prefix[i] != '\0'; ++i)
49 if (str[i] != prefix[i])
55 url_after_proto(char *url)
58 const char *proto = "gemini:";
59 const char *marker = "//";
62 if ((s = strstr(url, marker)) == NULL)
66 * if a protocol is not specified, gemini should be implied:
67 * this handles the case of //example.com
70 return s + strlen(marker);
72 if (s - strlen(proto) != url)
75 if (!starts_with(url, proto))
78 return s + strlen(marker);
82 url_start_of_request(char *url)
86 if ((s = url_after_proto(url)) == NULL)
89 /* non-absolute URL */
93 if ((t = strstr(s, "/")) == NULL)
99 url_trim(struct client *c, char *url)
101 const char *e = "\r\n";
104 if ((s = strstr(url, e)) == NULL)
110 LOGE(c, "%s", "request longer than 1024 bytes");
118 adjust_path(char *path)
123 if ((query = strchr(path, '?')) != NULL) {
131 if (!strcmp(&path[len-3], "/..")) {
136 /* if the path is only `..` trim out and exit */
137 if (!strcmp(path, "..")) {
142 /* remove every ../ in the path */
144 if ((s = strstr(path, "../")) == NULL)
146 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
151 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
153 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
158 client->meta = reason;
159 client->state = S_INITIALIZING;
161 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
162 assert(len < (int)sizeof(buf));
163 ret = tls_write(client->ctx, buf, len);
164 if (ret == TLS_WANT_POLLIN) {
165 pfd->events = POLLIN;
169 if (ret == TLS_WANT_POLLOUT) {
170 pfd->events = POLLOUT;
182 if ((len = lseek(fd, 0, SEEK_END)) == -1)
184 if (lseek(fd, 0, SEEK_SET) == -1)
190 path_ext(const char *path)
194 end = path + strlen(path)-1; /* the last byte before the NUL */
195 for (; end != path; --end) {
206 mime(const char *path)
208 const char *ext, *def = "application/octet-stream";
211 if ((ext = path_ext(path)) == NULL)
214 for (t = filetypes; t->mime != NULL; ++t)
215 if (!strcmp(ext, t->ext))
222 check_path(struct client *c, const char *path, int *fd)
226 assert(path != NULL);
227 if ((*fd = openat(dirfd, path,
228 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
232 if (fstat(*fd, &sb) == -1) {
233 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
237 if (S_ISDIR(sb.st_mode))
238 return FILE_DIRECTORY;
240 if (sb.st_mode & S_IXUSR)
241 return FILE_EXECUTABLE;
247 * the inverse of this algorithm, i.e. starting from the start of the
248 * path + strlen(cgi), and checking if each component, should be
249 * faster. But it's tedious to write. This does the opposite: starts
250 * from the end and strip one component at a time, until either an
251 * executable is found or we emptied the path.
254 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
257 end = strchr(path, '\0');
259 /* NB: assume CGI is enabled and path matches cgi */
262 /* go up one level. UNIX paths are simple and POSIX
263 * dirname, with its ambiguities on if the given path
264 * is changed or not, gives me headaches. */
269 switch (check_path(c, path, &c->fd)) {
270 case FILE_EXECUTABLE:
271 return start_cgi(path, end+1, query, fds,c);
283 if (!start_reply(fds, c, NOT_FOUND, "not found"))
291 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
295 bzero(fpath, sizeof(fpath));
299 strlcat(fpath, path, PATHBUF);
301 switch (check_path(c, fpath, &c->fd)) {
302 case FILE_EXECUTABLE:
303 /* +2 to skip the ./ */
304 if (cgi != NULL && starts_with(fpath+2, cgi))
305 return start_cgi(fpath, "", query, fds, c);
310 if ((c->len = filesize(c->fd)) == -1) {
311 LOGE(c, "failed to get file size for %s", fpath);
316 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
317 c->fd, 0)) == MAP_FAILED) {
318 warn("mmap: %s", fpath);
323 return start_reply(fds, c, SUCCESS, mime(fpath));
326 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
329 send_dir(fpath, fds, c);
333 if (cgi != NULL && starts_with(fpath+2, cgi))
334 return check_for_cgi(fpath, query, fds, c);
336 if (!start_reply(fds, c, NOT_FOUND, "not found"))
348 start_cgi(const char *spath, const char *relpath, const char *query,
349 struct pollfd *fds, struct client *c)
352 int p[2]; /* read end, write end */
357 switch (pid = fork()) {
361 case 0: { /* child */
362 char *ex, *requri, *portno;
363 char addr[INET_ADDRSTRLEN];
364 char *argv[] = { NULL, NULL, NULL };
369 if (dup2(p[1], 1) == -1)
372 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
375 if (asprintf(&portno, "%d", port) == -1)
378 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
381 if (asprintf(&requri, "%s%s%s", spath,
382 *relpath == '\0' ? "" : "/",
386 argv[0] = argv[1] = ex;
389 SAFE_SETENV("GATEWAY_INTERFACE", "CGI/1.1");
390 SAFE_SETENV("SERVER_SOFTWARE", "gmid");
391 SAFE_SETENV("SERVER_PORT", portno);
392 /* setenv("SERVER_NAME", "", 1); */
393 SAFE_SETENV("SCRIPT_NAME", spath);
394 SAFE_SETENV("SCRIPT_EXECUTABLE", ex);
395 SAFE_SETENV("REQUEST_URI", requri);
396 SAFE_SETENV("REQUEST_RELATIVE", relpath);
397 SAFE_SETENV("QUERY_STRING", query);
398 SAFE_SETENV("REMOTE_HOST", addr);
399 SAFE_SETENV("REMOTE_ADDR", addr);
400 SAFE_SETENV("DOCUMENT_ROOT", dir);
402 if (tls_peer_cert_provided(c->ctx)) {
403 SAFE_SETENV("AUTH_TYPE", "Certificate");
404 SAFE_SETENV("REMOTE_USER", tls_peer_cert_subject(c->ctx));
405 SAFE_SETENV("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
406 SAFE_SETENV("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
413 default: /* parent */
418 mark_nonblock(c->fd);
419 c->state = S_SENDING;
425 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
431 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
437 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
441 if (c->waiting_on_child)
443 c->waiting_on_child = 1;
445 fds->events = POLLIN;
453 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
457 if (!c->waiting_on_child)
459 c->waiting_on_child = 0;
467 handle_cgi(struct pollfd *fds, struct client *c)
471 /* ensure c->fd is the child and fds->fd the client */
472 cgi_setpoll_on_client(fds, c);
476 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
479 if (errno == EAGAIN || errno == EWOULDBLOCK) {
480 cgi_setpoll_on_child(fds, c);
490 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
494 case TLS_WANT_POLLOUT:
495 fds->events = POLLOUT;
498 case TLS_WANT_POLLIN:
499 fds->events = POLLIN;
515 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
520 if (!open_file(path, query, fds, c))
522 c->state = S_SENDING;
525 len = (c->buf + c->len) - c->i;
528 switch (ret = tls_write(c->ctx, c->i, len)) {
530 LOGE(c, "tls_write: %s", tls_error(c->ctx));
534 case TLS_WANT_POLLIN:
535 fds->events = POLLIN;
538 case TLS_WANT_POLLOUT:
539 fds->events = POLLOUT;
553 send_dir(char *path, struct pollfd *fds, struct client *client)
558 bzero(fpath, PATHBUF);
563 /* this cannot fail since sizeof(fpath) > maxlen of path */
564 strlcat(fpath, path, PATHBUF);
567 /* add a trailing / in case. */
568 if (fpath[len-1] != '/') {
572 strlcat(fpath, "index.gmi", sizeof(fpath));
574 send_file(fpath, NULL, fds, client);
578 handle(struct pollfd *fds, struct client *client)
580 char buf[GEMINI_URL_LEN];
584 switch (client->state) {
586 bzero(buf, GEMINI_URL_LEN);
587 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
589 LOGE(client, "tls_read: %s", tls_error(client->ctx));
590 goodbye(fds, client);
593 case TLS_WANT_POLLIN:
594 fds->events = POLLIN;
597 case TLS_WANT_POLLOUT:
598 fds->events = POLLOUT;
602 if (!url_trim(client, buf)) {
603 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
605 goodbye(fds, client);
609 if ((path = url_start_of_request(buf)) == NULL) {
610 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
612 goodbye(fds, client);
616 query = adjust_path(path);
617 LOGI(client, "GET %s%s%s", path,
621 send_file(path, query, fds, client);
625 if (!start_reply(fds, client, client->code, client->meta))
628 if (client->code != SUCCESS) {
629 /* we don't need a body */
630 goodbye(fds, client);
634 client->state = S_SENDING;
639 if (client->child != -1)
640 handle_cgi(fds, client);
642 send_file(NULL, NULL, fds, client);
646 goodbye(fds, client);
656 mark_nonblock(int fd)
660 if ((flags = fcntl(fd, F_GETFL)) == -1)
661 FATAL("fcntl(F_GETFL): %s", strerror(errno));
662 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
663 FATAL("fcntl(F_SETFL): %s", strerror(errno));
667 make_socket(int port, int family)
670 struct sockaddr_in addr4;
671 struct sockaddr_in6 addr6;
672 struct sockaddr *addr;
677 bzero(&addr4, sizeof(addr4));
678 addr4.sin_family = family;
679 addr4.sin_port = htons(port);
680 addr4.sin_addr.s_addr = INADDR_ANY;
681 addr = (struct sockaddr*)&addr4;
686 bzero(&addr6, sizeof(addr6));
687 addr6.sin6_family = AF_INET6;
688 addr6.sin6_port = htons(port);
689 addr6.sin6_addr = in6addr_any;
690 addr = (struct sockaddr*)&addr6;
699 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
700 FATAL("socket: %s", strerror(errno));
703 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
704 FATAL("setsockopt(SO_REUSEADDR): %s", strerror(errno));
707 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
708 FATAL("setsockopt(SO_REUSEPORT): %s", strerror(errno));
712 if (bind(sock, addr, len) == -1)
713 FATAL("bind: %s", strerror(errno));
715 if (listen(sock, 16) == -1)
716 FATAL("listen: %s", strerror(errno));
722 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
725 struct sockaddr_in addr;
729 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
730 if (errno == EWOULDBLOCK)
732 FATAL("accept: %s", strerror(errno));
737 for (i = 0; i < MAX_USERS; ++i) {
738 if (fds[i].fd == -1) {
739 bzero(&clients[i], sizeof(struct client));
740 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
741 break; /* goodbye fd! */
744 fds[i].events = POLLIN;
746 clients[i].state = S_OPEN;
748 clients[i].child = -1;
749 clients[i].buf = MAP_FAILED;
750 clients[i].af = AF_INET;
751 clients[i].addr = addr.sin_addr;
762 goodbye(struct pollfd *pfd, struct client *c)
766 c->state = S_CLOSING;
768 ret = tls_close(c->ctx);
769 if (ret == TLS_WANT_POLLIN) {
770 pfd->events = POLLIN;
773 if (ret == TLS_WANT_POLLOUT) {
774 pfd->events = POLLOUT;
783 if (c->buf != MAP_FAILED)
784 munmap(c->buf, c->len);
794 loop(struct tls *ctx, int sock)
797 struct client clients[MAX_USERS];
798 struct pollfd fds[MAX_USERS];
800 for (i = 0; i < MAX_USERS; ++i) {
802 fds[i].events = POLLIN;
803 bzero(&clients[i], sizeof(struct client));
809 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
810 if (errno == EINTR) {
811 warnx("connected clients: %d",
815 FATAL("poll: %s", strerror(errno));
818 for (i = 0; i < MAX_USERS; i++) {
819 assert(i < MAX_USERS);
821 if (fds[i].revents == 0)
824 if (fds[i].revents & (POLLERR|POLLNVAL))
825 FATAL("bad fd %d: %s", 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 absolutify_path(const char *path)
858 if (asprintf(&r, "%s/%s", wd, path) == -1)
865 usage(const char *me)
868 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
869 "[-l logfile] [-p port] [-x cgi-bin]\n",
874 main(int argc, char **argv)
876 const char *cert = "cert.pem", *key = "key.pem";
877 struct tls *ctx = NULL;
878 struct tls_config *conf;
881 signal(SIGPIPE, SIG_IGN);
882 signal(SIGCHLD, SIG_IGN);
885 signal(SIGINFO, siginfo_handler);
887 signal(SIGUSR2, siginfo_handler);
889 connected_clients = 0;
891 if ((dir = absolutify_path("docs")) == NULL)
892 err(1, "absolutify_path");
898 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
906 if ((dir = absolutify_path(optarg)) == NULL)
907 err(1, "absolutify_path");
927 lval = strtol(optarg, &ep, 10);
928 if (optarg[0] == '\0' || *ep != '\0')
929 err(1, "not a number: %s", optarg);
930 if (lval < 0 || lval > UINT16_MAX)
931 err(1, "port number out of range: %s", optarg);
946 if ((conf = tls_config_new()) == NULL)
947 err(1, "tls_config_new");
949 /* optionally accept client certs, but don't try to verify them */
950 tls_config_verify_client_optional(conf);
951 tls_config_insecure_noverifycert(conf);
953 if (tls_config_set_protocols(conf,
954 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
955 err(1, "tls_config_set_protocols");
957 if (tls_config_set_cert_file(conf, cert) == -1)
958 err(1, "tls_config_set_cert_file: %s", cert);
960 if (tls_config_set_key_file(conf, key) == -1)
961 err(1, "tls_config_set_key_file: %s", key);
963 if ((ctx = tls_server()) == NULL)
964 err(1, "tls_server");
966 if (tls_configure(ctx, conf) == -1)
967 errx(1, "tls_configure: %s", tls_error(ctx));
969 sock = make_socket(port, AF_INET);
971 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
972 err(1, "open: %s", dir);
974 if (!foreground && daemon(0, 1) == -1)
978 if (unveil(dir, "rx") == -1)
980 if (pledge("stdio rpath inet proc exec", NULL) == -1)
983 if (unveil(dir, "r") == -1)
985 if (pledge("stdio rpath inet", NULL) == -1)
993 tls_config_free(conf);