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 struct vhost hosts[HOSTSLEN];
39 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 __attribute__ ((__noreturn__))
77 fatal(const char *fmt, ...)
83 if (conf.foreground) {
84 vfprintf(stderr, fmt, ap);
85 fprintf(stderr, "\n");
87 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
93 __attribute__ ((format (printf, 3, 4)))
95 logs(int priority, struct client *c,
98 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
106 len = sizeof(c->addr);
107 ec = getnameinfo((struct sockaddr*)&c->addr, len,
110 NI_NUMERICHOST | NI_NUMERICSERV);
112 fatal("getnameinfo: %s", gai_strerror(ec));
114 if (vasprintf(&fmted, fmt, ap) == -1)
115 fatal("vasprintf: %s", strerror(errno));
118 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
120 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
121 fatal("asprintf: %s", strerror(errno));
122 syslog(priority | LOG_DAEMON, "%s", s);
138 starts_with(const char *str, const char *prefix)
142 for (i = 0; prefix[i] != '\0'; ++i)
143 if (str[i] != prefix[i])
149 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
151 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
156 client->meta = reason;
157 client->state = S_INITIALIZING;
159 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
160 assert(len < (int)sizeof(buf));
161 ret = tls_write(client->ctx, buf, len);
162 if (ret == TLS_WANT_POLLIN) {
163 pfd->events = POLLIN;
167 if (ret == TLS_WANT_POLLOUT) {
168 pfd->events = POLLOUT;
180 if ((len = lseek(fd, 0, SEEK_END)) == -1)
182 if (lseek(fd, 0, SEEK_SET) == -1)
188 path_ext(const char *path)
192 end = path + strlen(path)-1; /* the last byte before the NUL */
193 for (; end != path; --end) {
204 mime(const char *path)
206 const char *ext, *def = "application/octet-stream";
209 if ((ext = path_ext(path)) == NULL)
212 for (t = filetypes; t->mime != NULL; ++t)
213 if (!strcmp(ext, t->ext))
220 check_path(struct client *c, const char *path, int *fd)
224 assert(path != NULL);
225 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
226 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
230 if (fstat(*fd, &sb) == -1) {
231 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
235 if (S_ISDIR(sb.st_mode))
236 return FILE_DIRECTORY;
238 if (sb.st_mode & S_IXUSR)
239 return FILE_EXECUTABLE;
245 * the inverse of this algorithm, i.e. starting from the start of the
246 * path + strlen(cgi), and checking if each component, should be
247 * faster. But it's tedious to write. This does the opposite: starts
248 * from the end and strip one component at a time, until either an
249 * executable is found or we emptied the path.
252 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
255 end = strchr(path, '\0');
257 /* NB: assume CGI is enabled and path matches cgi */
260 /* go up one level. UNIX paths are simple and POSIX
261 * dirname, with its ambiguities on if the given path
262 * is changed or not, gives me headaches. */
267 switch (check_path(c, path, &c->fd)) {
268 case FILE_EXECUTABLE:
269 return start_cgi(path, end+1, query, fds,c);
281 if (!start_reply(fds, c, NOT_FOUND, "not found"))
289 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
291 switch (check_path(c, fpath, &c->fd)) {
292 case FILE_EXECUTABLE:
293 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
294 return start_cgi(fpath, "", query, fds, c);
299 if ((c->len = filesize(c->fd)) == -1) {
300 LOGE(c, "failed to get file size for %s", fpath);
305 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
306 c->fd, 0)) == MAP_FAILED) {
307 warn("mmap: %s", fpath);
312 return start_reply(fds, c, SUCCESS, mime(fpath));
315 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
318 send_dir(fpath, fds, c);
322 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
323 return check_for_cgi(fpath, query, fds, c);
325 if (!start_reply(fds, c, NOT_FOUND, "not found"))
337 start_cgi(const char *spath, const char *relpath, const char *query,
338 struct pollfd *fds, struct client *c)
341 int p[2]; /* read end, write end */
346 switch (pid = fork()) {
350 case 0: { /* child */
351 char *ex, *requri, *portno;
352 char addr[NI_MAXHOST];
353 char *argv[] = { NULL, NULL, NULL };
357 if (dup2(p[1], 1) == -1)
360 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
363 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
366 NI_NUMERICHOST | NI_NUMERICSERV);
370 if (asprintf(&portno, "%d", conf.port) == -1)
373 if (asprintf(&ex, "%s/%s", c->host->dir, spath) == -1)
376 if (asprintf(&requri, "%s%s%s", spath,
377 *relpath == '\0' ? "" : "/",
381 argv[0] = argv[1] = ex;
384 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
385 safe_setenv("SERVER_SOFTWARE", "gmid");
386 safe_setenv("SERVER_PORT", portno);
387 /* setenv("SERVER_NAME", "", 1); */
388 safe_setenv("SCRIPT_NAME", spath);
389 safe_setenv("SCRIPT_EXECUTABLE", ex);
390 safe_setenv("REQUEST_URI", requri);
391 safe_setenv("REQUEST_RELATIVE", relpath);
392 safe_setenv("QUERY_STRING", query);
393 safe_setenv("REMOTE_HOST", addr);
394 safe_setenv("REMOTE_ADDR", addr);
395 safe_setenv("DOCUMENT_ROOT", c->host->dir);
397 if (tls_peer_cert_provided(c->ctx)) {
398 safe_setenv("AUTH_TYPE", "Certificate");
399 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
400 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
401 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
408 default: /* parent */
413 mark_nonblock(c->fd);
414 c->state = S_SENDING;
420 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
426 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
432 cgi_poll_on_child(struct pollfd *fds, struct client *c)
436 if (c->waiting_on_child)
438 c->waiting_on_child = 1;
440 fds->events = POLLIN;
448 cgi_poll_on_client(struct pollfd *fds, struct client *c)
452 if (!c->waiting_on_child)
454 c->waiting_on_child = 0;
462 handle_cgi(struct pollfd *fds, struct client *c)
466 /* ensure c->fd is the child and fds->fd the client */
467 cgi_poll_on_client(fds, c);
471 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
474 if (errno == EAGAIN || errno == EWOULDBLOCK) {
475 cgi_poll_on_child(fds, c);
485 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
489 case TLS_WANT_POLLOUT:
490 fds->events = POLLOUT;
493 case TLS_WANT_POLLIN:
494 fds->events = POLLIN;
510 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
515 if (!open_file(path, query, fds, c))
517 c->state = S_SENDING;
520 len = (c->buf + c->len) - c->i;
523 switch (ret = tls_write(c->ctx, c->i, len)) {
525 LOGE(c, "tls_write: %s", tls_error(c->ctx));
529 case TLS_WANT_POLLIN:
530 fds->events = POLLIN;
533 case TLS_WANT_POLLOUT:
534 fds->events = POLLOUT;
548 send_dir(char *path, struct pollfd *fds, struct client *client)
553 bzero(fpath, PATHBUF);
558 /* this cannot fail since sizeof(fpath) > maxlen of path */
559 strlcat(fpath, path, PATHBUF);
562 /* add a trailing / in case. */
563 if (fpath[len-1] != '/') {
567 strlcat(fpath, "index.gmi", sizeof(fpath));
569 send_file(fpath, NULL, fds, client);
573 handle_handshake(struct pollfd *fds, struct client *c)
576 const char *servname;
578 switch (tls_handshake(c->ctx)) {
579 case 0: /* success */
580 case -1: /* already handshaked */
582 case TLS_WANT_POLLIN:
583 fds->events = POLLIN;
585 case TLS_WANT_POLLOUT:
586 fds->events = POLLOUT;
593 servname = tls_conn_servername(c->ctx);
594 if (servname == NULL)
597 for (h = hosts; h->domain != NULL; ++h) {
598 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
602 if (h->domain != NULL) {
605 handle_open_conn(fds, c);
610 /* XXX: check the correct response */
611 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
617 handle_open_conn(struct pollfd *fds, struct client *c)
619 char buf[GEMINI_URL_LEN];
620 const char *parse_err = "invalid request";
623 bzero(buf, sizeof(buf));
625 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
627 LOGE(c, "tls_read: %s", tls_error(c->ctx));
631 case TLS_WANT_POLLIN:
632 fds->events = POLLIN;
635 case TLS_WANT_POLLOUT:
636 fds->events = POLLOUT;
640 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
641 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
647 if (strcmp(iri.schema, "gemini")) {
648 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
654 LOGI(c, "GET %s%s%s",
655 *iri.path ? iri.path : "/",
656 *iri.query ? "?" : "",
657 *iri.query ? iri.query : "");
659 send_file(iri.path, iri.query, fds, c);
663 handle(struct pollfd *fds, struct client *client)
665 switch (client->state) {
667 handle_handshake(fds, client);
671 handle_open_conn(fds, client);
675 if (!start_reply(fds, client, client->code, client->meta))
678 if (client->code != SUCCESS) {
679 /* we don't need a body */
680 goodbye(fds, client);
684 client->state = S_SENDING;
689 if (client->child != -1)
690 handle_cgi(fds, client);
692 send_file(NULL, NULL, fds, client);
696 goodbye(fds, client);
706 mark_nonblock(int fd)
710 if ((flags = fcntl(fd, F_GETFL)) == -1)
711 fatal("fcntl(F_GETFL): %s", strerror(errno));
712 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
713 fatal("fcntl(F_SETFL): %s", strerror(errno));
717 make_socket(int port, int family)
720 struct sockaddr_in addr4;
721 struct sockaddr_in6 addr6;
722 struct sockaddr *addr;
727 bzero(&addr4, sizeof(addr4));
728 addr4.sin_family = family;
729 addr4.sin_port = htons(port);
730 addr4.sin_addr.s_addr = INADDR_ANY;
731 addr = (struct sockaddr*)&addr4;
736 bzero(&addr6, sizeof(addr6));
737 addr6.sin6_family = AF_INET6;
738 addr6.sin6_port = htons(port);
739 addr6.sin6_addr = in6addr_any;
740 addr = (struct sockaddr*)&addr6;
749 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
750 fatal("socket: %s", strerror(errno));
753 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
754 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
757 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
758 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
762 if (bind(sock, addr, len) == -1)
763 fatal("bind: %s", strerror(errno));
765 if (listen(sock, 16) == -1)
766 fatal("listen: %s", strerror(errno));
772 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
775 struct sockaddr_storage addr;
779 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
780 if (errno == EWOULDBLOCK)
782 fatal("accept: %s", strerror(errno));
787 for (i = 0; i < MAX_USERS; ++i) {
788 if (fds[i].fd == -1) {
789 bzero(&clients[i], sizeof(struct client));
790 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
791 break; /* goodbye fd! */
794 fds[i].events = POLLIN;
796 clients[i].state = S_HANDSHAKE;
798 clients[i].child = -1;
799 clients[i].buf = MAP_FAILED;
800 clients[i].af = AF_INET;
801 clients[i].addr = addr;
812 goodbye(struct pollfd *pfd, struct client *c)
816 c->state = S_CLOSING;
818 ret = tls_close(c->ctx);
819 if (ret == TLS_WANT_POLLIN) {
820 pfd->events = POLLIN;
823 if (ret == TLS_WANT_POLLOUT) {
824 pfd->events = POLLOUT;
833 if (c->buf != MAP_FAILED)
834 munmap(c->buf, c->len);
844 loop(struct tls *ctx, int sock4, int sock6)
847 struct client clients[MAX_USERS];
848 struct pollfd fds[MAX_USERS];
850 for (i = 0; i < MAX_USERS; ++i) {
852 fds[i].events = POLLIN;
853 bzero(&clients[i], sizeof(struct client));
860 if (poll(fds, MAX_USERS, INFTIM) == -1) {
861 if (errno == EINTR) {
862 warnx("connected clients: %d",
866 fatal("poll: %s", strerror(errno));
869 for (i = 0; i < MAX_USERS; i++) {
870 if (fds[i].revents == 0)
873 if (fds[i].revents & (POLLERR|POLLNVAL))
874 fatal("bad fd %d: %s", fds[i].fd,
877 if (fds[i].revents & POLLHUP) {
878 /* fds[i] may be the fd of the stdin
879 * of a cgi script that has exited. */
880 if (!clients[i].waiting_on_child) {
881 goodbye(&fds[i], &clients[i]);
886 if (fds[i].fd == sock4)
887 do_accept(sock4, ctx, fds, clients);
888 else if (fds[i].fd == sock6)
889 do_accept(sock6, ctx, fds, clients);
891 handle(&fds[i], &clients[i]);
897 absolutify_path(const char *path)
905 if (asprintf(&r, "%s/%s", wd, path) == -1)
912 yyerror(const char *msg)
915 fprintf(stderr, "%d: %s\n", yylineno, msg);
919 parse_portno(const char *p)
925 lval = strtol(p, &ep, 10);
926 if (p[0] == '\0' || *ep != '\0')
927 errx(1, "not a number: %s", p);
928 if (lval < 0 || lval > UINT16_MAX)
929 errx(1, "port number out of range for domain %s: %ld", p, lval);
934 parse_conf(const char *path)
936 if ((yyin = fopen(path, "r")) == NULL)
937 err(1, "cannot open config %s", path);
946 load_vhosts(struct tls_config *tlsconf)
950 /* we need to set something, then we can add how many key we want */
951 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
952 errx(1, "tls_config_set_keypair_file failed");
954 for (h = hosts; h->domain != NULL; ++h) {
955 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
956 errx(1, "failed to load the keypair (%s, %s)",
959 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
960 err(1, "open %s for domain %s", h->dir, h->domain);
964 /* we can augment this function to handle also capsicum and seccomp eventually */
971 for (h = hosts; h->domain != NULL; ++h) {
972 if (unveil(h->dir, "rx") == -1)
973 err(1, "unveil %s for domain %s", h->dir, h->domain);
979 if (pledge("stdio rpath inet proc exec", NULL) == -1)
982 /* drop proc and exec if cgi isn't enabled */
984 if (pledge("stdio rpath inet", NULL) == -1)
989 usage(const char *me)
992 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
993 "[-p port] [-x cgi-bin]\n",
998 main(int argc, char **argv)
1000 struct tls *ctx = NULL;
1001 struct tls_config *tlsconf;
1002 int sock4, sock6, ch;
1003 const char *config_path = NULL;
1005 int conftest = 0, has_cgi = 0;
1007 bzero(hosts, sizeof(hosts));
1008 for (i = 0; i < HOSTSLEN; ++i)
1009 hosts[i].dirfd = -1;
1011 conf.foreground = 1;
1015 connected_clients = 0;
1017 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
1024 hosts[0].cert = optarg;
1028 config_path = optarg;
1032 free((char*)hosts[0].dir);
1033 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
1034 err(1, "absolutify_path");
1038 conf.foreground = 1;
1046 hosts[0].key = optarg;
1054 conf.port = parse_portno(optarg);
1057 /* drop the starting / (if any) */
1060 hosts[0].cgi = optarg;
1069 if (config_path != NULL) {
1070 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
1071 hosts[0].dir != NULL)
1072 errx(1, "can't specify options in conf mode");
1073 parse_conf(config_path);
1075 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
1076 hosts[0].dir == NULL)
1077 errx(1, "missing cert, key or root directory to serve");
1078 hosts[0].domain = "*";
1082 errx(0, "config OK");
1084 signal(SIGPIPE, SIG_IGN);
1085 signal(SIGCHLD, SIG_IGN);
1088 signal(SIGINFO, sig_handler);
1090 signal(SIGUSR2, sig_handler);
1092 if (!conf.foreground)
1093 signal(SIGHUP, SIG_IGN);
1095 if ((tlsconf = tls_config_new()) == NULL)
1096 err(1, "tls_config_new");
1098 /* optionally accept client certs, but don't try to verify them */
1099 tls_config_verify_client_optional(tlsconf);
1100 tls_config_insecure_noverifycert(tlsconf);
1102 if (tls_config_set_protocols(tlsconf,
1103 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1104 err(1, "tls_config_set_protocols");
1106 load_vhosts(tlsconf);
1108 if ((ctx = tls_server()) == NULL)
1109 err(1, "tls_server");
1111 if (tls_configure(ctx, tlsconf) == -1)
1112 errx(1, "tls_configure: %s", tls_error(ctx));
1114 sock4 = make_socket(conf.port, AF_INET);
1116 sock6 = make_socket(conf.port, AF_INET6);
1121 if (!conf.foreground && daemon(0, 1) == -1)
1126 loop(ctx, sock4, sock6);
1131 tls_config_free(tlsconf);