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 LOGI(client, "GET %s%s%s",
604 *iri.path ? iri.path : "/",
605 *iri.query ? "?" : "",
606 *iri.query ? iri.query : "");
608 send_file(iri.path, iri.query, fds, client);
612 if (!start_reply(fds, client, client->code, client->meta))
615 if (client->code != SUCCESS) {
616 /* we don't need a body */
617 goodbye(fds, client);
621 client->state = S_SENDING;
626 if (client->child != -1)
627 handle_cgi(fds, client);
629 send_file(NULL, NULL, fds, client);
633 goodbye(fds, client);
643 mark_nonblock(int fd)
647 if ((flags = fcntl(fd, F_GETFL)) == -1)
648 fatal("fcntl(F_GETFL): %s", strerror(errno));
649 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
650 fatal("fcntl(F_SETFL): %s", strerror(errno));
654 make_socket(int port, int family)
657 struct sockaddr_in addr4;
658 struct sockaddr_in6 addr6;
659 struct sockaddr *addr;
664 bzero(&addr4, sizeof(addr4));
665 addr4.sin_family = family;
666 addr4.sin_port = htons(port);
667 addr4.sin_addr.s_addr = INADDR_ANY;
668 addr = (struct sockaddr*)&addr4;
673 bzero(&addr6, sizeof(addr6));
674 addr6.sin6_family = AF_INET6;
675 addr6.sin6_port = htons(port);
676 addr6.sin6_addr = in6addr_any;
677 addr = (struct sockaddr*)&addr6;
686 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
687 fatal("socket: %s", strerror(errno));
690 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
691 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
694 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
695 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
699 if (bind(sock, addr, len) == -1)
700 fatal("bind: %s", strerror(errno));
702 if (listen(sock, 16) == -1)
703 fatal("listen: %s", strerror(errno));
709 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
712 struct sockaddr_storage addr;
716 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
717 if (errno == EWOULDBLOCK)
719 fatal("accept: %s", strerror(errno));
724 for (i = 0; i < MAX_USERS; ++i) {
725 if (fds[i].fd == -1) {
726 bzero(&clients[i], sizeof(struct client));
727 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
728 break; /* goodbye fd! */
731 fds[i].events = POLLIN;
733 clients[i].state = S_OPEN;
735 clients[i].child = -1;
736 clients[i].buf = MAP_FAILED;
737 clients[i].af = AF_INET;
738 clients[i].addr = addr;
749 goodbye(struct pollfd *pfd, struct client *c)
753 c->state = S_CLOSING;
755 ret = tls_close(c->ctx);
756 if (ret == TLS_WANT_POLLIN) {
757 pfd->events = POLLIN;
760 if (ret == TLS_WANT_POLLOUT) {
761 pfd->events = POLLOUT;
770 if (c->buf != MAP_FAILED)
771 munmap(c->buf, c->len);
781 loop(struct tls *ctx, int sock4, int sock6)
784 struct client clients[MAX_USERS];
785 struct pollfd fds[MAX_USERS];
787 for (i = 0; i < MAX_USERS; ++i) {
789 fds[i].events = POLLIN;
790 bzero(&clients[i], sizeof(struct client));
797 if (poll(fds, MAX_USERS, INFTIM) == -1) {
798 if (errno == EINTR) {
799 warnx("connected clients: %d",
803 fatal("poll: %s", strerror(errno));
806 for (i = 0; i < MAX_USERS; i++) {
807 if (fds[i].revents == 0)
810 if (fds[i].revents & (POLLERR|POLLNVAL))
811 fatal("bad fd %d: %s", fds[i].fd,
814 if (fds[i].revents & POLLHUP) {
815 /* fds[i] may be the fd of the stdin
816 * of a cgi script that has exited. */
817 if (!clients[i].waiting_on_child) {
818 goodbye(&fds[i], &clients[i]);
823 if (fds[i].fd == sock4)
824 do_accept(sock4, ctx, fds, clients);
825 else if (fds[i].fd == sock6)
826 do_accept(sock6, ctx, fds, clients);
828 handle(&fds[i], &clients[i]);
834 absolutify_path(const char *path)
842 if (asprintf(&r, "%s/%s", wd, path) == -1)
849 usage(const char *me)
852 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
853 "[-l logfile] [-p port] [-x cgi-bin]\n",
858 main(int argc, char **argv)
860 const char *cert = "cert.pem", *key = "key.pem";
861 struct tls *ctx = NULL;
862 struct tls_config *conf;
863 int sock4, sock6, enable_ipv6, ch;
864 connected_clients = 0;
866 if ((dir = absolutify_path("docs")) == NULL)
867 err(1, "absolutify_path");
874 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
886 if ((dir = absolutify_path(optarg)) == NULL)
887 err(1, "absolutify_path");
907 lval = strtol(optarg, &ep, 10);
908 if (optarg[0] == '\0' || *ep != '\0')
909 err(1, "not a number: %s", optarg);
910 if (lval < 0 || lval > UINT16_MAX)
911 err(1, "port number out of range: %s", optarg);
926 signal(SIGPIPE, SIG_IGN);
927 signal(SIGCHLD, SIG_IGN);
930 signal(SIGINFO, sig_handler);
932 signal(SIGUSR2, sig_handler);
935 signal(SIGHUP, SIG_IGN);
937 if ((conf = tls_config_new()) == NULL)
938 err(1, "tls_config_new");
940 /* optionally accept client certs, but don't try to verify them */
941 tls_config_verify_client_optional(conf);
942 tls_config_insecure_noverifycert(conf);
944 if (tls_config_set_protocols(conf,
945 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
946 err(1, "tls_config_set_protocols");
948 if (tls_config_set_cert_file(conf, cert) == -1)
949 err(1, "tls_config_set_cert_file: %s", cert);
951 if (tls_config_set_key_file(conf, key) == -1)
952 err(1, "tls_config_set_key_file: %s", key);
954 if ((ctx = tls_server()) == NULL)
955 err(1, "tls_server");
957 if (tls_configure(ctx, conf) == -1)
958 errx(1, "tls_configure: %s", tls_error(ctx));
960 sock4 = make_socket(port, AF_INET);
962 sock6 = make_socket(port, AF_INET6);
966 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
967 err(1, "open: %s", dir);
969 if (!foreground && daemon(0, 1) == -1)
972 if (unveil(dir, "rx") == -1)
975 if (pledge("stdio rpath inet proc exec", NULL) == -1)
978 /* drop proc and exec if cgi isn't enabled */
979 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
982 loop(ctx, sock4, sock6);
987 tls_config_free(conf);