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>
33 #define LOGE(c, fmt, ...) logs(LOG_ERR, c, fmt, __VA_ARGS__)
34 #define LOGN(c, fmt, ...) logs(LOG_NOTICE, c, fmt, __VA_ARGS__)
35 #define LOGI(c, fmt, ...) logs(LOG_INFO, c, fmt, __VA_ARGS__)
36 #define LOGD(c, fmt, ...) logs(LOG_DEBUG, c, fmt, __VA_ARGS__)
38 const char *dir, *cgi;
42 int connected_clients;
44 struct etm { /* file extension to mime */
48 {"application/pdf", "pdf"},
51 {"image/jpeg", "jpg"},
52 {"image/jpeg", "jpeg"},
54 {"image/svg+xml", "svg"},
56 {"text/gemini", "gemini"},
57 {"text/gemini", "gmi"},
58 {"text/markdown", "markdown"},
59 {"text/markdown", "md"},
60 {"text/plain", "txt"},
67 safe_setenv(const char *name, const char *val)
74 __attribute__ ((format (printf, 1, 2)))
75 static inline void __dead
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(struct pollfd *fds, struct client *client)
574 char buf[GEMINI_URL_LEN];
575 const char *parse_err;
578 switch (client->state) {
580 bzero(buf, GEMINI_URL_LEN);
581 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
583 LOGE(client, "tls_read: %s", tls_error(client->ctx));
584 goodbye(fds, client);
587 case TLS_WANT_POLLIN:
588 fds->events = POLLIN;
591 case TLS_WANT_POLLOUT:
592 fds->events = POLLOUT;
596 parse_err = "invalid request";
597 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
598 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
600 goodbye(fds, client);
604 LOGI(client, "GET %s%s%s",
605 *uri.path ? uri.path : "/",
606 *uri.query ? "?" : "",
607 *uri.query ? uri.query : "");
609 send_file(uri.path, uri.query, fds, client);
613 if (!start_reply(fds, client, client->code, client->meta))
616 if (client->code != SUCCESS) {
617 /* we don't need a body */
618 goodbye(fds, client);
622 client->state = S_SENDING;
627 if (client->child != -1)
628 handle_cgi(fds, client);
630 send_file(NULL, NULL, fds, client);
634 goodbye(fds, client);
644 mark_nonblock(int fd)
648 if ((flags = fcntl(fd, F_GETFL)) == -1)
649 fatal("fcntl(F_GETFL): %s", strerror(errno));
650 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
651 fatal("fcntl(F_SETFL): %s", strerror(errno));
655 make_socket(int port, int family)
658 struct sockaddr_in addr4;
659 struct sockaddr_in6 addr6;
660 struct sockaddr *addr;
665 bzero(&addr4, sizeof(addr4));
666 addr4.sin_family = family;
667 addr4.sin_port = htons(port);
668 addr4.sin_addr.s_addr = INADDR_ANY;
669 addr = (struct sockaddr*)&addr4;
674 bzero(&addr6, sizeof(addr6));
675 addr6.sin6_family = AF_INET6;
676 addr6.sin6_port = htons(port);
677 addr6.sin6_addr = in6addr_any;
678 addr = (struct sockaddr*)&addr6;
687 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
688 fatal("socket: %s", strerror(errno));
691 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
692 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
695 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
696 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
700 if (bind(sock, addr, len) == -1)
701 fatal("bind: %s", strerror(errno));
703 if (listen(sock, 16) == -1)
704 fatal("listen: %s", strerror(errno));
710 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
713 struct sockaddr_storage addr;
717 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
718 if (errno == EWOULDBLOCK)
720 fatal("accept: %s", strerror(errno));
725 for (i = 0; i < MAX_USERS; ++i) {
726 if (fds[i].fd == -1) {
727 bzero(&clients[i], sizeof(struct client));
728 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
729 break; /* goodbye fd! */
732 fds[i].events = POLLIN;
734 clients[i].state = S_OPEN;
736 clients[i].child = -1;
737 clients[i].buf = MAP_FAILED;
738 clients[i].af = AF_INET;
739 clients[i].addr = addr;
750 goodbye(struct pollfd *pfd, struct client *c)
754 c->state = S_CLOSING;
756 ret = tls_close(c->ctx);
757 if (ret == TLS_WANT_POLLIN) {
758 pfd->events = POLLIN;
761 if (ret == TLS_WANT_POLLOUT) {
762 pfd->events = POLLOUT;
771 if (c->buf != MAP_FAILED)
772 munmap(c->buf, c->len);
782 loop(struct tls *ctx, int sock4, int sock6)
785 struct client clients[MAX_USERS];
786 struct pollfd fds[MAX_USERS];
788 for (i = 0; i < MAX_USERS; ++i) {
790 fds[i].events = POLLIN;
791 bzero(&clients[i], sizeof(struct client));
798 if (poll(fds, MAX_USERS, INFTIM) == -1) {
799 if (errno == EINTR) {
800 warnx("connected clients: %d",
804 fatal("poll: %s", strerror(errno));
807 for (i = 0; i < MAX_USERS; i++) {
808 if (fds[i].revents == 0)
811 if (fds[i].revents & (POLLERR|POLLNVAL))
812 fatal("bad fd %d: %s", fds[i].fd,
815 if (fds[i].revents & POLLHUP) {
816 /* fds[i] may be the fd of the stdin
817 * of a cgi script that has exited. */
818 if (!clients[i].waiting_on_child) {
819 goodbye(&fds[i], &clients[i]);
824 if (fds[i].fd == sock4)
825 do_accept(sock4, ctx, fds, clients);
826 else if (fds[i].fd == sock6)
827 do_accept(sock6, ctx, fds, clients);
829 handle(&fds[i], &clients[i]);
835 absolutify_path(const char *path)
843 if (asprintf(&r, "%s/%s", wd, path) == -1)
850 usage(const char *me)
853 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
854 "[-l logfile] [-p port] [-x cgi-bin]\n",
859 main(int argc, char **argv)
861 const char *cert = "cert.pem", *key = "key.pem";
862 struct tls *ctx = NULL;
863 struct tls_config *conf;
864 int sock4, sock6, enable_ipv6, ch;
865 connected_clients = 0;
867 if ((dir = absolutify_path("docs")) == NULL)
868 err(1, "absolutify_path");
875 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
887 if ((dir = absolutify_path(optarg)) == NULL)
888 err(1, "absolutify_path");
908 lval = strtol(optarg, &ep, 10);
909 if (optarg[0] == '\0' || *ep != '\0')
910 err(1, "not a number: %s", optarg);
911 if (lval < 0 || lval > UINT16_MAX)
912 err(1, "port number out of range: %s", optarg);
927 signal(SIGPIPE, SIG_IGN);
928 signal(SIGCHLD, SIG_IGN);
931 signal(SIGINFO, sig_handler);
933 signal(SIGUSR2, sig_handler);
936 signal(SIGHUP, SIG_IGN);
938 if ((conf = tls_config_new()) == NULL)
939 err(1, "tls_config_new");
941 /* optionally accept client certs, but don't try to verify them */
942 tls_config_verify_client_optional(conf);
943 tls_config_insecure_noverifycert(conf);
945 if (tls_config_set_protocols(conf,
946 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
947 err(1, "tls_config_set_protocols");
949 if (tls_config_set_cert_file(conf, cert) == -1)
950 err(1, "tls_config_set_cert_file: %s", cert);
952 if (tls_config_set_key_file(conf, key) == -1)
953 err(1, "tls_config_set_key_file: %s", key);
955 if ((ctx = tls_server()) == NULL)
956 err(1, "tls_server");
958 if (tls_configure(ctx, conf) == -1)
959 errx(1, "tls_configure: %s", tls_error(ctx));
961 sock4 = make_socket(port, AF_INET);
963 sock6 = make_socket(port, AF_INET6);
967 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
968 err(1, "open: %s", dir);
970 if (!foreground && daemon(0, 1) == -1)
973 if (unveil(dir, "rx") == -1)
976 if (pledge("stdio rpath inet proc exec", NULL) == -1)
979 /* drop proc and exec if cgi isn't enabled */
980 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
983 loop(ctx, sock4, sock6);
988 tls_config_free(conf);