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;
37 struct etm { /* file extension to mime */
41 {"application/pdf", "pdf"},
44 {"image/jpeg", "jpg"},
45 {"image/jpeg", "jpeg"},
47 {"image/svg+xml", "svg"},
49 {"text/gemini", "gemini"},
50 {"text/gemini", "gmi"},
51 {"text/markdown", "markdown"},
52 {"text/markdown", "md"},
53 {"text/plain", "txt"},
60 siginfo_handler(int sig)
66 starts_with(const char *str, const char *prefix)
70 for (i = 0; prefix[i] != '\0'; ++i)
71 if (str[i] != prefix[i])
77 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
79 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
84 client->meta = reason;
85 client->state = S_INITIALIZING;
87 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
88 assert(len < (int)sizeof(buf));
89 ret = tls_write(client->ctx, buf, len);
90 if (ret == TLS_WANT_POLLIN) {
95 if (ret == TLS_WANT_POLLOUT) {
96 pfd->events = POLLOUT;
108 if ((len = lseek(fd, 0, SEEK_END)) == -1)
110 if (lseek(fd, 0, SEEK_SET) == -1)
116 path_ext(const char *path)
120 end = path + strlen(path)-1; /* the last byte before the NUL */
121 for (; end != path; --end) {
132 mime(const char *path)
134 const char *ext, *def = "application/octet-stream";
137 if ((ext = path_ext(path)) == NULL)
140 for (t = filetypes; t->mime != NULL; ++t)
141 if (!strcmp(ext, t->ext))
148 check_path(struct client *c, const char *path, int *fd)
152 assert(path != NULL);
153 if ((*fd = openat(dirfd, *path ? path : ".",
154 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
158 if (fstat(*fd, &sb) == -1) {
159 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
163 if (S_ISDIR(sb.st_mode))
164 return FILE_DIRECTORY;
166 if (sb.st_mode & S_IXUSR)
167 return FILE_EXECUTABLE;
173 * the inverse of this algorithm, i.e. starting from the start of the
174 * path + strlen(cgi), and checking if each component, should be
175 * faster. But it's tedious to write. This does the opposite: starts
176 * from the end and strip one component at a time, until either an
177 * executable is found or we emptied the path.
180 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
183 end = strchr(path, '\0');
185 /* NB: assume CGI is enabled and path matches cgi */
188 /* go up one level. UNIX paths are simple and POSIX
189 * dirname, with its ambiguities on if the given path
190 * is changed or not, gives me headaches. */
195 switch (check_path(c, path, &c->fd)) {
196 case FILE_EXECUTABLE:
197 return start_cgi(path, end+1, query, fds,c);
209 if (!start_reply(fds, c, NOT_FOUND, "not found"))
217 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
219 switch (check_path(c, fpath, &c->fd)) {
220 case FILE_EXECUTABLE:
221 /* +2 to skip the ./ */
222 if (cgi != NULL && starts_with(fpath+2, cgi))
223 return start_cgi(fpath, "", query, fds, c);
228 if ((c->len = filesize(c->fd)) == -1) {
229 LOGE(c, "failed to get file size for %s", fpath);
234 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
235 c->fd, 0)) == MAP_FAILED) {
236 warn("mmap: %s", fpath);
241 return start_reply(fds, c, SUCCESS, mime(fpath));
244 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
247 send_dir(fpath, fds, c);
251 if (cgi != NULL && starts_with(fpath+2, cgi))
252 return check_for_cgi(fpath, query, fds, c);
254 if (!start_reply(fds, c, NOT_FOUND, "not found"))
266 start_cgi(const char *spath, const char *relpath, const char *query,
267 struct pollfd *fds, struct client *c)
270 int p[2]; /* read end, write end */
275 switch (pid = fork()) {
279 case 0: { /* child */
280 char *ex, *requri, *portno;
281 char addr[INET_ADDRSTRLEN];
282 char *argv[] = { NULL, NULL, NULL };
287 if (dup2(p[1], 1) == -1)
290 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
293 if (asprintf(&portno, "%d", port) == -1)
296 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
299 if (asprintf(&requri, "%s%s%s", spath,
300 *relpath == '\0' ? "" : "/",
304 argv[0] = argv[1] = ex;
307 SAFE_SETENV("GATEWAY_INTERFACE", "CGI/1.1");
308 SAFE_SETENV("SERVER_SOFTWARE", "gmid");
309 SAFE_SETENV("SERVER_PORT", portno);
310 /* setenv("SERVER_NAME", "", 1); */
311 SAFE_SETENV("SCRIPT_NAME", spath);
312 SAFE_SETENV("SCRIPT_EXECUTABLE", ex);
313 SAFE_SETENV("REQUEST_URI", requri);
314 SAFE_SETENV("REQUEST_RELATIVE", relpath);
315 SAFE_SETENV("QUERY_STRING", query);
316 SAFE_SETENV("REMOTE_HOST", addr);
317 SAFE_SETENV("REMOTE_ADDR", addr);
318 SAFE_SETENV("DOCUMENT_ROOT", dir);
320 if (tls_peer_cert_provided(c->ctx)) {
321 SAFE_SETENV("AUTH_TYPE", "Certificate");
322 SAFE_SETENV("REMOTE_USER", tls_peer_cert_subject(c->ctx));
323 SAFE_SETENV("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
324 SAFE_SETENV("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
331 default: /* parent */
336 mark_nonblock(c->fd);
337 c->state = S_SENDING;
343 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
349 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
355 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
359 if (c->waiting_on_child)
361 c->waiting_on_child = 1;
363 fds->events = POLLIN;
371 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
375 if (!c->waiting_on_child)
377 c->waiting_on_child = 0;
385 handle_cgi(struct pollfd *fds, struct client *c)
389 /* ensure c->fd is the child and fds->fd the client */
390 cgi_setpoll_on_client(fds, c);
394 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
397 if (errno == EAGAIN || errno == EWOULDBLOCK) {
398 cgi_setpoll_on_child(fds, c);
408 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
412 case TLS_WANT_POLLOUT:
413 fds->events = POLLOUT;
416 case TLS_WANT_POLLIN:
417 fds->events = POLLIN;
433 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
438 if (!open_file(path, query, fds, c))
440 c->state = S_SENDING;
443 len = (c->buf + c->len) - c->i;
446 switch (ret = tls_write(c->ctx, c->i, len)) {
448 LOGE(c, "tls_write: %s", tls_error(c->ctx));
452 case TLS_WANT_POLLIN:
453 fds->events = POLLIN;
456 case TLS_WANT_POLLOUT:
457 fds->events = POLLOUT;
471 send_dir(char *path, struct pollfd *fds, struct client *client)
476 bzero(fpath, PATHBUF);
481 /* this cannot fail since sizeof(fpath) > maxlen of path */
482 strlcat(fpath, path, PATHBUF);
485 /* add a trailing / in case. */
486 if (fpath[len-1] != '/') {
490 strlcat(fpath, "index.gmi", sizeof(fpath));
492 send_file(fpath, NULL, fds, client);
496 handle(struct pollfd *fds, struct client *client)
498 char buf[GEMINI_URL_LEN];
499 const char *parse_err;
502 switch (client->state) {
504 bzero(buf, GEMINI_URL_LEN);
505 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
507 LOGE(client, "tls_read: %s", tls_error(client->ctx));
508 goodbye(fds, client);
511 case TLS_WANT_POLLIN:
512 fds->events = POLLIN;
515 case TLS_WANT_POLLOUT:
516 fds->events = POLLOUT;
520 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
521 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
523 goodbye(fds, client);
527 LOGI(client, "GET %s%s%s",
528 *uri.path ? uri.path : "/",
529 *uri.query ? "?" : "",
530 *uri.query ? uri.query : "");
532 send_file(uri.path, uri.query, fds, client);
536 if (!start_reply(fds, client, client->code, client->meta))
539 if (client->code != SUCCESS) {
540 /* we don't need a body */
541 goodbye(fds, client);
545 client->state = S_SENDING;
550 if (client->child != -1)
551 handle_cgi(fds, client);
553 send_file(NULL, NULL, fds, client);
557 goodbye(fds, client);
567 mark_nonblock(int fd)
571 if ((flags = fcntl(fd, F_GETFL)) == -1)
572 FATAL("fcntl(F_GETFL): %s", strerror(errno));
573 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
574 FATAL("fcntl(F_SETFL): %s", strerror(errno));
578 make_socket(int port, int family)
581 struct sockaddr_in addr4;
582 struct sockaddr_in6 addr6;
583 struct sockaddr *addr;
588 bzero(&addr4, sizeof(addr4));
589 addr4.sin_family = family;
590 addr4.sin_port = htons(port);
591 addr4.sin_addr.s_addr = INADDR_ANY;
592 addr = (struct sockaddr*)&addr4;
597 bzero(&addr6, sizeof(addr6));
598 addr6.sin6_family = AF_INET6;
599 addr6.sin6_port = htons(port);
600 addr6.sin6_addr = in6addr_any;
601 addr = (struct sockaddr*)&addr6;
610 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
611 FATAL("socket: %s", strerror(errno));
614 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
615 FATAL("setsockopt(SO_REUSEADDR): %s", strerror(errno));
618 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
619 FATAL("setsockopt(SO_REUSEPORT): %s", strerror(errno));
623 if (bind(sock, addr, len) == -1)
624 FATAL("bind: %s", strerror(errno));
626 if (listen(sock, 16) == -1)
627 FATAL("listen: %s", strerror(errno));
633 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
636 struct sockaddr_in addr;
640 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
641 if (errno == EWOULDBLOCK)
643 FATAL("accept: %s", strerror(errno));
648 for (i = 0; i < MAX_USERS; ++i) {
649 if (fds[i].fd == -1) {
650 bzero(&clients[i], sizeof(struct client));
651 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
652 break; /* goodbye fd! */
655 fds[i].events = POLLIN;
657 clients[i].state = S_OPEN;
659 clients[i].child = -1;
660 clients[i].buf = MAP_FAILED;
661 clients[i].af = AF_INET;
662 clients[i].addr = addr.sin_addr;
673 goodbye(struct pollfd *pfd, struct client *c)
677 c->state = S_CLOSING;
679 ret = tls_close(c->ctx);
680 if (ret == TLS_WANT_POLLIN) {
681 pfd->events = POLLIN;
684 if (ret == TLS_WANT_POLLOUT) {
685 pfd->events = POLLOUT;
694 if (c->buf != MAP_FAILED)
695 munmap(c->buf, c->len);
705 loop(struct tls *ctx, int sock)
708 struct client clients[MAX_USERS];
709 struct pollfd fds[MAX_USERS];
711 for (i = 0; i < MAX_USERS; ++i) {
713 fds[i].events = POLLIN;
714 bzero(&clients[i], sizeof(struct client));
720 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
721 if (errno == EINTR) {
722 warnx("connected clients: %d",
726 FATAL("poll: %s", strerror(errno));
729 for (i = 0; i < MAX_USERS; i++) {
730 assert(i < MAX_USERS);
732 if (fds[i].revents == 0)
735 if (fds[i].revents & (POLLERR|POLLNVAL))
736 FATAL("bad fd %d: %s", fds[i].fd,
739 if (fds[i].revents & POLLHUP) {
740 /* fds[i] may be the fd of the stdin
741 * of a cgi script that has exited. */
742 if (!clients[i].waiting_on_child) {
743 goodbye(&fds[i], &clients[i]);
750 if (i == 0) { /* new client */
751 do_accept(sock, ctx, fds, clients);
755 handle(&fds[i], &clients[i]);
761 absolutify_path(const char *path)
769 if (asprintf(&r, "%s/%s", wd, path) == -1)
776 usage(const char *me)
779 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
780 "[-l logfile] [-p port] [-x cgi-bin]\n",
785 main(int argc, char **argv)
787 const char *cert = "cert.pem", *key = "key.pem";
788 struct tls *ctx = NULL;
789 struct tls_config *conf;
792 signal(SIGPIPE, SIG_IGN);
793 signal(SIGCHLD, SIG_IGN);
796 signal(SIGINFO, siginfo_handler);
798 signal(SIGUSR2, siginfo_handler);
800 connected_clients = 0;
802 if ((dir = absolutify_path("docs")) == NULL)
803 err(1, "absolutify_path");
809 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
817 if ((dir = absolutify_path(optarg)) == NULL)
818 err(1, "absolutify_path");
838 lval = strtol(optarg, &ep, 10);
839 if (optarg[0] == '\0' || *ep != '\0')
840 err(1, "not a number: %s", optarg);
841 if (lval < 0 || lval > UINT16_MAX)
842 err(1, "port number out of range: %s", optarg);
857 if ((conf = tls_config_new()) == NULL)
858 err(1, "tls_config_new");
860 /* optionally accept client certs, but don't try to verify them */
861 tls_config_verify_client_optional(conf);
862 tls_config_insecure_noverifycert(conf);
864 if (tls_config_set_protocols(conf,
865 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
866 err(1, "tls_config_set_protocols");
868 if (tls_config_set_cert_file(conf, cert) == -1)
869 err(1, "tls_config_set_cert_file: %s", cert);
871 if (tls_config_set_key_file(conf, key) == -1)
872 err(1, "tls_config_set_key_file: %s", key);
874 if ((ctx = tls_server()) == NULL)
875 err(1, "tls_server");
877 if (tls_configure(ctx, conf) == -1)
878 errx(1, "tls_configure: %s", tls_error(ctx));
880 sock = make_socket(port, AF_INET);
882 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
883 err(1, "open: %s", dir);
885 if (!foreground && daemon(0, 1) == -1)
889 if (unveil(dir, "rx") == -1)
891 if (pledge("stdio rpath inet proc exec", NULL) == -1)
894 if (unveil(dir, "r") == -1)
896 if (pledge("stdio rpath inet", NULL) == -1)
904 tls_config_free(conf);