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;
41 struct etm { /* file extension to mime */
45 {"application/pdf", "pdf"},
48 {"image/jpeg", "jpg"},
49 {"image/jpeg", "jpeg"},
51 {"image/svg+xml", "svg"},
53 {"text/gemini", "gemini"},
54 {"text/gemini", "gmi"},
55 {"text/markdown", "markdown"},
56 {"text/markdown", "md"},
57 {"text/plain", "txt"},
63 __attribute__ ((format (printf, 1, 2)))
64 __attribute__ ((__noreturn__))
66 fatal(const char *fmt, ...)
72 if (conf.foreground) {
73 vfprintf(stderr, fmt, ap);
74 fprintf(stderr, "\n");
76 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
83 logs(int priority, struct client *c,
86 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
95 strncpy(hbuf, "<internal>", sizeof(hbuf));
98 len = sizeof(c->addr);
99 ec = getnameinfo((struct sockaddr*)&c->addr, len,
102 NI_NUMERICHOST | NI_NUMERICSERV);
104 fatal("getnameinfo: %s", gai_strerror(ec));
107 if (vasprintf(&fmted, fmt, ap) == -1)
108 fatal("vasprintf: %s", strerror(errno));
111 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
113 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
114 fatal("asprintf: %s", strerror(errno));
115 syslog(priority | LOG_DAEMON, "%s", s);
131 starts_with(const char *str, const char *prefix)
135 for (i = 0; prefix[i] != '\0'; ++i)
136 if (str[i] != prefix[i])
142 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
144 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
148 client->meta = reason;
149 client->state = S_INITIALIZING;
151 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
152 assert(len < (int)sizeof(buf));
154 switch (tls_write(client->ctx, buf, len)) {
155 case TLS_WANT_POLLIN:
156 pfd->events = POLLIN;
158 case TLS_WANT_POLLOUT:
159 pfd->events = POLLOUT;
171 if ((len = lseek(fd, 0, SEEK_END)) == -1)
173 if (lseek(fd, 0, SEEK_SET) == -1)
179 path_ext(const char *path)
183 end = path + strlen(path)-1;
184 for (; end != path; --end) {
195 mime(const char *path)
197 const char *ext, *def = "application/octet-stream";
200 if ((ext = path_ext(path)) == NULL)
203 for (t = filetypes; t->mime != NULL; ++t)
204 if (!strcmp(ext, t->ext))
211 check_path(struct client *c, const char *path, int *fd)
215 assert(path != NULL);
216 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
217 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
221 if (fstat(*fd, &sb) == -1) {
222 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
226 if (S_ISDIR(sb.st_mode))
227 return FILE_DIRECTORY;
229 if (sb.st_mode & S_IXUSR)
230 return FILE_EXECUTABLE;
236 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
238 switch (check_path(c, fpath, &c->fd)) {
239 case FILE_EXECUTABLE:
240 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
241 return start_cgi(fpath, "", query, fds, c);
246 if ((c->len = filesize(c->fd)) == -1) {
247 LOGE(c, "failed to get file size for %s", fpath);
252 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
253 c->fd, 0)) == MAP_FAILED) {
254 warn("mmap: %s", fpath);
259 return start_reply(fds, c, SUCCESS, mime(fpath));
262 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
265 send_dir(fpath, fds, c);
269 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
270 return check_for_cgi(fpath, query, fds, c);
272 if (!start_reply(fds, c, NOT_FOUND, "not found"))
284 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
289 if (!open_file(path, query, fds, c))
291 c->state = S_SENDING;
294 len = (c->buf + c->len) - c->i;
297 switch (ret = tls_write(c->ctx, c->i, len)) {
299 LOGE(c, "tls_write: %s", tls_error(c->ctx));
303 case TLS_WANT_POLLIN:
304 fds->events = POLLIN;
307 case TLS_WANT_POLLOUT:
308 fds->events = POLLOUT;
322 send_dir(char *path, struct pollfd *fds, struct client *client)
327 bzero(fpath, PATHBUF);
332 /* this cannot fail since sizeof(fpath) > maxlen of path */
333 strlcat(fpath, path, PATHBUF);
336 /* add a trailing / in case. */
337 if (fpath[len-1] != '/') {
341 strlcat(fpath, "index.gmi", sizeof(fpath));
343 send_file(fpath, NULL, fds, client);
347 handle_handshake(struct pollfd *fds, struct client *c)
350 const char *servname;
352 switch (tls_handshake(c->ctx)) {
353 case 0: /* success */
354 case -1: /* already handshaked */
356 case TLS_WANT_POLLIN:
357 fds->events = POLLIN;
359 case TLS_WANT_POLLOUT:
360 fds->events = POLLOUT;
367 servname = tls_conn_servername(c->ctx);
368 if (servname == NULL)
371 for (h = hosts; h->domain != NULL; ++h) {
372 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
376 if (h->domain != NULL) {
379 handle_open_conn(fds, c);
384 /* XXX: check the correct response */
385 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
391 handle_open_conn(struct pollfd *fds, struct client *c)
393 char buf[GEMINI_URL_LEN];
394 const char *parse_err = "invalid request";
397 bzero(buf, sizeof(buf));
399 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
401 LOGE(c, "tls_read: %s", tls_error(c->ctx));
405 case TLS_WANT_POLLIN:
406 fds->events = POLLIN;
409 case TLS_WANT_POLLOUT:
410 fds->events = POLLOUT;
414 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
415 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
421 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
422 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
428 LOGI(c, "GET %s%s%s",
429 *iri.path ? iri.path : "/",
430 *iri.query ? "?" : "",
431 *iri.query ? iri.query : "");
433 send_file(iri.path, iri.query, fds, c);
437 handle(struct pollfd *fds, struct client *client)
439 switch (client->state) {
441 handle_handshake(fds, client);
445 handle_open_conn(fds, client);
449 if (!start_reply(fds, client, client->code, client->meta))
452 if (client->code != SUCCESS) {
453 /* we don't need a body */
454 goodbye(fds, client);
458 client->state = S_SENDING;
464 handle_cgi(fds, client);
466 send_file(NULL, NULL, fds, client);
470 goodbye(fds, client);
480 mark_nonblock(int fd)
484 if ((flags = fcntl(fd, F_GETFL)) == -1)
485 fatal("fcntl(F_GETFL): %s", strerror(errno));
486 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
487 fatal("fcntl(F_SETFL): %s", strerror(errno));
491 make_socket(int port, int family)
494 struct sockaddr_in addr4;
495 struct sockaddr_in6 addr6;
496 struct sockaddr *addr;
501 bzero(&addr4, sizeof(addr4));
502 addr4.sin_family = family;
503 addr4.sin_port = htons(port);
504 addr4.sin_addr.s_addr = INADDR_ANY;
505 addr = (struct sockaddr*)&addr4;
510 bzero(&addr6, sizeof(addr6));
511 addr6.sin6_family = AF_INET6;
512 addr6.sin6_port = htons(port);
513 addr6.sin6_addr = in6addr_any;
514 addr = (struct sockaddr*)&addr6;
523 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
524 fatal("socket: %s", strerror(errno));
527 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
528 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
531 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
532 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
536 if (bind(sock, addr, len) == -1)
537 fatal("bind: %s", strerror(errno));
539 if (listen(sock, 16) == -1)
540 fatal("listen: %s", strerror(errno));
546 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
549 struct sockaddr_storage addr;
553 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
554 if (errno == EWOULDBLOCK)
556 fatal("accept: %s", strerror(errno));
561 for (i = 0; i < MAX_USERS; ++i) {
562 if (fds[i].fd == -1) {
563 bzero(&clients[i], sizeof(struct client));
564 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
565 break; /* goodbye fd! */
568 fds[i].events = POLLIN;
570 clients[i].state = S_HANDSHAKE;
572 clients[i].child = 0;
573 clients[i].waiting_on_child = 0;
574 clients[i].buf = MAP_FAILED;
575 clients[i].af = AF_INET;
576 clients[i].addr = addr;
587 goodbye(struct pollfd *pfd, struct client *c)
589 c->state = S_CLOSING;
591 switch (tls_close(c->ctx)) {
592 case TLS_WANT_POLLIN:
593 pfd->events = POLLIN;
595 case TLS_WANT_POLLOUT:
596 pfd->events = POLLOUT;
605 if (c->buf != MAP_FAILED)
606 munmap(c->buf, c->len);
616 loop(struct tls *ctx, int sock4, int sock6)
619 struct client clients[MAX_USERS];
620 struct pollfd fds[MAX_USERS];
622 for (i = 0; i < MAX_USERS; ++i) {
624 fds[i].events = POLLIN;
625 bzero(&clients[i], sizeof(struct client));
632 if (poll(fds, MAX_USERS, INFTIM) == -1) {
633 if (errno == EINTR) {
634 warnx("connected clients: %d",
638 fatal("poll: %s", strerror(errno));
641 for (i = 0; i < MAX_USERS; i++) {
642 if (fds[i].revents == 0)
645 if (fds[i].revents & (POLLERR|POLLNVAL))
646 fatal("bad fd %d: %s", fds[i].fd,
649 if (fds[i].revents & POLLHUP) {
650 /* fds[i] may be the fd of the stdin
651 * of a cgi script that has exited. */
652 if (!clients[i].waiting_on_child) {
653 goodbye(&fds[i], &clients[i]);
658 if (fds[i].fd == sock4)
659 do_accept(sock4, ctx, fds, clients);
660 else if (fds[i].fd == sock6)
661 do_accept(sock6, ctx, fds, clients);
663 handle(&fds[i], &clients[i]);
669 absolutify_path(const char *path)
676 wd = getcwd(NULL, 0);
677 if (asprintf(&r, "%s/%s", wd, path) == -1)
684 yyerror(const char *msg)
687 fprintf(stderr, "%d: %s\n", yylineno, msg);
691 parse_portno(const char *p)
697 lval = strtol(p, &ep, 10);
698 if (p[0] == '\0' || *ep != '\0')
699 errx(1, "not a number: %s", p);
700 if (lval < 0 || lval > UINT16_MAX)
701 errx(1, "port number out of range for domain %s: %ld", p, lval);
706 parse_conf(const char *path)
708 if ((yyin = fopen(path, "r")) == NULL)
709 err(1, "cannot open config %s", path);
718 load_vhosts(struct tls_config *tlsconf)
722 /* we need to set something, then we can add how many key we want */
723 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
724 errx(1, "tls_config_set_keypair_file failed");
726 for (h = hosts; h->domain != NULL; ++h) {
727 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
728 errx(1, "failed to load the keypair (%s, %s)",
731 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
732 err(1, "open %s for domain %s", h->dir, h->domain);
740 struct tls *ctx = NULL;
741 struct tls_config *tlsconf;
743 if ((tlsconf = tls_config_new()) == NULL)
744 err(1, "tls_config_new");
746 /* optionally accept client certs, but don't try to verify them */
747 tls_config_verify_client_optional(tlsconf);
748 tls_config_insecure_noverifycert(tlsconf);
750 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
751 err(1, "tls_config_set_protocols");
753 if ((ctx = tls_server()) == NULL)
754 errx(1, "tls_server failure");
756 load_vhosts(tlsconf);
758 if (tls_configure(ctx, tlsconf) == -1)
759 errx(1, "tls_configure: %s", tls_error(ctx));
761 if (!conf.foreground && daemon(0, 1) == -1)
764 sock4 = make_socket(conf.port, AF_INET);
767 sock6 = make_socket(conf.port, AF_INET6);
770 loop(ctx, sock4, sock6);
776 usage(const char *me)
779 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
780 "[-p port] [-x cgi-bin]\n",
785 main(int argc, char **argv)
788 const char *config_path = NULL;
792 bzero(hosts, sizeof(hosts));
793 for (i = 0; i < HOSTSLEN; ++i)
799 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
801 connected_clients = 0;
803 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
810 hosts[0].cert = optarg;
814 config_path = optarg;
818 free((char*)hosts[0].dir);
819 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
820 err(1, "absolutify_path");
832 hosts[0].key = optarg;
840 conf.port = parse_portno(optarg);
844 /* drop the starting / (if any) */
847 hosts[0].cgi = optarg;
856 if (config_path != NULL) {
857 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
858 hosts[0].dir != NULL)
859 errx(1, "can't specify options in conf mode");
860 parse_conf(config_path);
862 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
863 hosts[0].dir == NULL)
864 errx(1, "missing cert, key or root directory to serve");
865 hosts[0].domain = "*";
869 errx(0, "config OK");
871 signal(SIGPIPE, SIG_IGN);
872 signal(SIGCHLD, SIG_IGN);
875 signal(SIGINFO, sig_handler);
877 signal(SIGUSR2, sig_handler);
879 if (!conf.foreground) {
880 signal(SIGHUP, SIG_IGN);
881 if (daemon(1, 1) == -1)
885 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
886 fatal("socketpair: %s", strerror(errno));
890 fatal("fork: %s", strerror(errno));
898 default: /* parent */
900 return executor_main(p[0]);