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 #define LOG(priority, c, fmt, ...) \
33 char buf[INET_ADDRSTRLEN]; \
34 if (inet_ntop((c)->af, &(c)->addr, \
35 buf, sizeof(buf)) == NULL) \
36 FATAL("inet_ntop: %s", strerror(errno)); \
39 "%s " fmt "\n", buf, __VA_ARGS__); \
41 syslog((priority) | LOG_DAEMON, \
42 "%s " fmt, buf, __VA_ARGS__); \
45 #define LOGE(c, fmt, ...) LOG(LOG_ERR, c, fmt, __VA_ARGS__)
46 #define LOGN(c, fmt, ...) LOG(LOG_NOTICE, c, fmt, __VA_ARGS__)
47 #define LOGI(c, fmt, ...) LOG(LOG_INFO, c, fmt, __VA_ARGS__)
48 #define LOGD(c, fmt, ...) LOG(LOG_DEBUG, c, fmt, __VA_ARGS__)
50 #define FATAL(fmt, ...) \
53 fprintf(stderr, fmt "\n", __VA_ARGS__); \
55 syslog(LOG_DAEMON | LOG_CRIT, \
60 const char *dir, *cgi;
64 int connected_clients;
66 struct etm { /* file extension to mime */
70 {"application/pdf", "pdf"},
73 {"image/jpeg", "jpg"},
74 {"image/jpeg", "jpeg"},
76 {"image/svg+xml", "svg"},
78 {"text/gemini", "gemini"},
79 {"text/gemini", "gmi"},
80 {"text/markdown", "markdown"},
81 {"text/markdown", "md"},
82 {"text/plain", "txt"},
89 safe_setenv(const char *name, const char *val)
103 starts_with(const char *str, const char *prefix)
107 for (i = 0; prefix[i] != '\0'; ++i)
108 if (str[i] != prefix[i])
114 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
116 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
121 client->meta = reason;
122 client->state = S_INITIALIZING;
124 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
125 assert(len < (int)sizeof(buf));
126 ret = tls_write(client->ctx, buf, len);
127 if (ret == TLS_WANT_POLLIN) {
128 pfd->events = POLLIN;
132 if (ret == TLS_WANT_POLLOUT) {
133 pfd->events = POLLOUT;
145 if ((len = lseek(fd, 0, SEEK_END)) == -1)
147 if (lseek(fd, 0, SEEK_SET) == -1)
153 path_ext(const char *path)
157 end = path + strlen(path)-1; /* the last byte before the NUL */
158 for (; end != path; --end) {
169 mime(const char *path)
171 const char *ext, *def = "application/octet-stream";
174 if ((ext = path_ext(path)) == NULL)
177 for (t = filetypes; t->mime != NULL; ++t)
178 if (!strcmp(ext, t->ext))
185 check_path(struct client *c, const char *path, int *fd)
189 assert(path != NULL);
190 if ((*fd = openat(dirfd, *path ? path : ".",
191 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
195 if (fstat(*fd, &sb) == -1) {
196 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
200 if (S_ISDIR(sb.st_mode))
201 return FILE_DIRECTORY;
203 if (sb.st_mode & S_IXUSR)
204 return FILE_EXECUTABLE;
210 * the inverse of this algorithm, i.e. starting from the start of the
211 * path + strlen(cgi), and checking if each component, should be
212 * faster. But it's tedious to write. This does the opposite: starts
213 * from the end and strip one component at a time, until either an
214 * executable is found or we emptied the path.
217 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
220 end = strchr(path, '\0');
222 /* NB: assume CGI is enabled and path matches cgi */
225 /* go up one level. UNIX paths are simple and POSIX
226 * dirname, with its ambiguities on if the given path
227 * is changed or not, gives me headaches. */
232 switch (check_path(c, path, &c->fd)) {
233 case FILE_EXECUTABLE:
234 return start_cgi(path, end+1, query, fds,c);
246 if (!start_reply(fds, c, NOT_FOUND, "not found"))
254 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
256 switch (check_path(c, fpath, &c->fd)) {
257 case FILE_EXECUTABLE:
258 if (cgi != NULL && starts_with(fpath, cgi))
259 return start_cgi(fpath, "", query, fds, c);
264 if ((c->len = filesize(c->fd)) == -1) {
265 LOGE(c, "failed to get file size for %s", fpath);
270 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
271 c->fd, 0)) == MAP_FAILED) {
272 warn("mmap: %s", fpath);
277 return start_reply(fds, c, SUCCESS, mime(fpath));
280 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
283 send_dir(fpath, fds, c);
287 if (cgi != NULL && starts_with(fpath, cgi))
288 return check_for_cgi(fpath, query, fds, c);
290 if (!start_reply(fds, c, NOT_FOUND, "not found"))
302 start_cgi(const char *spath, const char *relpath, const char *query,
303 struct pollfd *fds, struct client *c)
306 int p[2]; /* read end, write end */
311 switch (pid = fork()) {
315 case 0: { /* child */
316 char *ex, *requri, *portno;
317 char addr[INET_ADDRSTRLEN];
318 char *argv[] = { NULL, NULL, NULL };
321 if (dup2(p[1], 1) == -1)
324 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
327 if (asprintf(&portno, "%d", port) == -1)
330 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
333 if (asprintf(&requri, "%s%s%s", spath,
334 *relpath == '\0' ? "" : "/",
338 argv[0] = argv[1] = ex;
341 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
342 safe_setenv("SERVER_SOFTWARE", "gmid");
343 safe_setenv("SERVER_PORT", portno);
344 /* setenv("SERVER_NAME", "", 1); */
345 safe_setenv("SCRIPT_NAME", spath);
346 safe_setenv("SCRIPT_EXECUTABLE", ex);
347 safe_setenv("REQUEST_URI", requri);
348 safe_setenv("REQUEST_RELATIVE", relpath);
349 safe_setenv("QUERY_STRING", query);
350 safe_setenv("REMOTE_HOST", addr);
351 safe_setenv("REMOTE_ADDR", addr);
352 safe_setenv("DOCUMENT_ROOT", dir);
354 if (tls_peer_cert_provided(c->ctx)) {
355 safe_setenv("AUTH_TYPE", "Certificate");
356 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
357 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
358 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
365 default: /* parent */
370 mark_nonblock(c->fd);
371 c->state = S_SENDING;
377 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
383 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
389 cgi_poll_on_child(struct pollfd *fds, struct client *c)
393 if (c->waiting_on_child)
395 c->waiting_on_child = 1;
397 fds->events = POLLIN;
405 cgi_poll_on_client(struct pollfd *fds, struct client *c)
409 if (!c->waiting_on_child)
411 c->waiting_on_child = 0;
419 handle_cgi(struct pollfd *fds, struct client *c)
423 /* ensure c->fd is the child and fds->fd the client */
424 cgi_poll_on_client(fds, c);
428 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
431 if (errno == EAGAIN || errno == EWOULDBLOCK) {
432 cgi_poll_on_child(fds, c);
442 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
446 case TLS_WANT_POLLOUT:
447 fds->events = POLLOUT;
450 case TLS_WANT_POLLIN:
451 fds->events = POLLIN;
467 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
472 if (!open_file(path, query, fds, c))
474 c->state = S_SENDING;
477 len = (c->buf + c->len) - c->i;
480 switch (ret = tls_write(c->ctx, c->i, len)) {
482 LOGE(c, "tls_write: %s", tls_error(c->ctx));
486 case TLS_WANT_POLLIN:
487 fds->events = POLLIN;
490 case TLS_WANT_POLLOUT:
491 fds->events = POLLOUT;
505 send_dir(char *path, struct pollfd *fds, struct client *client)
510 bzero(fpath, PATHBUF);
515 /* this cannot fail since sizeof(fpath) > maxlen of path */
516 strlcat(fpath, path, PATHBUF);
519 /* add a trailing / in case. */
520 if (fpath[len-1] != '/') {
524 strlcat(fpath, "index.gmi", sizeof(fpath));
526 send_file(fpath, NULL, fds, client);
530 handle(struct pollfd *fds, struct client *client)
532 char buf[GEMINI_URL_LEN];
533 const char *parse_err;
536 switch (client->state) {
538 bzero(buf, GEMINI_URL_LEN);
539 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
541 LOGE(client, "tls_read: %s", tls_error(client->ctx));
542 goodbye(fds, client);
545 case TLS_WANT_POLLIN:
546 fds->events = POLLIN;
549 case TLS_WANT_POLLOUT:
550 fds->events = POLLOUT;
554 parse_err = "invalid request";
555 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
556 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
558 goodbye(fds, client);
562 LOGI(client, "GET %s%s%s",
563 *uri.path ? uri.path : "/",
564 *uri.query ? "?" : "",
565 *uri.query ? uri.query : "");
567 send_file(uri.path, uri.query, fds, client);
571 if (!start_reply(fds, client, client->code, client->meta))
574 if (client->code != SUCCESS) {
575 /* we don't need a body */
576 goodbye(fds, client);
580 client->state = S_SENDING;
585 if (client->child != -1)
586 handle_cgi(fds, client);
588 send_file(NULL, NULL, fds, client);
592 goodbye(fds, client);
602 mark_nonblock(int fd)
606 if ((flags = fcntl(fd, F_GETFL)) == -1)
607 FATAL("fcntl(F_GETFL): %s", strerror(errno));
608 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
609 FATAL("fcntl(F_SETFL): %s", strerror(errno));
613 make_socket(int port, int family)
616 struct sockaddr_in addr4;
617 struct sockaddr_in6 addr6;
618 struct sockaddr *addr;
623 bzero(&addr4, sizeof(addr4));
624 addr4.sin_family = family;
625 addr4.sin_port = htons(port);
626 addr4.sin_addr.s_addr = INADDR_ANY;
627 addr = (struct sockaddr*)&addr4;
632 bzero(&addr6, sizeof(addr6));
633 addr6.sin6_family = AF_INET6;
634 addr6.sin6_port = htons(port);
635 addr6.sin6_addr = in6addr_any;
636 addr = (struct sockaddr*)&addr6;
645 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
646 FATAL("socket: %s", strerror(errno));
649 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
650 FATAL("setsockopt(SO_REUSEADDR): %s", strerror(errno));
653 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
654 FATAL("setsockopt(SO_REUSEPORT): %s", strerror(errno));
658 if (bind(sock, addr, len) == -1)
659 FATAL("bind: %s", strerror(errno));
661 if (listen(sock, 16) == -1)
662 FATAL("listen: %s", strerror(errno));
668 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
671 struct sockaddr_in addr;
675 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
676 if (errno == EWOULDBLOCK)
678 FATAL("accept: %s", strerror(errno));
683 for (i = 0; i < MAX_USERS; ++i) {
684 if (fds[i].fd == -1) {
685 bzero(&clients[i], sizeof(struct client));
686 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
687 break; /* goodbye fd! */
690 fds[i].events = POLLIN;
692 clients[i].state = S_OPEN;
694 clients[i].child = -1;
695 clients[i].buf = MAP_FAILED;
696 clients[i].af = AF_INET;
697 clients[i].addr = addr.sin_addr;
708 goodbye(struct pollfd *pfd, struct client *c)
712 c->state = S_CLOSING;
714 ret = tls_close(c->ctx);
715 if (ret == TLS_WANT_POLLIN) {
716 pfd->events = POLLIN;
719 if (ret == TLS_WANT_POLLOUT) {
720 pfd->events = POLLOUT;
729 if (c->buf != MAP_FAILED)
730 munmap(c->buf, c->len);
740 loop(struct tls *ctx, int sock)
743 struct client clients[MAX_USERS];
744 struct pollfd fds[MAX_USERS];
746 for (i = 0; i < MAX_USERS; ++i) {
748 fds[i].events = POLLIN;
749 bzero(&clients[i], sizeof(struct client));
755 if (poll(fds, MAX_USERS, INFTIM) == -1) {
756 if (errno == EINTR) {
757 warnx("connected clients: %d",
761 FATAL("poll: %s", strerror(errno));
764 for (i = 0; i < MAX_USERS; i++) {
765 if (fds[i].revents == 0)
768 if (fds[i].revents & (POLLERR|POLLNVAL))
769 FATAL("bad fd %d: %s", fds[i].fd,
772 if (fds[i].revents & POLLHUP) {
773 /* fds[i] may be the fd of the stdin
774 * of a cgi script that has exited. */
775 if (!clients[i].waiting_on_child) {
776 goodbye(&fds[i], &clients[i]);
781 if (i == 0) { /* new client */
782 do_accept(sock, ctx, fds, clients);
786 handle(&fds[i], &clients[i]);
792 absolutify_path(const char *path)
800 if (asprintf(&r, "%s/%s", wd, path) == -1)
807 usage(const char *me)
810 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
811 "[-l logfile] [-p port] [-x cgi-bin]\n",
816 main(int argc, char **argv)
818 const char *cert = "cert.pem", *key = "key.pem";
819 struct tls *ctx = NULL;
820 struct tls_config *conf;
822 connected_clients = 0;
824 if ((dir = absolutify_path("docs")) == NULL)
825 err(1, "absolutify_path");
831 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
839 if ((dir = absolutify_path(optarg)) == NULL)
840 err(1, "absolutify_path");
860 lval = strtol(optarg, &ep, 10);
861 if (optarg[0] == '\0' || *ep != '\0')
862 err(1, "not a number: %s", optarg);
863 if (lval < 0 || lval > UINT16_MAX)
864 err(1, "port number out of range: %s", optarg);
879 signal(SIGPIPE, SIG_IGN);
880 signal(SIGCHLD, SIG_IGN);
883 signal(SIGINFO, sig_handler);
885 signal(SIGUSR2, sig_handler);
888 signal(SIGHUP, SIG_IGN);
890 if ((conf = tls_config_new()) == NULL)
891 err(1, "tls_config_new");
893 /* optionally accept client certs, but don't try to verify them */
894 tls_config_verify_client_optional(conf);
895 tls_config_insecure_noverifycert(conf);
897 if (tls_config_set_protocols(conf,
898 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
899 err(1, "tls_config_set_protocols");
901 if (tls_config_set_cert_file(conf, cert) == -1)
902 err(1, "tls_config_set_cert_file: %s", cert);
904 if (tls_config_set_key_file(conf, key) == -1)
905 err(1, "tls_config_set_key_file: %s", key);
907 if ((ctx = tls_server()) == NULL)
908 err(1, "tls_server");
910 if (tls_configure(ctx, conf) == -1)
911 errx(1, "tls_configure: %s", tls_error(ctx));
913 sock = make_socket(port, AF_INET);
915 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
916 err(1, "open: %s", dir);
918 if (!foreground && daemon(0, 1) == -1)
921 if (unveil(dir, "rx") == -1)
924 if (pledge("stdio rpath inet proc exec", NULL) == -1)
927 /* drop proc and exec if cgi isn't enabled */
928 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
935 tls_config_free(conf);