Blob


1 /*
2 * Copyright (c) 2020 Omar Polo <op@omarpolo.com>
3 *
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.
7 *
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.
15 */
17 #include <sys/mman.h>
18 #include <sys/stat.h>
20 #include <assert.h>
21 #include <err.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <netdb.h>
26 #include <signal.h>
27 #include <stdarg.h>
28 #include <string.h>
30 #include "gmid.h"
32 struct vhost hosts[HOSTSLEN];
34 int connected_clients;
35 int goterror;
37 int exfd;
39 struct conf conf;
41 struct etm { /* file extension to mime */
42 const char *mime;
43 const char *ext;
44 } filetypes[] = {
45 {"application/pdf", "pdf"},
47 {"image/gif", "gif"},
48 {"image/jpeg", "jpg"},
49 {"image/jpeg", "jpeg"},
50 {"image/png", "png"},
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"},
58 {"text/xml", "xml"},
60 {NULL, NULL}
61 };
63 __attribute__ ((format (printf, 1, 2)))
64 __attribute__ ((__noreturn__))
65 static inline void
66 fatal(const char *fmt, ...)
67 {
68 va_list ap;
70 va_start(ap, fmt);
72 if (conf.foreground) {
73 vfprintf(stderr, fmt, ap);
74 fprintf(stderr, "\n");
75 } else
76 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
78 va_end(ap);
79 exit(1);
80 }
82 void
83 logs(int priority, struct client *c,
84 const char *fmt, ...)
85 {
86 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
87 char *fmted, *s;
88 size_t len;
89 int ec;
90 va_list ap;
92 va_start(ap, fmt);
94 if (c == NULL) {
95 strncpy(hbuf, "<internal>", sizeof(hbuf));
96 sbuf[0] = '\0';
97 } else {
98 len = sizeof(c->addr);
99 ec = getnameinfo((struct sockaddr*)&c->addr, len,
100 hbuf, sizeof(hbuf),
101 sbuf, sizeof(sbuf),
102 NI_NUMERICHOST | NI_NUMERICSERV);
103 if (ec != 0)
104 fatal("getnameinfo: %s", gai_strerror(ec));
107 if (vasprintf(&fmted, fmt, ap) == -1)
108 fatal("vasprintf: %s", strerror(errno));
110 if (conf.foreground)
111 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
112 else {
113 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
114 fatal("asprintf: %s", strerror(errno));
115 syslog(priority | LOG_DAEMON, "%s", s);
116 free(s);
119 free(fmted);
121 va_end(ap);
124 void
125 sig_handler(int sig)
127 (void)sig;
130 int
131 starts_with(const char *str, const char *prefix)
133 size_t i;
135 for (i = 0; prefix[i] != '\0'; ++i)
136 if (str[i] != prefix[i])
137 return 0;
138 return 1;
141 int
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 */
145 int len;
147 client->code = code;
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;
157 return 0;
158 case TLS_WANT_POLLOUT:
159 pfd->events = POLLOUT;
160 return 0;
161 default:
162 return 1;
166 ssize_t
167 filesize(int fd)
169 ssize_t len;
171 if ((len = lseek(fd, 0, SEEK_END)) == -1)
172 return -1;
173 if (lseek(fd, 0, SEEK_SET) == -1)
174 return -1;
175 return len;
178 const char *
179 path_ext(const char *path)
181 const char *end;
183 end = path + strlen(path)-1;
184 for (; end != path; --end) {
185 if (*end == '.')
186 return end+1;
187 if (*end == '/')
188 break;
191 return NULL;
194 const char *
195 mime(const char *path)
197 const char *ext, *def = "application/octet-stream";
198 struct etm *t;
200 if ((ext = path_ext(path)) == NULL)
201 return def;
203 for (t = filetypes; t->mime != NULL; ++t)
204 if (!strcmp(ext, t->ext))
205 return t->mime;
207 return def;
210 int
211 check_path(struct client *c, const char *path, int *fd)
213 struct stat sb;
215 assert(path != NULL);
216 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
217 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
218 return FILE_MISSING;
221 if (fstat(*fd, &sb) == -1) {
222 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
223 return FILE_MISSING;
226 if (S_ISDIR(sb.st_mode))
227 return FILE_DIRECTORY;
229 if (sb.st_mode & S_IXUSR)
230 return FILE_EXECUTABLE;
232 return FILE_EXISTS;
235 int
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);
243 /* fallthrough */
245 case FILE_EXISTS:
246 if ((c->len = filesize(c->fd)) == -1) {
247 LOGE(c, "failed to get file size for %s", fpath);
248 goodbye(fds, c);
249 return 0;
252 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
253 c->fd, 0)) == MAP_FAILED) {
254 warn("mmap: %s", fpath);
255 goodbye(fds, c);
256 return 0;
258 c->i = c->buf;
259 return start_reply(fds, c, SUCCESS, mime(fpath));
261 case FILE_DIRECTORY:
262 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
263 close(c->fd);
264 c->fd = -1;
265 send_dir(fpath, fds, c);
266 return 0;
268 case FILE_MISSING:
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"))
273 return 0;
274 goodbye(fds, c);
275 return 0;
277 default:
278 /* unreachable */
279 abort();
283 void
284 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
286 ssize_t ret, len;
288 if (c->fd == -1) {
289 if (!open_file(path, query, fds, c))
290 return;
291 c->state = S_SENDING;
294 len = (c->buf + c->len) - c->i;
296 while (len > 0) {
297 switch (ret = tls_write(c->ctx, c->i, len)) {
298 case -1:
299 LOGE(c, "tls_write: %s", tls_error(c->ctx));
300 goodbye(fds, c);
301 return;
303 case TLS_WANT_POLLIN:
304 fds->events = POLLIN;
305 return;
307 case TLS_WANT_POLLOUT:
308 fds->events = POLLOUT;
309 return;
311 default:
312 c->i += ret;
313 len -= ret;
314 break;
318 goodbye(fds, c);
321 void
322 send_dir(char *path, struct pollfd *fds, struct client *client)
324 char fpath[PATHBUF];
325 size_t len;
327 bzero(fpath, PATHBUF);
329 if (path[0] != '.')
330 fpath[0] = '.';
332 /* this cannot fail since sizeof(fpath) > maxlen of path */
333 strlcat(fpath, path, PATHBUF);
334 len = strlen(fpath);
336 /* add a trailing / in case. */
337 if (fpath[len-1] != '/') {
338 fpath[len] = '/';
341 strlcat(fpath, "index.gmi", sizeof(fpath));
343 send_file(fpath, NULL, fds, client);
346 void
347 handle_handshake(struct pollfd *fds, struct client *c)
349 struct vhost *h;
350 const char *servname;
352 switch (tls_handshake(c->ctx)) {
353 case 0: /* success */
354 case -1: /* already handshaked */
355 break;
356 case TLS_WANT_POLLIN:
357 fds->events = POLLIN;
358 return;
359 case TLS_WANT_POLLOUT:
360 fds->events = POLLOUT;
361 return;
362 default:
363 /* unreachable */
364 abort();
367 servname = tls_conn_servername(c->ctx);
368 if (servname == NULL)
369 goto hostnotfound;
371 for (h = hosts; h->domain != NULL; ++h) {
372 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
373 break;
376 if (h->domain != NULL) {
377 c->state = S_OPEN;
378 c->host = h;
379 handle_open_conn(fds, c);
380 return;
383 hostnotfound:
384 /* XXX: check the correct response */
385 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
386 return;
387 goodbye(fds, c);
390 void
391 handle_open_conn(struct pollfd *fds, struct client *c)
393 char buf[GEMINI_URL_LEN];
394 const char *parse_err = "invalid request";
395 struct iri iri;
397 bzero(buf, sizeof(buf));
399 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
400 case -1:
401 LOGE(c, "tls_read: %s", tls_error(c->ctx));
402 goodbye(fds, c);
403 return;
405 case TLS_WANT_POLLIN:
406 fds->events = POLLIN;
407 return;
409 case TLS_WANT_POLLOUT:
410 fds->events = POLLOUT;
411 return;
414 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
415 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
416 return;
417 goodbye(fds, c);
418 return;
421 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
422 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
423 return;
424 goodbye(fds, c);
425 return;
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);
436 void
437 handle(struct pollfd *fds, struct client *client)
439 switch (client->state) {
440 case S_HANDSHAKE:
441 handle_handshake(fds, client);
442 break;
444 case S_OPEN:
445 handle_open_conn(fds, client);
446 break;
448 case S_INITIALIZING:
449 if (!start_reply(fds, client, client->code, client->meta))
450 return;
452 if (client->code != SUCCESS) {
453 /* we don't need a body */
454 goodbye(fds, client);
455 return;
458 client->state = S_SENDING;
460 /* fallthrough */
462 case S_SENDING:
463 if (client->child)
464 handle_cgi(fds, client);
465 else
466 send_file(NULL, NULL, fds, client);
467 break;
469 case S_CLOSING:
470 goodbye(fds, client);
471 break;
473 default:
474 /* unreachable */
475 abort();
479 void
480 mark_nonblock(int fd)
482 int flags;
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));
490 int
491 make_socket(int port, int family)
493 int sock, v;
494 struct sockaddr_in addr4;
495 struct sockaddr_in6 addr6;
496 struct sockaddr *addr;
497 socklen_t len;
499 switch (family) {
500 case AF_INET:
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;
506 len = sizeof(addr4);
507 break;
509 case AF_INET6:
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;
515 len = sizeof(addr6);
516 break;
518 default:
519 /* unreachable */
520 abort();
523 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
524 fatal("socket: %s", strerror(errno));
526 v = 1;
527 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
528 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
530 v = 1;
531 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
532 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
534 mark_nonblock(sock);
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));
542 return sock;
545 void
546 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
548 int i, fd;
549 struct sockaddr_storage addr;
550 socklen_t len;
552 len = sizeof(addr);
553 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
554 if (errno == EWOULDBLOCK)
555 return;
556 fatal("accept: %s", strerror(errno));
559 mark_nonblock(fd);
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! */
567 fds[i].fd = fd;
568 fds[i].events = POLLIN;
570 clients[i].state = S_HANDSHAKE;
571 clients[i].fd = -1;
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;
578 connected_clients++;
579 return;
583 close(fd);
586 void
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;
594 return;
595 case TLS_WANT_POLLOUT:
596 pfd->events = POLLOUT;
597 return;
600 connected_clients--;
602 tls_free(c->ctx);
603 c->ctx = NULL;
605 if (c->buf != MAP_FAILED)
606 munmap(c->buf, c->len);
608 if (c->fd != -1)
609 close(c->fd);
611 close(pfd->fd);
612 pfd->fd = -1;
615 void
616 loop(struct tls *ctx, int sock4, int sock6)
618 int i;
619 struct client clients[MAX_USERS];
620 struct pollfd fds[MAX_USERS];
622 for (i = 0; i < MAX_USERS; ++i) {
623 fds[i].fd = -1;
624 fds[i].events = POLLIN;
625 bzero(&clients[i], sizeof(struct client));
628 fds[0].fd = sock4;
629 fds[1].fd = sock6;
631 for (;;) {
632 if (poll(fds, MAX_USERS, INFTIM) == -1) {
633 if (errno == EINTR) {
634 warnx("connected clients: %d",
635 connected_clients);
636 continue;
638 fatal("poll: %s", strerror(errno));
641 for (i = 0; i < MAX_USERS; i++) {
642 if (fds[i].revents == 0)
643 continue;
645 if (fds[i].revents & (POLLERR|POLLNVAL))
646 fatal("bad fd %d: %s", fds[i].fd,
647 strerror(errno));
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]);
654 continue;
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);
662 else
663 handle(&fds[i], &clients[i]);
668 char *
669 absolutify_path(const char *path)
671 char *wd, *r;
673 if (*path == '/')
674 return strdup(path);
676 wd = getcwd(NULL, 0);
677 if (asprintf(&r, "%s/%s", wd, path) == -1)
678 err(1, "asprintf");
679 free(wd);
680 return r;
683 void
684 yyerror(const char *msg)
686 goterror = 1;
687 fprintf(stderr, "%d: %s\n", yylineno, msg);
690 int
691 parse_portno(const char *p)
693 char *ep;
694 long lval;
696 errno = 0;
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);
702 return lval;
705 void
706 parse_conf(const char *path)
708 if ((yyin = fopen(path, "r")) == NULL)
709 err(1, "cannot open config %s", path);
710 yyparse();
711 fclose(yyin);
713 if (goterror)
714 exit(1);
717 void
718 load_vhosts(struct tls_config *tlsconf)
720 struct vhost *h;
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)",
729 h->cert, h->key);
731 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
732 err(1, "open %s for domain %s", h->dir, h->domain);
736 int
737 listener_main()
739 int sock4, sock6;
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)
762 exit(1);
764 sock4 = make_socket(conf.port, AF_INET);
765 sock6 = -1;
766 if (conf.ipv6)
767 sock6 = make_socket(conf.port, AF_INET6);
769 sandbox();
770 loop(ctx, sock4, sock6);
772 return 0;
775 void
776 usage(const char *me)
778 fprintf(stderr,
779 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
780 "[-p port] [-x cgi-bin]\n",
781 me);
784 int
785 main(int argc, char **argv)
787 int ch, p[2];
788 const char *config_path = NULL;
789 size_t i;
790 int conftest = 0;
792 bzero(hosts, sizeof(hosts));
793 for (i = 0; i < HOSTSLEN; ++i)
794 hosts[i].dirfd = -1;
796 conf.foreground = 1;
797 conf.port = 1965;
798 conf.ipv6 = 0;
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) {
804 switch (ch) {
805 case '6':
806 conf.ipv6 = 1;
807 break;
809 case 'C':
810 hosts[0].cert = optarg;
811 break;
813 case 'c':
814 config_path = optarg;
815 break;
817 case 'd':
818 free((char*)hosts[0].dir);
819 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
820 err(1, "absolutify_path");
821 break;
823 case 'f':
824 conf.foreground = 1;
825 break;
827 case 'h':
828 usage(*argv);
829 return 0;
831 case 'K':
832 hosts[0].key = optarg;
833 break;
835 case 'n':
836 conftest = 1;
837 break;
839 case 'p':
840 conf.port = parse_portno(optarg);
841 break;
843 case 'x':
844 /* drop the starting / (if any) */
845 if (*optarg == '/')
846 optarg++;
847 hosts[0].cgi = optarg;
848 break;
850 default:
851 usage(*argv);
852 return 1;
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);
861 } else {
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 = "*";
868 if (conftest)
869 errx(0, "config OK");
871 signal(SIGPIPE, SIG_IGN);
872 signal(SIGCHLD, SIG_IGN);
874 #ifdef SIGINFO
875 signal(SIGINFO, sig_handler);
876 #endif
877 signal(SIGUSR2, sig_handler);
879 if (!conf.foreground)
880 signal(SIGHUP, SIG_IGN);
882 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
883 fatal("socketpair: %s", strerror(errno));
885 switch (fork()) {
886 case -1:
887 fatal("fork: %s", strerror(errno));
889 case 0: /* child */
890 close(p[0]);
891 exfd = p[1];
892 listener_main();
893 _exit(0);
895 default: /* parent */
896 close(p[1]);
897 return executor_main(p[0]);