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 struct vhost hosts[HOSTSLEN];
34 int connected_clients;
39 struct etm { /* file extension to mime */
43 {"application/pdf", "pdf"},
46 {"image/jpeg", "jpg"},
47 {"image/jpeg", "jpeg"},
49 {"image/svg+xml", "svg"},
51 {"text/gemini", "gemini"},
52 {"text/gemini", "gmi"},
53 {"text/markdown", "markdown"},
54 {"text/markdown", "md"},
55 {"text/plain", "txt"},
62 safe_setenv(const char *name, const char *val)
69 __attribute__ ((format (printf, 1, 2)))
70 __attribute__ ((__noreturn__))
72 fatal(const char *fmt, ...)
78 if (conf.foreground) {
79 vfprintf(stderr, fmt, ap);
80 fprintf(stderr, "\n");
82 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
89 logs(int priority, struct client *c,
92 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
101 strncpy(hbuf, "<internal>", sizeof(hbuf));
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));
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(c->host->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 (c->host->cgi != NULL && starts_with(fpath, c->host->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 (c->host->cgi != NULL && starts_with(fpath, c->host->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", conf.port) == -1)
372 if (asprintf(&ex, "%s/%s", c->host->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", c->host->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_handshake(struct pollfd *fds, struct client *c)
575 const char *servname;
577 switch (tls_handshake(c->ctx)) {
578 case 0: /* success */
579 case -1: /* already handshaked */
581 case TLS_WANT_POLLIN:
582 fds->events = POLLIN;
584 case TLS_WANT_POLLOUT:
585 fds->events = POLLOUT;
592 servname = tls_conn_servername(c->ctx);
593 if (servname == NULL)
596 for (h = hosts; h->domain != NULL; ++h) {
597 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
601 if (h->domain != NULL) {
604 handle_open_conn(fds, c);
609 /* XXX: check the correct response */
610 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
616 handle_open_conn(struct pollfd *fds, struct client *c)
618 char buf[GEMINI_URL_LEN];
619 const char *parse_err = "invalid request";
622 bzero(buf, sizeof(buf));
624 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
626 LOGE(c, "tls_read: %s", tls_error(c->ctx));
630 case TLS_WANT_POLLIN:
631 fds->events = POLLIN;
634 case TLS_WANT_POLLOUT:
635 fds->events = POLLOUT;
639 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
640 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
646 if (strcmp(iri.schema, "gemini")) {
647 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
653 LOGI(c, "GET %s%s%s",
654 *iri.path ? iri.path : "/",
655 *iri.query ? "?" : "",
656 *iri.query ? iri.query : "");
658 send_file(iri.path, iri.query, fds, c);
662 handle(struct pollfd *fds, struct client *client)
664 switch (client->state) {
666 handle_handshake(fds, client);
670 handle_open_conn(fds, client);
674 if (!start_reply(fds, client, client->code, client->meta))
677 if (client->code != SUCCESS) {
678 /* we don't need a body */
679 goodbye(fds, client);
683 client->state = S_SENDING;
688 if (client->child != -1)
689 handle_cgi(fds, client);
691 send_file(NULL, NULL, fds, client);
695 goodbye(fds, client);
705 mark_nonblock(int fd)
709 if ((flags = fcntl(fd, F_GETFL)) == -1)
710 fatal("fcntl(F_GETFL): %s", strerror(errno));
711 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
712 fatal("fcntl(F_SETFL): %s", strerror(errno));
716 make_socket(int port, int family)
719 struct sockaddr_in addr4;
720 struct sockaddr_in6 addr6;
721 struct sockaddr *addr;
726 bzero(&addr4, sizeof(addr4));
727 addr4.sin_family = family;
728 addr4.sin_port = htons(port);
729 addr4.sin_addr.s_addr = INADDR_ANY;
730 addr = (struct sockaddr*)&addr4;
735 bzero(&addr6, sizeof(addr6));
736 addr6.sin6_family = AF_INET6;
737 addr6.sin6_port = htons(port);
738 addr6.sin6_addr = in6addr_any;
739 addr = (struct sockaddr*)&addr6;
748 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
749 fatal("socket: %s", strerror(errno));
752 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
753 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
756 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
757 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
761 if (bind(sock, addr, len) == -1)
762 fatal("bind: %s", strerror(errno));
764 if (listen(sock, 16) == -1)
765 fatal("listen: %s", strerror(errno));
771 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
774 struct sockaddr_storage addr;
778 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
779 if (errno == EWOULDBLOCK)
781 fatal("accept: %s", strerror(errno));
786 for (i = 0; i < MAX_USERS; ++i) {
787 if (fds[i].fd == -1) {
788 bzero(&clients[i], sizeof(struct client));
789 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
790 break; /* goodbye fd! */
793 fds[i].events = POLLIN;
795 clients[i].state = S_HANDSHAKE;
797 clients[i].child = -1;
798 clients[i].buf = MAP_FAILED;
799 clients[i].af = AF_INET;
800 clients[i].addr = addr;
811 goodbye(struct pollfd *pfd, struct client *c)
815 c->state = S_CLOSING;
817 ret = tls_close(c->ctx);
818 if (ret == TLS_WANT_POLLIN) {
819 pfd->events = POLLIN;
822 if (ret == TLS_WANT_POLLOUT) {
823 pfd->events = POLLOUT;
832 if (c->buf != MAP_FAILED)
833 munmap(c->buf, c->len);
843 loop(struct tls *ctx, int sock4, int sock6)
846 struct client clients[MAX_USERS];
847 struct pollfd fds[MAX_USERS];
849 for (i = 0; i < MAX_USERS; ++i) {
851 fds[i].events = POLLIN;
852 bzero(&clients[i], sizeof(struct client));
859 if (poll(fds, MAX_USERS, INFTIM) == -1) {
860 if (errno == EINTR) {
861 warnx("connected clients: %d",
865 fatal("poll: %s", strerror(errno));
868 for (i = 0; i < MAX_USERS; i++) {
869 if (fds[i].revents == 0)
872 if (fds[i].revents & (POLLERR|POLLNVAL))
873 fatal("bad fd %d: %s", fds[i].fd,
876 if (fds[i].revents & POLLHUP) {
877 /* fds[i] may be the fd of the stdin
878 * of a cgi script that has exited. */
879 if (!clients[i].waiting_on_child) {
880 goodbye(&fds[i], &clients[i]);
885 if (fds[i].fd == sock4)
886 do_accept(sock4, ctx, fds, clients);
887 else if (fds[i].fd == sock6)
888 do_accept(sock6, ctx, fds, clients);
890 handle(&fds[i], &clients[i]);
896 absolutify_path(const char *path)
904 if (asprintf(&r, "%s/%s", wd, path) == -1)
911 yyerror(const char *msg)
914 fprintf(stderr, "%d: %s\n", yylineno, msg);
918 parse_portno(const char *p)
924 lval = strtol(p, &ep, 10);
925 if (p[0] == '\0' || *ep != '\0')
926 errx(1, "not a number: %s", p);
927 if (lval < 0 || lval > UINT16_MAX)
928 errx(1, "port number out of range for domain %s: %ld", p, lval);
933 parse_conf(const char *path)
935 if ((yyin = fopen(path, "r")) == NULL)
936 err(1, "cannot open config %s", path);
945 load_vhosts(struct tls_config *tlsconf)
949 /* we need to set something, then we can add how many key we want */
950 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
951 errx(1, "tls_config_set_keypair_file failed");
953 for (h = hosts; h->domain != NULL; ++h) {
954 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
955 errx(1, "failed to load the keypair (%s, %s)",
958 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
959 err(1, "open %s for domain %s", h->dir, h->domain);
964 usage(const char *me)
967 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
968 "[-p port] [-x cgi-bin]\n",
973 main(int argc, char **argv)
975 struct tls *ctx = NULL;
976 struct tls_config *tlsconf;
977 int sock4, sock6, ch;
978 const char *config_path = NULL;
982 bzero(hosts, sizeof(hosts));
983 for (i = 0; i < HOSTSLEN; ++i)
990 connected_clients = 0;
992 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
999 hosts[0].cert = optarg;
1003 config_path = optarg;
1007 free((char*)hosts[0].dir);
1008 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
1009 err(1, "absolutify_path");
1013 conf.foreground = 1;
1021 hosts[0].key = optarg;
1029 conf.port = parse_portno(optarg);
1032 /* drop the starting / (if any) */
1035 hosts[0].cgi = optarg;
1044 if (config_path != NULL) {
1045 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
1046 hosts[0].dir != NULL)
1047 errx(1, "can't specify options in conf mode");
1048 parse_conf(config_path);
1050 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
1051 hosts[0].dir == NULL)
1052 errx(1, "missing cert, key or root directory to serve");
1053 hosts[0].domain = "*";
1057 errx(0, "config OK");
1059 signal(SIGPIPE, SIG_IGN);
1060 signal(SIGCHLD, SIG_IGN);
1063 signal(SIGINFO, sig_handler);
1065 signal(SIGUSR2, sig_handler);
1067 if (!conf.foreground)
1068 signal(SIGHUP, SIG_IGN);
1070 if ((tlsconf = tls_config_new()) == NULL)
1071 err(1, "tls_config_new");
1073 /* optionally accept client certs, but don't try to verify them */
1074 tls_config_verify_client_optional(tlsconf);
1075 tls_config_insecure_noverifycert(tlsconf);
1077 if (tls_config_set_protocols(tlsconf,
1078 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1079 err(1, "tls_config_set_protocols");
1081 load_vhosts(tlsconf);
1083 if ((ctx = tls_server()) == NULL)
1084 err(1, "tls_server");
1086 if (tls_configure(ctx, tlsconf) == -1)
1087 errx(1, "tls_configure: %s", tls_error(ctx));
1089 sock4 = make_socket(conf.port, AF_INET);
1091 sock6 = make_socket(conf.port, AF_INET6);
1096 if (!conf.foreground && daemon(0, 1) == -1)
1101 loop(ctx, sock4, sock6);
1106 tls_config_free(tlsconf);