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>
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, const char *fmt, ...)
95 char buf[INET_ADDRSTRLEN];
99 priority |= LOG_DAEMON;
101 if (inet_ntop(c->af, &c->addr, buf, sizeof(buf)) == NULL)
102 fatal("inet_ntop: %s", strerror(errno));
105 vfprintf(stderr, fmt, ap);
106 fprintf(stderr, "\n");
108 vsyslog(priority, fmt, ap);
120 starts_with(const char *str, const char *prefix)
124 for (i = 0; prefix[i] != '\0'; ++i)
125 if (str[i] != prefix[i])
131 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
133 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
138 client->meta = reason;
139 client->state = S_INITIALIZING;
141 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
142 assert(len < (int)sizeof(buf));
143 ret = tls_write(client->ctx, buf, len);
144 if (ret == TLS_WANT_POLLIN) {
145 pfd->events = POLLIN;
149 if (ret == TLS_WANT_POLLOUT) {
150 pfd->events = POLLOUT;
162 if ((len = lseek(fd, 0, SEEK_END)) == -1)
164 if (lseek(fd, 0, SEEK_SET) == -1)
170 path_ext(const char *path)
174 end = path + strlen(path)-1; /* the last byte before the NUL */
175 for (; end != path; --end) {
186 mime(const char *path)
188 const char *ext, *def = "application/octet-stream";
191 if ((ext = path_ext(path)) == NULL)
194 for (t = filetypes; t->mime != NULL; ++t)
195 if (!strcmp(ext, t->ext))
202 check_path(struct client *c, const char *path, int *fd)
206 assert(path != NULL);
207 if ((*fd = openat(dirfd, *path ? path : ".",
208 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
212 if (fstat(*fd, &sb) == -1) {
213 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
217 if (S_ISDIR(sb.st_mode))
218 return FILE_DIRECTORY;
220 if (sb.st_mode & S_IXUSR)
221 return FILE_EXECUTABLE;
227 * the inverse of this algorithm, i.e. starting from the start of the
228 * path + strlen(cgi), and checking if each component, should be
229 * faster. But it's tedious to write. This does the opposite: starts
230 * from the end and strip one component at a time, until either an
231 * executable is found or we emptied the path.
234 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
237 end = strchr(path, '\0');
239 /* NB: assume CGI is enabled and path matches cgi */
242 /* go up one level. UNIX paths are simple and POSIX
243 * dirname, with its ambiguities on if the given path
244 * is changed or not, gives me headaches. */
249 switch (check_path(c, path, &c->fd)) {
250 case FILE_EXECUTABLE:
251 return start_cgi(path, end+1, query, fds,c);
263 if (!start_reply(fds, c, NOT_FOUND, "not found"))
271 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
273 switch (check_path(c, fpath, &c->fd)) {
274 case FILE_EXECUTABLE:
275 if (cgi != NULL && starts_with(fpath, cgi))
276 return start_cgi(fpath, "", query, fds, c);
281 if ((c->len = filesize(c->fd)) == -1) {
282 LOGE(c, "failed to get file size for %s", fpath);
287 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
288 c->fd, 0)) == MAP_FAILED) {
289 warn("mmap: %s", fpath);
294 return start_reply(fds, c, SUCCESS, mime(fpath));
297 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
300 send_dir(fpath, fds, c);
304 if (cgi != NULL && starts_with(fpath, cgi))
305 return check_for_cgi(fpath, query, fds, c);
307 if (!start_reply(fds, c, NOT_FOUND, "not found"))
319 start_cgi(const char *spath, const char *relpath, const char *query,
320 struct pollfd *fds, struct client *c)
323 int p[2]; /* read end, write end */
328 switch (pid = fork()) {
332 case 0: { /* child */
333 char *ex, *requri, *portno;
334 char addr[INET_ADDRSTRLEN];
335 char *argv[] = { NULL, NULL, NULL };
338 if (dup2(p[1], 1) == -1)
341 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
344 if (asprintf(&portno, "%d", port) == -1)
347 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
350 if (asprintf(&requri, "%s%s%s", spath,
351 *relpath == '\0' ? "" : "/",
355 argv[0] = argv[1] = ex;
358 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
359 safe_setenv("SERVER_SOFTWARE", "gmid");
360 safe_setenv("SERVER_PORT", portno);
361 /* setenv("SERVER_NAME", "", 1); */
362 safe_setenv("SCRIPT_NAME", spath);
363 safe_setenv("SCRIPT_EXECUTABLE", ex);
364 safe_setenv("REQUEST_URI", requri);
365 safe_setenv("REQUEST_RELATIVE", relpath);
366 safe_setenv("QUERY_STRING", query);
367 safe_setenv("REMOTE_HOST", addr);
368 safe_setenv("REMOTE_ADDR", addr);
369 safe_setenv("DOCUMENT_ROOT", dir);
371 if (tls_peer_cert_provided(c->ctx)) {
372 safe_setenv("AUTH_TYPE", "Certificate");
373 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
374 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
375 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
382 default: /* parent */
387 mark_nonblock(c->fd);
388 c->state = S_SENDING;
394 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
400 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
406 cgi_poll_on_child(struct pollfd *fds, struct client *c)
410 if (c->waiting_on_child)
412 c->waiting_on_child = 1;
414 fds->events = POLLIN;
422 cgi_poll_on_client(struct pollfd *fds, struct client *c)
426 if (!c->waiting_on_child)
428 c->waiting_on_child = 0;
436 handle_cgi(struct pollfd *fds, struct client *c)
440 /* ensure c->fd is the child and fds->fd the client */
441 cgi_poll_on_client(fds, c);
445 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
448 if (errno == EAGAIN || errno == EWOULDBLOCK) {
449 cgi_poll_on_child(fds, c);
459 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
463 case TLS_WANT_POLLOUT:
464 fds->events = POLLOUT;
467 case TLS_WANT_POLLIN:
468 fds->events = POLLIN;
484 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
489 if (!open_file(path, query, fds, c))
491 c->state = S_SENDING;
494 len = (c->buf + c->len) - c->i;
497 switch (ret = tls_write(c->ctx, c->i, len)) {
499 LOGE(c, "tls_write: %s", tls_error(c->ctx));
503 case TLS_WANT_POLLIN:
504 fds->events = POLLIN;
507 case TLS_WANT_POLLOUT:
508 fds->events = POLLOUT;
522 send_dir(char *path, struct pollfd *fds, struct client *client)
527 bzero(fpath, PATHBUF);
532 /* this cannot fail since sizeof(fpath) > maxlen of path */
533 strlcat(fpath, path, PATHBUF);
536 /* add a trailing / in case. */
537 if (fpath[len-1] != '/') {
541 strlcat(fpath, "index.gmi", sizeof(fpath));
543 send_file(fpath, NULL, fds, client);
547 handle(struct pollfd *fds, struct client *client)
549 char buf[GEMINI_URL_LEN];
550 const char *parse_err;
553 switch (client->state) {
555 bzero(buf, GEMINI_URL_LEN);
556 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
558 LOGE(client, "tls_read: %s", tls_error(client->ctx));
559 goodbye(fds, client);
562 case TLS_WANT_POLLIN:
563 fds->events = POLLIN;
566 case TLS_WANT_POLLOUT:
567 fds->events = POLLOUT;
571 parse_err = "invalid request";
572 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
573 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
575 goodbye(fds, client);
579 LOGI(client, "GET %s%s%s",
580 *uri.path ? uri.path : "/",
581 *uri.query ? "?" : "",
582 *uri.query ? uri.query : "");
584 send_file(uri.path, uri.query, fds, client);
588 if (!start_reply(fds, client, client->code, client->meta))
591 if (client->code != SUCCESS) {
592 /* we don't need a body */
593 goodbye(fds, client);
597 client->state = S_SENDING;
602 if (client->child != -1)
603 handle_cgi(fds, client);
605 send_file(NULL, NULL, fds, client);
609 goodbye(fds, client);
619 mark_nonblock(int fd)
623 if ((flags = fcntl(fd, F_GETFL)) == -1)
624 fatal("fcntl(F_GETFL): %s", strerror(errno));
625 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
626 fatal("fcntl(F_SETFL): %s", strerror(errno));
630 make_socket(int port, int family)
633 struct sockaddr_in addr4;
634 struct sockaddr_in6 addr6;
635 struct sockaddr *addr;
640 bzero(&addr4, sizeof(addr4));
641 addr4.sin_family = family;
642 addr4.sin_port = htons(port);
643 addr4.sin_addr.s_addr = INADDR_ANY;
644 addr = (struct sockaddr*)&addr4;
649 bzero(&addr6, sizeof(addr6));
650 addr6.sin6_family = AF_INET6;
651 addr6.sin6_port = htons(port);
652 addr6.sin6_addr = in6addr_any;
653 addr = (struct sockaddr*)&addr6;
662 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
663 fatal("socket: %s", strerror(errno));
666 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
667 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
670 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
671 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
675 if (bind(sock, addr, len) == -1)
676 fatal("bind: %s", strerror(errno));
678 if (listen(sock, 16) == -1)
679 fatal("listen: %s", strerror(errno));
685 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
688 struct sockaddr_in addr;
692 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
693 if (errno == EWOULDBLOCK)
695 fatal("accept: %s", strerror(errno));
700 for (i = 0; i < MAX_USERS; ++i) {
701 if (fds[i].fd == -1) {
702 bzero(&clients[i], sizeof(struct client));
703 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
704 break; /* goodbye fd! */
707 fds[i].events = POLLIN;
709 clients[i].state = S_OPEN;
711 clients[i].child = -1;
712 clients[i].buf = MAP_FAILED;
713 clients[i].af = AF_INET;
714 clients[i].addr = addr.sin_addr;
725 goodbye(struct pollfd *pfd, struct client *c)
729 c->state = S_CLOSING;
731 ret = tls_close(c->ctx);
732 if (ret == TLS_WANT_POLLIN) {
733 pfd->events = POLLIN;
736 if (ret == TLS_WANT_POLLOUT) {
737 pfd->events = POLLOUT;
746 if (c->buf != MAP_FAILED)
747 munmap(c->buf, c->len);
757 loop(struct tls *ctx, int sock)
760 struct client clients[MAX_USERS];
761 struct pollfd fds[MAX_USERS];
763 for (i = 0; i < MAX_USERS; ++i) {
765 fds[i].events = POLLIN;
766 bzero(&clients[i], sizeof(struct client));
772 if (poll(fds, MAX_USERS, INFTIM) == -1) {
773 if (errno == EINTR) {
774 warnx("connected clients: %d",
778 fatal("poll: %s", strerror(errno));
781 for (i = 0; i < MAX_USERS; i++) {
782 if (fds[i].revents == 0)
785 if (fds[i].revents & (POLLERR|POLLNVAL))
786 fatal("bad fd %d: %s", fds[i].fd,
789 if (fds[i].revents & POLLHUP) {
790 /* fds[i] may be the fd of the stdin
791 * of a cgi script that has exited. */
792 if (!clients[i].waiting_on_child) {
793 goodbye(&fds[i], &clients[i]);
798 if (i == 0) { /* new client */
799 do_accept(sock, ctx, fds, clients);
803 handle(&fds[i], &clients[i]);
809 absolutify_path(const char *path)
817 if (asprintf(&r, "%s/%s", wd, path) == -1)
824 usage(const char *me)
827 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
828 "[-l logfile] [-p port] [-x cgi-bin]\n",
833 main(int argc, char **argv)
835 const char *cert = "cert.pem", *key = "key.pem";
836 struct tls *ctx = NULL;
837 struct tls_config *conf;
839 connected_clients = 0;
841 if ((dir = absolutify_path("docs")) == NULL)
842 err(1, "absolutify_path");
848 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
856 if ((dir = absolutify_path(optarg)) == NULL)
857 err(1, "absolutify_path");
877 lval = strtol(optarg, &ep, 10);
878 if (optarg[0] == '\0' || *ep != '\0')
879 err(1, "not a number: %s", optarg);
880 if (lval < 0 || lval > UINT16_MAX)
881 err(1, "port number out of range: %s", optarg);
896 signal(SIGPIPE, SIG_IGN);
897 signal(SIGCHLD, SIG_IGN);
900 signal(SIGINFO, sig_handler);
902 signal(SIGUSR2, sig_handler);
905 signal(SIGHUP, SIG_IGN);
907 if ((conf = tls_config_new()) == NULL)
908 err(1, "tls_config_new");
910 /* optionally accept client certs, but don't try to verify them */
911 tls_config_verify_client_optional(conf);
912 tls_config_insecure_noverifycert(conf);
914 if (tls_config_set_protocols(conf,
915 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
916 err(1, "tls_config_set_protocols");
918 if (tls_config_set_cert_file(conf, cert) == -1)
919 err(1, "tls_config_set_cert_file: %s", cert);
921 if (tls_config_set_key_file(conf, key) == -1)
922 err(1, "tls_config_set_key_file: %s", key);
924 if ((ctx = tls_server()) == NULL)
925 err(1, "tls_server");
927 if (tls_configure(ctx, conf) == -1)
928 errx(1, "tls_configure: %s", tls_error(ctx));
930 sock = make_socket(port, AF_INET);
932 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
933 err(1, "open: %s", dir);
935 if (!foreground && daemon(0, 1) == -1)
938 if (unveil(dir, "rx") == -1)
941 if (pledge("stdio rpath inet proc exec", NULL) == -1)
944 /* drop proc and exec if cgi isn't enabled */
945 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
952 tls_config_free(conf);