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.
32 #define LOGE(c, fmt, ...) logs(LOG_ERR, c, fmt, __VA_ARGS__)
33 #define LOGN(c, fmt, ...) logs(LOG_NOTICE, c, fmt, __VA_ARGS__)
34 #define LOGI(c, fmt, ...) logs(LOG_INFO, c, fmt, __VA_ARGS__)
35 #define LOGD(c, fmt, ...) logs(LOG_DEBUG, c, fmt, __VA_ARGS__)
37 const char *dir, *cgi;
41 int connected_clients;
43 struct etm { /* file extension to mime */
47 {"application/pdf", "pdf"},
50 {"image/jpeg", "jpg"},
51 {"image/jpeg", "jpeg"},
53 {"image/svg+xml", "svg"},
55 {"text/gemini", "gemini"},
56 {"text/gemini", "gmi"},
57 {"text/markdown", "markdown"},
58 {"text/markdown", "md"},
59 {"text/plain", "txt"},
66 safe_setenv(const char *name, const char *val)
73 __attribute__ ((format (printf, 1, 2)))
74 __attribute__ ((__noreturn__))
76 fatal(const char *fmt, ...)
83 vfprintf(stderr, fmt, ap);
84 fprintf(stderr, "\n");
86 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
92 __attribute__ ((format (printf, 3, 4)))
94 logs(int priority, struct client *c,
97 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
105 len = sizeof(c->addr);
106 ec = getnameinfo((struct sockaddr*)&c->addr, len,
109 NI_NUMERICHOST | NI_NUMERICSERV);
111 fatal("getnameinfo: %s", gai_strerror(ec));
113 if (vasprintf(&fmted, fmt, ap) == -1)
114 fatal("vasprintf: %s", strerror(errno));
117 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
119 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
120 fatal("asprintf: %s", strerror(errno));
121 syslog(priority | LOG_DAEMON, "%s", s);
137 starts_with(const char *str, const char *prefix)
141 for (i = 0; prefix[i] != '\0'; ++i)
142 if (str[i] != prefix[i])
148 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
150 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
155 client->meta = reason;
156 client->state = S_INITIALIZING;
158 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
159 assert(len < (int)sizeof(buf));
160 ret = tls_write(client->ctx, buf, len);
161 if (ret == TLS_WANT_POLLIN) {
162 pfd->events = POLLIN;
166 if (ret == TLS_WANT_POLLOUT) {
167 pfd->events = POLLOUT;
179 if ((len = lseek(fd, 0, SEEK_END)) == -1)
181 if (lseek(fd, 0, SEEK_SET) == -1)
187 path_ext(const char *path)
191 end = path + strlen(path)-1; /* the last byte before the NUL */
192 for (; end != path; --end) {
203 mime(const char *path)
205 const char *ext, *def = "application/octet-stream";
208 if ((ext = path_ext(path)) == NULL)
211 for (t = filetypes; t->mime != NULL; ++t)
212 if (!strcmp(ext, t->ext))
219 check_path(struct client *c, const char *path, int *fd)
223 assert(path != NULL);
224 if ((*fd = openat(dirfd, *path ? path : ".",
225 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
229 if (fstat(*fd, &sb) == -1) {
230 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
234 if (S_ISDIR(sb.st_mode))
235 return FILE_DIRECTORY;
237 if (sb.st_mode & S_IXUSR)
238 return FILE_EXECUTABLE;
244 * the inverse of this algorithm, i.e. starting from the start of the
245 * path + strlen(cgi), and checking if each component, should be
246 * faster. But it's tedious to write. This does the opposite: starts
247 * from the end and strip one component at a time, until either an
248 * executable is found or we emptied the path.
251 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
254 end = strchr(path, '\0');
256 /* NB: assume CGI is enabled and path matches cgi */
259 /* go up one level. UNIX paths are simple and POSIX
260 * dirname, with its ambiguities on if the given path
261 * is changed or not, gives me headaches. */
266 switch (check_path(c, path, &c->fd)) {
267 case FILE_EXECUTABLE:
268 return start_cgi(path, end+1, query, fds,c);
280 if (!start_reply(fds, c, NOT_FOUND, "not found"))
288 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
290 switch (check_path(c, fpath, &c->fd)) {
291 case FILE_EXECUTABLE:
292 if (cgi != NULL && starts_with(fpath, cgi))
293 return start_cgi(fpath, "", query, fds, c);
298 if ((c->len = filesize(c->fd)) == -1) {
299 LOGE(c, "failed to get file size for %s", fpath);
304 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
305 c->fd, 0)) == MAP_FAILED) {
306 warn("mmap: %s", fpath);
311 return start_reply(fds, c, SUCCESS, mime(fpath));
314 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
317 send_dir(fpath, fds, c);
321 if (cgi != NULL && starts_with(fpath, cgi))
322 return check_for_cgi(fpath, query, fds, c);
324 if (!start_reply(fds, c, NOT_FOUND, "not found"))
336 start_cgi(const char *spath, const char *relpath, const char *query,
337 struct pollfd *fds, struct client *c)
340 int p[2]; /* read end, write end */
345 switch (pid = fork()) {
349 case 0: { /* child */
350 char *ex, *requri, *portno;
351 char addr[NI_MAXHOST];
352 char *argv[] = { NULL, NULL, NULL };
356 if (dup2(p[1], 1) == -1)
359 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
362 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
365 NI_NUMERICHOST | NI_NUMERICSERV);
369 if (asprintf(&portno, "%d", port) == -1)
372 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
375 if (asprintf(&requri, "%s%s%s", spath,
376 *relpath == '\0' ? "" : "/",
380 argv[0] = argv[1] = ex;
383 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
384 safe_setenv("SERVER_SOFTWARE", "gmid");
385 safe_setenv("SERVER_PORT", portno);
386 /* setenv("SERVER_NAME", "", 1); */
387 safe_setenv("SCRIPT_NAME", spath);
388 safe_setenv("SCRIPT_EXECUTABLE", ex);
389 safe_setenv("REQUEST_URI", requri);
390 safe_setenv("REQUEST_RELATIVE", relpath);
391 safe_setenv("QUERY_STRING", query);
392 safe_setenv("REMOTE_HOST", addr);
393 safe_setenv("REMOTE_ADDR", addr);
394 safe_setenv("DOCUMENT_ROOT", dir);
396 if (tls_peer_cert_provided(c->ctx)) {
397 safe_setenv("AUTH_TYPE", "Certificate");
398 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
399 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
400 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
407 default: /* parent */
412 mark_nonblock(c->fd);
413 c->state = S_SENDING;
419 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
425 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
431 cgi_poll_on_child(struct pollfd *fds, struct client *c)
435 if (c->waiting_on_child)
437 c->waiting_on_child = 1;
439 fds->events = POLLIN;
447 cgi_poll_on_client(struct pollfd *fds, struct client *c)
451 if (!c->waiting_on_child)
453 c->waiting_on_child = 0;
461 handle_cgi(struct pollfd *fds, struct client *c)
465 /* ensure c->fd is the child and fds->fd the client */
466 cgi_poll_on_client(fds, c);
470 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
473 if (errno == EAGAIN || errno == EWOULDBLOCK) {
474 cgi_poll_on_child(fds, c);
484 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
488 case TLS_WANT_POLLOUT:
489 fds->events = POLLOUT;
492 case TLS_WANT_POLLIN:
493 fds->events = POLLIN;
509 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
514 if (!open_file(path, query, fds, c))
516 c->state = S_SENDING;
519 len = (c->buf + c->len) - c->i;
522 switch (ret = tls_write(c->ctx, c->i, len)) {
524 LOGE(c, "tls_write: %s", tls_error(c->ctx));
528 case TLS_WANT_POLLIN:
529 fds->events = POLLIN;
532 case TLS_WANT_POLLOUT:
533 fds->events = POLLOUT;
547 send_dir(char *path, struct pollfd *fds, struct client *client)
552 bzero(fpath, PATHBUF);
557 /* this cannot fail since sizeof(fpath) > maxlen of path */
558 strlcat(fpath, path, PATHBUF);
561 /* add a trailing / in case. */
562 if (fpath[len-1] != '/') {
566 strlcat(fpath, "index.gmi", sizeof(fpath));
568 send_file(fpath, NULL, fds, client);
572 handle_handshake(struct pollfd *fds, struct client *c)
574 switch (tls_handshake(c->ctx)) {
575 case 0: /* success */
576 case -1: /* already handshaked */
578 case TLS_WANT_POLLIN:
579 fds->events = POLLIN;
581 case TLS_WANT_POLLOUT:
582 fds->events = POLLOUT;
589 /* TODO: check SNI here */
590 logs(LOG_DEBUG, c, "client wanted to talk to: %s", tls_conn_servername(c->ctx));
593 handle_open_conn(fds, c);
597 handle_open_conn(struct pollfd *fds, struct client *c)
599 char buf[GEMINI_URL_LEN];
600 const char *parse_err = "invalid request";
603 bzero(buf, sizeof(buf));
605 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
607 LOGE(c, "tls_read: %s", tls_error(c->ctx));
611 case TLS_WANT_POLLIN:
612 fds->events = POLLIN;
615 case TLS_WANT_POLLOUT:
616 fds->events = POLLOUT;
620 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
621 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
627 if (strcmp(iri.schema, "gemini")) {
628 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
634 LOGI(c, "GET %s%s%s",
635 *iri.path ? iri.path : "/",
636 *iri.query ? "?" : "",
637 *iri.query ? iri.query : "");
639 send_file(iri.path, iri.query, fds, c);
643 handle(struct pollfd *fds, struct client *client)
645 switch (client->state) {
647 handle_handshake(fds, client);
651 handle_open_conn(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 fatal("fcntl(F_GETFL): %s", strerror(errno));
692 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
693 fatal("fcntl(F_SETFL): %s", strerror(errno));
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)
730 fatal("socket: %s", strerror(errno));
733 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
734 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
737 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
738 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
742 if (bind(sock, addr, len) == -1)
743 fatal("bind: %s", strerror(errno));
745 if (listen(sock, 16) == -1)
746 fatal("listen: %s", strerror(errno));
752 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
755 struct sockaddr_storage addr;
759 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
760 if (errno == EWOULDBLOCK)
762 fatal("accept: %s", strerror(errno));
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_HANDSHAKE;
778 clients[i].child = -1;
779 clients[i].buf = MAP_FAILED;
780 clients[i].af = AF_INET;
781 clients[i].addr = 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 sock4, int sock6)
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));
840 if (poll(fds, MAX_USERS, INFTIM) == -1) {
841 if (errno == EINTR) {
842 warnx("connected clients: %d",
846 fatal("poll: %s", strerror(errno));
849 for (i = 0; i < MAX_USERS; i++) {
850 if (fds[i].revents == 0)
853 if (fds[i].revents & (POLLERR|POLLNVAL))
854 fatal("bad fd %d: %s", fds[i].fd,
857 if (fds[i].revents & POLLHUP) {
858 /* fds[i] may be the fd of the stdin
859 * of a cgi script that has exited. */
860 if (!clients[i].waiting_on_child) {
861 goodbye(&fds[i], &clients[i]);
866 if (fds[i].fd == sock4)
867 do_accept(sock4, ctx, fds, clients);
868 else if (fds[i].fd == sock6)
869 do_accept(sock6, ctx, fds, clients);
871 handle(&fds[i], &clients[i]);
877 absolutify_path(const char *path)
885 if (asprintf(&r, "%s/%s", wd, path) == -1)
892 usage(const char *me)
895 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
896 "[-l logfile] [-p port] [-x cgi-bin]\n",
901 main(int argc, char **argv)
903 const char *cert = "cert.pem", *key = "key.pem";
904 struct tls *ctx = NULL;
905 struct tls_config *conf;
906 int sock4, sock6, enable_ipv6, ch;
907 connected_clients = 0;
909 if ((dir = absolutify_path("docs")) == NULL)
910 err(1, "absolutify_path");
917 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
929 if ((dir = absolutify_path(optarg)) == NULL)
930 err(1, "absolutify_path");
950 lval = strtol(optarg, &ep, 10);
951 if (optarg[0] == '\0' || *ep != '\0')
952 err(1, "not a number: %s", optarg);
953 if (lval < 0 || lval > UINT16_MAX)
954 err(1, "port number out of range: %s", optarg);
969 signal(SIGPIPE, SIG_IGN);
970 signal(SIGCHLD, SIG_IGN);
973 signal(SIGINFO, sig_handler);
975 signal(SIGUSR2, sig_handler);
978 signal(SIGHUP, SIG_IGN);
980 if ((conf = tls_config_new()) == NULL)
981 err(1, "tls_config_new");
983 /* optionally accept client certs, but don't try to verify them */
984 tls_config_verify_client_optional(conf);
985 tls_config_insecure_noverifycert(conf);
987 if (tls_config_set_protocols(conf,
988 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
989 err(1, "tls_config_set_protocols");
991 if (tls_config_set_cert_file(conf, cert) == -1)
992 err(1, "tls_config_set_cert_file: %s", cert);
994 if (tls_config_set_key_file(conf, key) == -1)
995 err(1, "tls_config_set_key_file: %s", key);
997 if ((ctx = tls_server()) == NULL)
998 err(1, "tls_server");
1000 if (tls_configure(ctx, conf) == -1)
1001 errx(1, "tls_configure: %s", tls_error(ctx));
1003 sock4 = make_socket(port, AF_INET);
1005 sock6 = make_socket(port, AF_INET6);
1009 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
1010 err(1, "open: %s", dir);
1012 if (!foreground && daemon(0, 1) == -1)
1015 if (unveil(dir, "rx") == -1)
1018 if (pledge("stdio rpath inet proc exec", NULL) == -1)
1021 /* drop proc and exec if cgi isn't enabled */
1022 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
1025 loop(ctx, sock4, sock6);
1030 tls_config_free(conf);