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 static inline void __dead
75 fatal(const char *fmt, ...)
82 vfprintf(stderr, fmt, ap);
83 fprintf(stderr, "\n");
85 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
91 __attribute__ ((format (printf, 3, 4)))
93 logs(int priority, struct client *c,
96 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
104 len = sizeof(c->addr);
105 ec = getnameinfo((struct sockaddr*)&c->addr, len,
108 NI_NUMERICHOST | NI_NUMERICSERV);
110 fatal("getnameinfo: %s", gai_strerror(ec));
112 if (vasprintf(&fmted, fmt, ap) == -1)
113 fatal("vasprintf: %s", strerror(errno));
116 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
118 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
119 fatal("asprintf: %s", strerror(errno));
120 syslog(priority | LOG_DAEMON, "%s", s);
136 starts_with(const char *str, const char *prefix)
140 for (i = 0; prefix[i] != '\0'; ++i)
141 if (str[i] != prefix[i])
147 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
149 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
154 client->meta = reason;
155 client->state = S_INITIALIZING;
157 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
158 assert(len < (int)sizeof(buf));
159 ret = tls_write(client->ctx, buf, len);
160 if (ret == TLS_WANT_POLLIN) {
161 pfd->events = POLLIN;
165 if (ret == TLS_WANT_POLLOUT) {
166 pfd->events = POLLOUT;
178 if ((len = lseek(fd, 0, SEEK_END)) == -1)
180 if (lseek(fd, 0, SEEK_SET) == -1)
186 path_ext(const char *path)
190 end = path + strlen(path)-1; /* the last byte before the NUL */
191 for (; end != path; --end) {
202 mime(const char *path)
204 const char *ext, *def = "application/octet-stream";
207 if ((ext = path_ext(path)) == NULL)
210 for (t = filetypes; t->mime != NULL; ++t)
211 if (!strcmp(ext, t->ext))
218 check_path(struct client *c, const char *path, int *fd)
222 assert(path != NULL);
223 if ((*fd = openat(dirfd, *path ? path : ".",
224 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
228 if (fstat(*fd, &sb) == -1) {
229 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
233 if (S_ISDIR(sb.st_mode))
234 return FILE_DIRECTORY;
236 if (sb.st_mode & S_IXUSR)
237 return FILE_EXECUTABLE;
243 * the inverse of this algorithm, i.e. starting from the start of the
244 * path + strlen(cgi), and checking if each component, should be
245 * faster. But it's tedious to write. This does the opposite: starts
246 * from the end and strip one component at a time, until either an
247 * executable is found or we emptied the path.
250 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
253 end = strchr(path, '\0');
255 /* NB: assume CGI is enabled and path matches cgi */
258 /* go up one level. UNIX paths are simple and POSIX
259 * dirname, with its ambiguities on if the given path
260 * is changed or not, gives me headaches. */
265 switch (check_path(c, path, &c->fd)) {
266 case FILE_EXECUTABLE:
267 return start_cgi(path, end+1, query, fds,c);
279 if (!start_reply(fds, c, NOT_FOUND, "not found"))
287 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
289 switch (check_path(c, fpath, &c->fd)) {
290 case FILE_EXECUTABLE:
291 if (cgi != NULL && starts_with(fpath, cgi))
292 return start_cgi(fpath, "", query, fds, c);
297 if ((c->len = filesize(c->fd)) == -1) {
298 LOGE(c, "failed to get file size for %s", fpath);
303 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
304 c->fd, 0)) == MAP_FAILED) {
305 warn("mmap: %s", fpath);
310 return start_reply(fds, c, SUCCESS, mime(fpath));
313 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
316 send_dir(fpath, fds, c);
320 if (cgi != NULL && starts_with(fpath, cgi))
321 return check_for_cgi(fpath, query, fds, c);
323 if (!start_reply(fds, c, NOT_FOUND, "not found"))
335 start_cgi(const char *spath, const char *relpath, const char *query,
336 struct pollfd *fds, struct client *c)
339 int p[2]; /* read end, write end */
344 switch (pid = fork()) {
348 case 0: { /* child */
349 char *ex, *requri, *portno;
350 char addr[NI_MAXHOST];
351 char *argv[] = { NULL, NULL, NULL };
355 if (dup2(p[1], 1) == -1)
358 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
361 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
364 NI_NUMERICHOST | NI_NUMERICSERV);
368 if (asprintf(&portno, "%d", port) == -1)
371 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
374 if (asprintf(&requri, "%s%s%s", spath,
375 *relpath == '\0' ? "" : "/",
379 argv[0] = argv[1] = ex;
382 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
383 safe_setenv("SERVER_SOFTWARE", "gmid");
384 safe_setenv("SERVER_PORT", portno);
385 /* setenv("SERVER_NAME", "", 1); */
386 safe_setenv("SCRIPT_NAME", spath);
387 safe_setenv("SCRIPT_EXECUTABLE", ex);
388 safe_setenv("REQUEST_URI", requri);
389 safe_setenv("REQUEST_RELATIVE", relpath);
390 safe_setenv("QUERY_STRING", query);
391 safe_setenv("REMOTE_HOST", addr);
392 safe_setenv("REMOTE_ADDR", addr);
393 safe_setenv("DOCUMENT_ROOT", dir);
395 if (tls_peer_cert_provided(c->ctx)) {
396 safe_setenv("AUTH_TYPE", "Certificate");
397 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
398 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
399 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
406 default: /* parent */
411 mark_nonblock(c->fd);
412 c->state = S_SENDING;
418 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
424 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
430 cgi_poll_on_child(struct pollfd *fds, struct client *c)
434 if (c->waiting_on_child)
436 c->waiting_on_child = 1;
438 fds->events = POLLIN;
446 cgi_poll_on_client(struct pollfd *fds, struct client *c)
450 if (!c->waiting_on_child)
452 c->waiting_on_child = 0;
460 handle_cgi(struct pollfd *fds, struct client *c)
464 /* ensure c->fd is the child and fds->fd the client */
465 cgi_poll_on_client(fds, c);
469 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
472 if (errno == EAGAIN || errno == EWOULDBLOCK) {
473 cgi_poll_on_child(fds, c);
483 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
487 case TLS_WANT_POLLOUT:
488 fds->events = POLLOUT;
491 case TLS_WANT_POLLIN:
492 fds->events = POLLIN;
508 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
513 if (!open_file(path, query, fds, c))
515 c->state = S_SENDING;
518 len = (c->buf + c->len) - c->i;
521 switch (ret = tls_write(c->ctx, c->i, len)) {
523 LOGE(c, "tls_write: %s", tls_error(c->ctx));
527 case TLS_WANT_POLLIN:
528 fds->events = POLLIN;
531 case TLS_WANT_POLLOUT:
532 fds->events = POLLOUT;
546 send_dir(char *path, struct pollfd *fds, struct client *client)
551 bzero(fpath, PATHBUF);
556 /* this cannot fail since sizeof(fpath) > maxlen of path */
557 strlcat(fpath, path, PATHBUF);
560 /* add a trailing / in case. */
561 if (fpath[len-1] != '/') {
565 strlcat(fpath, "index.gmi", sizeof(fpath));
567 send_file(fpath, NULL, fds, client);
571 handle(struct pollfd *fds, struct client *client)
573 char buf[GEMINI_URL_LEN];
574 const char *parse_err;
577 switch (client->state) {
579 bzero(buf, GEMINI_URL_LEN);
580 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
582 LOGE(client, "tls_read: %s", tls_error(client->ctx));
583 goodbye(fds, client);
586 case TLS_WANT_POLLIN:
587 fds->events = POLLIN;
590 case TLS_WANT_POLLOUT:
591 fds->events = POLLOUT;
595 parse_err = "invalid request";
596 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
597 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
599 goodbye(fds, client);
603 if (strcmp(iri.schema, "gemini")) {
604 if (!start_reply(fds, client, PROXY_REFUSED, "won't proxy request"))
606 goodbye(fds, client);
610 LOGI(client, "GET %s%s%s",
611 *iri.path ? iri.path : "/",
612 *iri.query ? "?" : "",
613 *iri.query ? iri.query : "");
615 send_file(iri.path, iri.query, fds, client);
619 if (!start_reply(fds, client, client->code, client->meta))
622 if (client->code != SUCCESS) {
623 /* we don't need a body */
624 goodbye(fds, client);
628 client->state = S_SENDING;
633 if (client->child != -1)
634 handle_cgi(fds, client);
636 send_file(NULL, NULL, fds, client);
640 goodbye(fds, client);
650 mark_nonblock(int fd)
654 if ((flags = fcntl(fd, F_GETFL)) == -1)
655 fatal("fcntl(F_GETFL): %s", strerror(errno));
656 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
657 fatal("fcntl(F_SETFL): %s", strerror(errno));
661 make_socket(int port, int family)
664 struct sockaddr_in addr4;
665 struct sockaddr_in6 addr6;
666 struct sockaddr *addr;
671 bzero(&addr4, sizeof(addr4));
672 addr4.sin_family = family;
673 addr4.sin_port = htons(port);
674 addr4.sin_addr.s_addr = INADDR_ANY;
675 addr = (struct sockaddr*)&addr4;
680 bzero(&addr6, sizeof(addr6));
681 addr6.sin6_family = AF_INET6;
682 addr6.sin6_port = htons(port);
683 addr6.sin6_addr = in6addr_any;
684 addr = (struct sockaddr*)&addr6;
693 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
694 fatal("socket: %s", strerror(errno));
697 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
698 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
701 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
702 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
706 if (bind(sock, addr, len) == -1)
707 fatal("bind: %s", strerror(errno));
709 if (listen(sock, 16) == -1)
710 fatal("listen: %s", strerror(errno));
716 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
719 struct sockaddr_storage addr;
723 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
724 if (errno == EWOULDBLOCK)
726 fatal("accept: %s", strerror(errno));
731 for (i = 0; i < MAX_USERS; ++i) {
732 if (fds[i].fd == -1) {
733 bzero(&clients[i], sizeof(struct client));
734 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
735 break; /* goodbye fd! */
738 fds[i].events = POLLIN;
740 clients[i].state = S_OPEN;
742 clients[i].child = -1;
743 clients[i].buf = MAP_FAILED;
744 clients[i].af = AF_INET;
745 clients[i].addr = addr;
756 goodbye(struct pollfd *pfd, struct client *c)
760 c->state = S_CLOSING;
762 ret = tls_close(c->ctx);
763 if (ret == TLS_WANT_POLLIN) {
764 pfd->events = POLLIN;
767 if (ret == TLS_WANT_POLLOUT) {
768 pfd->events = POLLOUT;
777 if (c->buf != MAP_FAILED)
778 munmap(c->buf, c->len);
788 loop(struct tls *ctx, int sock4, int sock6)
791 struct client clients[MAX_USERS];
792 struct pollfd fds[MAX_USERS];
794 for (i = 0; i < MAX_USERS; ++i) {
796 fds[i].events = POLLIN;
797 bzero(&clients[i], sizeof(struct client));
804 if (poll(fds, MAX_USERS, INFTIM) == -1) {
805 if (errno == EINTR) {
806 warnx("connected clients: %d",
810 fatal("poll: %s", strerror(errno));
813 for (i = 0; i < MAX_USERS; i++) {
814 if (fds[i].revents == 0)
817 if (fds[i].revents & (POLLERR|POLLNVAL))
818 fatal("bad fd %d: %s", fds[i].fd,
821 if (fds[i].revents & POLLHUP) {
822 /* fds[i] may be the fd of the stdin
823 * of a cgi script that has exited. */
824 if (!clients[i].waiting_on_child) {
825 goodbye(&fds[i], &clients[i]);
830 if (fds[i].fd == sock4)
831 do_accept(sock4, ctx, fds, clients);
832 else if (fds[i].fd == sock6)
833 do_accept(sock6, ctx, fds, clients);
835 handle(&fds[i], &clients[i]);
841 absolutify_path(const char *path)
849 if (asprintf(&r, "%s/%s", wd, path) == -1)
856 usage(const char *me)
859 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
860 "[-l logfile] [-p port] [-x cgi-bin]\n",
865 main(int argc, char **argv)
867 const char *cert = "cert.pem", *key = "key.pem";
868 struct tls *ctx = NULL;
869 struct tls_config *conf;
870 int sock4, sock6, enable_ipv6, ch;
871 connected_clients = 0;
873 if ((dir = absolutify_path("docs")) == NULL)
874 err(1, "absolutify_path");
881 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
893 if ((dir = absolutify_path(optarg)) == NULL)
894 err(1, "absolutify_path");
914 lval = strtol(optarg, &ep, 10);
915 if (optarg[0] == '\0' || *ep != '\0')
916 err(1, "not a number: %s", optarg);
917 if (lval < 0 || lval > UINT16_MAX)
918 err(1, "port number out of range: %s", optarg);
933 signal(SIGPIPE, SIG_IGN);
934 signal(SIGCHLD, SIG_IGN);
937 signal(SIGINFO, sig_handler);
939 signal(SIGUSR2, sig_handler);
942 signal(SIGHUP, SIG_IGN);
944 if ((conf = tls_config_new()) == NULL)
945 err(1, "tls_config_new");
947 /* optionally accept client certs, but don't try to verify them */
948 tls_config_verify_client_optional(conf);
949 tls_config_insecure_noverifycert(conf);
951 if (tls_config_set_protocols(conf,
952 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
953 err(1, "tls_config_set_protocols");
955 if (tls_config_set_cert_file(conf, cert) == -1)
956 err(1, "tls_config_set_cert_file: %s", cert);
958 if (tls_config_set_key_file(conf, key) == -1)
959 err(1, "tls_config_set_key_file: %s", key);
961 if ((ctx = tls_server()) == NULL)
962 err(1, "tls_server");
964 if (tls_configure(ctx, conf) == -1)
965 errx(1, "tls_configure: %s", tls_error(ctx));
967 sock4 = make_socket(port, AF_INET);
969 sock6 = make_socket(port, AF_INET6);
973 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
974 err(1, "open: %s", dir);
976 if (!foreground && daemon(0, 1) == -1)
979 if (unveil(dir, "rx") == -1)
982 if (pledge("stdio rpath inet proc exec", NULL) == -1)
985 /* drop proc and exec if cgi isn't enabled */
986 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
989 loop(ctx, sock4, sock6);
994 tls_config_free(conf);