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]; /* status + ' ' + max reply len + \r\n\0 */
154 client->meta = reason;
155 client->state = S_INITIALIZING;
157 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
158 assert(len < (int)sizeof(buf));
160 switch (tls_write(client->ctx, buf, len)) {
161 case TLS_WANT_POLLIN:
162 pfd->events = POLLIN;
164 case TLS_WANT_POLLOUT:
165 pfd->events = POLLOUT;
177 if ((len = lseek(fd, 0, SEEK_END)) == -1)
179 if (lseek(fd, 0, SEEK_SET) == -1)
185 path_ext(const char *path)
189 end = path + strlen(path)-1;
190 for (; end != path; --end) {
201 mime(const char *path)
203 const char *ext, *def = "application/octet-stream";
206 if ((ext = path_ext(path)) == NULL)
209 for (t = filetypes; t->mime != NULL; ++t)
210 if (!strcmp(ext, t->ext))
217 check_path(struct client *c, const char *path, int *fd)
221 assert(path != NULL);
222 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
223 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
227 if (fstat(*fd, &sb) == -1) {
228 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
232 if (S_ISDIR(sb.st_mode))
233 return FILE_DIRECTORY;
235 if (sb.st_mode & S_IXUSR)
236 return FILE_EXECUTABLE;
242 * the inverse of this algorithm, i.e. starting from the start of the
243 * path + strlen(cgi), and checking if each component, should be
244 * faster. But it's tedious to write. This does the opposite: starts
245 * from the end and strip one component at a time, until either an
246 * executable is found or we emptied the path.
249 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
252 end = strchr(path, '\0');
254 /* NB: assume CGI is enabled and path matches cgi */
257 /* go up one level. UNIX paths are simple and POSIX
258 * dirname, with its ambiguities on if the given path
259 * is changed or not, gives me headaches. */
264 switch (check_path(c, path, &c->fd)) {
265 case FILE_EXECUTABLE:
266 return start_cgi(path, end+1, query, fds,c);
278 if (!start_reply(fds, c, NOT_FOUND, "not found"))
285 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
287 switch (check_path(c, fpath, &c->fd)) {
288 case FILE_EXECUTABLE:
289 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
290 return start_cgi(fpath, "", query, fds, c);
295 if ((c->len = filesize(c->fd)) == -1) {
296 LOGE(c, "failed to get file size for %s", fpath);
301 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
302 c->fd, 0)) == MAP_FAILED) {
303 warn("mmap: %s", fpath);
308 return start_reply(fds, c, SUCCESS, mime(fpath));
311 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
314 send_dir(fpath, fds, c);
318 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
319 return check_for_cgi(fpath, query, fds, c);
321 if (!start_reply(fds, c, NOT_FOUND, "not found"))
333 start_cgi(const char *spath, const char *relpath, const char *query,
334 struct pollfd *fds, struct client *c)
337 int p[2]; /* read end, write end */
342 switch (pid = fork()) {
346 case 0: { /* child */
347 char *ex, *requri, *portno;
348 char addr[NI_MAXHOST];
349 char *argv[] = { NULL, NULL, NULL };
353 if (dup2(p[1], 1) == -1)
356 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
359 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
362 NI_NUMERICHOST | NI_NUMERICSERV);
366 if (asprintf(&portno, "%d", conf.port) == -1)
369 if (asprintf(&ex, "%s/%s", c->host->dir, spath) == -1)
372 if (asprintf(&requri, "%s%s%s", spath,
373 *relpath == '\0' ? "" : "/", relpath) == -1)
376 argv[0] = argv[1] = ex;
379 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
380 safe_setenv("SERVER_SOFTWARE", "gmid");
381 safe_setenv("SERVER_PORT", portno);
382 /* setenv("SERVER_NAME", "", 1); */
383 safe_setenv("SCRIPT_NAME", spath);
384 safe_setenv("SCRIPT_EXECUTABLE", ex);
385 safe_setenv("REQUEST_URI", requri);
386 safe_setenv("REQUEST_RELATIVE", relpath);
387 safe_setenv("QUERY_STRING", query);
388 safe_setenv("REMOTE_HOST", addr);
389 safe_setenv("REMOTE_ADDR", addr);
390 safe_setenv("DOCUMENT_ROOT", c->host->dir);
392 if (tls_peer_cert_provided(c->ctx)) {
393 safe_setenv("AUTH_TYPE", "Certificate");
394 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
395 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
396 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
403 default: /* parent */
408 mark_nonblock(c->fd);
409 c->state = S_SENDING;
415 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
421 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
427 cgi_poll_on_child(struct pollfd *fds, struct client *c)
431 if (c->waiting_on_child)
433 c->waiting_on_child = 1;
435 fds->events = POLLIN;
443 cgi_poll_on_client(struct pollfd *fds, struct client *c)
447 if (!c->waiting_on_child)
449 c->waiting_on_child = 0;
457 handle_cgi(struct pollfd *fds, struct client *c)
461 /* ensure c->fd is the child and fds->fd the client */
462 cgi_poll_on_client(fds, c);
466 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
469 if (errno == EAGAIN || errno == EWOULDBLOCK) {
470 cgi_poll_on_child(fds, c);
480 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
484 case TLS_WANT_POLLOUT:
485 fds->events = POLLOUT;
488 case TLS_WANT_POLLIN:
489 fds->events = POLLIN;
505 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
510 if (!open_file(path, query, fds, c))
512 c->state = S_SENDING;
515 len = (c->buf + c->len) - c->i;
518 switch (ret = tls_write(c->ctx, c->i, len)) {
520 LOGE(c, "tls_write: %s", tls_error(c->ctx));
524 case TLS_WANT_POLLIN:
525 fds->events = POLLIN;
528 case TLS_WANT_POLLOUT:
529 fds->events = POLLOUT;
543 send_dir(char *path, struct pollfd *fds, struct client *client)
548 bzero(fpath, PATHBUF);
553 /* this cannot fail since sizeof(fpath) > maxlen of path */
554 strlcat(fpath, path, PATHBUF);
557 /* add a trailing / in case. */
558 if (fpath[len-1] != '/') {
562 strlcat(fpath, "index.gmi", sizeof(fpath));
564 send_file(fpath, NULL, fds, client);
568 handle_handshake(struct pollfd *fds, struct client *c)
571 const char *servname;
573 switch (tls_handshake(c->ctx)) {
574 case 0: /* success */
575 case -1: /* already handshaked */
577 case TLS_WANT_POLLIN:
578 fds->events = POLLIN;
580 case TLS_WANT_POLLOUT:
581 fds->events = POLLOUT;
588 servname = tls_conn_servername(c->ctx);
589 if (servname == NULL)
592 for (h = hosts; h->domain != NULL; ++h) {
593 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
597 if (h->domain != NULL) {
600 handle_open_conn(fds, c);
605 /* XXX: check the correct response */
606 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
612 handle_open_conn(struct pollfd *fds, struct client *c)
614 char buf[GEMINI_URL_LEN];
615 const char *parse_err = "invalid request";
618 bzero(buf, sizeof(buf));
620 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
622 LOGE(c, "tls_read: %s", tls_error(c->ctx));
626 case TLS_WANT_POLLIN:
627 fds->events = POLLIN;
630 case TLS_WANT_POLLOUT:
631 fds->events = POLLOUT;
635 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
636 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
642 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
643 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
649 LOGI(c, "GET %s%s%s",
650 *iri.path ? iri.path : "/",
651 *iri.query ? "?" : "",
652 *iri.query ? iri.query : "");
654 send_file(iri.path, iri.query, fds, c);
658 handle(struct pollfd *fds, struct client *client)
660 switch (client->state) {
662 handle_handshake(fds, client);
666 handle_open_conn(fds, client);
670 if (!start_reply(fds, client, client->code, client->meta))
673 if (client->code != SUCCESS) {
674 /* we don't need a body */
675 goodbye(fds, client);
679 client->state = S_SENDING;
684 if (client->child != -1)
685 handle_cgi(fds, client);
687 send_file(NULL, NULL, fds, client);
691 goodbye(fds, client);
701 mark_nonblock(int fd)
705 if ((flags = fcntl(fd, F_GETFL)) == -1)
706 fatal("fcntl(F_GETFL): %s", strerror(errno));
707 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
708 fatal("fcntl(F_SETFL): %s", strerror(errno));
712 make_socket(int port, int family)
715 struct sockaddr_in addr4;
716 struct sockaddr_in6 addr6;
717 struct sockaddr *addr;
722 bzero(&addr4, sizeof(addr4));
723 addr4.sin_family = family;
724 addr4.sin_port = htons(port);
725 addr4.sin_addr.s_addr = INADDR_ANY;
726 addr = (struct sockaddr*)&addr4;
731 bzero(&addr6, sizeof(addr6));
732 addr6.sin6_family = AF_INET6;
733 addr6.sin6_port = htons(port);
734 addr6.sin6_addr = in6addr_any;
735 addr = (struct sockaddr*)&addr6;
744 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
745 fatal("socket: %s", strerror(errno));
748 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
749 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
752 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
753 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
757 if (bind(sock, addr, len) == -1)
758 fatal("bind: %s", strerror(errno));
760 if (listen(sock, 16) == -1)
761 fatal("listen: %s", strerror(errno));
767 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
770 struct sockaddr_storage addr;
774 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
775 if (errno == EWOULDBLOCK)
777 fatal("accept: %s", strerror(errno));
782 for (i = 0; i < MAX_USERS; ++i) {
783 if (fds[i].fd == -1) {
784 bzero(&clients[i], sizeof(struct client));
785 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
786 break; /* goodbye fd! */
789 fds[i].events = POLLIN;
791 clients[i].state = S_HANDSHAKE;
793 clients[i].child = -1;
794 clients[i].buf = MAP_FAILED;
795 clients[i].af = AF_INET;
796 clients[i].addr = addr;
807 goodbye(struct pollfd *pfd, struct client *c)
809 c->state = S_CLOSING;
811 switch (tls_close(c->ctx)) {
812 case TLS_WANT_POLLIN:
813 pfd->events = POLLIN;
815 case TLS_WANT_POLLOUT:
816 pfd->events = POLLOUT;
825 if (c->buf != MAP_FAILED)
826 munmap(c->buf, c->len);
836 loop(struct tls *ctx, int sock4, int sock6)
839 struct client clients[MAX_USERS];
840 struct pollfd fds[MAX_USERS];
842 for (i = 0; i < MAX_USERS; ++i) {
844 fds[i].events = POLLIN;
845 bzero(&clients[i], sizeof(struct client));
852 if (poll(fds, MAX_USERS, INFTIM) == -1) {
853 if (errno == EINTR) {
854 warnx("connected clients: %d",
858 fatal("poll: %s", strerror(errno));
861 for (i = 0; i < MAX_USERS; i++) {
862 if (fds[i].revents == 0)
865 if (fds[i].revents & (POLLERR|POLLNVAL))
866 fatal("bad fd %d: %s", fds[i].fd,
869 if (fds[i].revents & POLLHUP) {
870 /* fds[i] may be the fd of the stdin
871 * of a cgi script that has exited. */
872 if (!clients[i].waiting_on_child) {
873 goodbye(&fds[i], &clients[i]);
878 if (fds[i].fd == sock4)
879 do_accept(sock4, ctx, fds, clients);
880 else if (fds[i].fd == sock6)
881 do_accept(sock6, ctx, fds, clients);
883 handle(&fds[i], &clients[i]);
889 absolutify_path(const char *path)
897 if (asprintf(&r, "%s/%s", wd, path) == -1)
904 yyerror(const char *msg)
907 fprintf(stderr, "%d: %s\n", yylineno, msg);
911 parse_portno(const char *p)
917 lval = strtol(p, &ep, 10);
918 if (p[0] == '\0' || *ep != '\0')
919 errx(1, "not a number: %s", p);
920 if (lval < 0 || lval > UINT16_MAX)
921 errx(1, "port number out of range for domain %s: %ld", p, lval);
926 parse_conf(const char *path)
928 if ((yyin = fopen(path, "r")) == NULL)
929 err(1, "cannot open config %s", path);
938 load_vhosts(struct tls_config *tlsconf)
942 /* we need to set something, then we can add how many key we want */
943 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
944 errx(1, "tls_config_set_keypair_file failed");
946 for (h = hosts; h->domain != NULL; ++h) {
947 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
948 errx(1, "failed to load the keypair (%s, %s)",
951 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
952 err(1, "open %s for domain %s", h->dir, h->domain);
957 usage(const char *me)
960 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
961 "[-p port] [-x cgi-bin]\n",
966 main(int argc, char **argv)
968 struct tls *ctx = NULL;
969 struct tls_config *tlsconf;
970 int sock4, sock6, ch;
971 const char *config_path = NULL;
975 bzero(hosts, sizeof(hosts));
976 for (i = 0; i < HOSTSLEN; ++i)
983 connected_clients = 0;
985 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
992 hosts[0].cert = optarg;
996 config_path = optarg;
1000 free((char*)hosts[0].dir);
1001 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
1002 err(1, "absolutify_path");
1006 conf.foreground = 1;
1014 hosts[0].key = optarg;
1022 conf.port = parse_portno(optarg);
1025 /* drop the starting / (if any) */
1028 hosts[0].cgi = optarg;
1037 if (config_path != NULL) {
1038 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
1039 hosts[0].dir != NULL)
1040 errx(1, "can't specify options in conf mode");
1041 parse_conf(config_path);
1043 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
1044 hosts[0].dir == NULL)
1045 errx(1, "missing cert, key or root directory to serve");
1046 hosts[0].domain = "*";
1050 errx(0, "config OK");
1052 signal(SIGPIPE, SIG_IGN);
1053 signal(SIGCHLD, SIG_IGN);
1056 signal(SIGINFO, sig_handler);
1058 signal(SIGUSR2, sig_handler);
1060 if (!conf.foreground)
1061 signal(SIGHUP, SIG_IGN);
1063 if ((tlsconf = tls_config_new()) == NULL)
1064 err(1, "tls_config_new");
1066 /* optionally accept client certs, but don't try to verify them */
1067 tls_config_verify_client_optional(tlsconf);
1068 tls_config_insecure_noverifycert(tlsconf);
1070 if (tls_config_set_protocols(tlsconf,
1071 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1072 err(1, "tls_config_set_protocols");
1074 load_vhosts(tlsconf);
1076 if ((ctx = tls_server()) == NULL)
1077 err(1, "tls_server");
1079 if (tls_configure(ctx, tlsconf) == -1)
1080 errx(1, "tls_configure: %s", tls_error(ctx));
1082 sock4 = make_socket(conf.port, AF_INET);
1084 sock6 = make_socket(conf.port, AF_INET6);
1088 if (!conf.foreground && daemon(0, 1) == -1)
1093 loop(ctx, sock4, sock6);
1098 tls_config_free(tlsconf);