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 struct conf conf;
39 struct etm { /* file extension to mime */
40 const char *mime;
41 const char *ext;
42 } filetypes[] = {
43 {"application/pdf", "pdf"},
45 {"image/gif", "gif"},
46 {"image/jpeg", "jpg"},
47 {"image/jpeg", "jpeg"},
48 {"image/png", "png"},
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"},
56 {"text/xml", "xml"},
58 {NULL, NULL}
59 };
61 __attribute__ ((format (printf, 1, 2)))
62 __attribute__ ((__noreturn__))
63 static inline void
64 fatal(const char *fmt, ...)
65 {
66 va_list ap;
68 va_start(ap, fmt);
70 if (conf.foreground) {
71 vfprintf(stderr, fmt, ap);
72 fprintf(stderr, "\n");
73 } else
74 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
76 va_end(ap);
77 exit(1);
78 }
80 void
81 logs(int priority, struct client *c,
82 const char *fmt, ...)
83 {
84 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
85 char *fmted, *s;
86 size_t len;
87 int ec;
88 va_list ap;
90 va_start(ap, fmt);
92 if (c == NULL) {
93 strncpy(hbuf, "<internal>", sizeof(hbuf));
94 sbuf[0] = '\0';
95 } else {
96 len = sizeof(c->addr);
97 ec = getnameinfo((struct sockaddr*)&c->addr, len,
98 hbuf, sizeof(hbuf),
99 sbuf, sizeof(sbuf),
100 NI_NUMERICHOST | NI_NUMERICSERV);
101 if (ec != 0)
102 fatal("getnameinfo: %s", gai_strerror(ec));
105 if (vasprintf(&fmted, fmt, ap) == -1)
106 fatal("vasprintf: %s", strerror(errno));
108 if (conf.foreground)
109 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
110 else {
111 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
112 fatal("asprintf: %s", strerror(errno));
113 syslog(priority | LOG_DAEMON, "%s", s);
114 free(s);
117 free(fmted);
119 va_end(ap);
122 void
123 sig_handler(int sig)
125 (void)sig;
128 int
129 starts_with(const char *str, const char *prefix)
131 size_t i;
133 for (i = 0; prefix[i] != '\0'; ++i)
134 if (str[i] != prefix[i])
135 return 0;
136 return 1;
139 int
140 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
142 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
143 int len;
145 client->code = code;
146 client->meta = reason;
147 client->state = S_INITIALIZING;
149 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
150 assert(len < (int)sizeof(buf));
152 switch (tls_write(client->ctx, buf, len)) {
153 case TLS_WANT_POLLIN:
154 pfd->events = POLLIN;
155 return 0;
156 case TLS_WANT_POLLOUT:
157 pfd->events = POLLOUT;
158 return 0;
159 default:
160 return 1;
164 ssize_t
165 filesize(int fd)
167 ssize_t len;
169 if ((len = lseek(fd, 0, SEEK_END)) == -1)
170 return -1;
171 if (lseek(fd, 0, SEEK_SET) == -1)
172 return -1;
173 return len;
176 const char *
177 path_ext(const char *path)
179 const char *end;
181 end = path + strlen(path)-1;
182 for (; end != path; --end) {
183 if (*end == '.')
184 return end+1;
185 if (*end == '/')
186 break;
189 return NULL;
192 const char *
193 mime(const char *path)
195 const char *ext, *def = "application/octet-stream";
196 struct etm *t;
198 if ((ext = path_ext(path)) == NULL)
199 return def;
201 for (t = filetypes; t->mime != NULL; ++t)
202 if (!strcmp(ext, t->ext))
203 return t->mime;
205 return def;
208 int
209 check_path(struct client *c, const char *path, int *fd)
211 struct stat sb;
213 assert(path != NULL);
214 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
215 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
216 return FILE_MISSING;
219 if (fstat(*fd, &sb) == -1) {
220 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
221 return FILE_MISSING;
224 if (S_ISDIR(sb.st_mode))
225 return FILE_DIRECTORY;
227 if (sb.st_mode & S_IXUSR)
228 return FILE_EXECUTABLE;
230 return FILE_EXISTS;
233 int
234 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
236 switch (check_path(c, fpath, &c->fd)) {
237 case FILE_EXECUTABLE:
238 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
239 return start_cgi(fpath, "", query, fds, c);
241 /* fallthrough */
243 case FILE_EXISTS:
244 if ((c->len = filesize(c->fd)) == -1) {
245 LOGE(c, "failed to get file size for %s", fpath);
246 goodbye(fds, c);
247 return 0;
250 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
251 c->fd, 0)) == MAP_FAILED) {
252 warn("mmap: %s", fpath);
253 goodbye(fds, c);
254 return 0;
256 c->i = c->buf;
257 return start_reply(fds, c, SUCCESS, mime(fpath));
259 case FILE_DIRECTORY:
260 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
261 close(c->fd);
262 c->fd = -1;
263 send_dir(fpath, fds, c);
264 return 0;
266 case FILE_MISSING:
267 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
268 return check_for_cgi(fpath, query, fds, c);
270 if (!start_reply(fds, c, NOT_FOUND, "not found"))
271 return 0;
272 goodbye(fds, c);
273 return 0;
275 default:
276 /* unreachable */
277 abort();
281 void
282 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
284 ssize_t ret, len;
286 if (c->fd == -1) {
287 if (!open_file(path, query, fds, c))
288 return;
289 c->state = S_SENDING;
292 len = (c->buf + c->len) - c->i;
294 while (len > 0) {
295 switch (ret = tls_write(c->ctx, c->i, len)) {
296 case -1:
297 LOGE(c, "tls_write: %s", tls_error(c->ctx));
298 goodbye(fds, c);
299 return;
301 case TLS_WANT_POLLIN:
302 fds->events = POLLIN;
303 return;
305 case TLS_WANT_POLLOUT:
306 fds->events = POLLOUT;
307 return;
309 default:
310 c->i += ret;
311 len -= ret;
312 break;
316 goodbye(fds, c);
319 void
320 send_dir(char *path, struct pollfd *fds, struct client *client)
322 char fpath[PATHBUF];
323 size_t len;
325 bzero(fpath, PATHBUF);
327 if (path[0] != '.')
328 fpath[0] = '.';
330 /* this cannot fail since sizeof(fpath) > maxlen of path */
331 strlcat(fpath, path, PATHBUF);
332 len = strlen(fpath);
334 /* add a trailing / in case. */
335 if (fpath[len-1] != '/') {
336 fpath[len] = '/';
339 strlcat(fpath, "index.gmi", sizeof(fpath));
341 send_file(fpath, NULL, fds, client);
344 void
345 handle_handshake(struct pollfd *fds, struct client *c)
347 struct vhost *h;
348 const char *servname;
350 switch (tls_handshake(c->ctx)) {
351 case 0: /* success */
352 case -1: /* already handshaked */
353 break;
354 case TLS_WANT_POLLIN:
355 fds->events = POLLIN;
356 return;
357 case TLS_WANT_POLLOUT:
358 fds->events = POLLOUT;
359 return;
360 default:
361 /* unreachable */
362 abort();
365 servname = tls_conn_servername(c->ctx);
366 if (servname == NULL)
367 goto hostnotfound;
369 for (h = hosts; h->domain != NULL; ++h) {
370 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
371 break;
374 if (h->domain != NULL) {
375 c->state = S_OPEN;
376 c->host = h;
377 handle_open_conn(fds, c);
378 return;
381 hostnotfound:
382 /* XXX: check the correct response */
383 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
384 return;
385 goodbye(fds, c);
388 void
389 handle_open_conn(struct pollfd *fds, struct client *c)
391 char buf[GEMINI_URL_LEN];
392 const char *parse_err = "invalid request";
393 struct iri iri;
395 bzero(buf, sizeof(buf));
397 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
398 case -1:
399 LOGE(c, "tls_read: %s", tls_error(c->ctx));
400 goodbye(fds, c);
401 return;
403 case TLS_WANT_POLLIN:
404 fds->events = POLLIN;
405 return;
407 case TLS_WANT_POLLOUT:
408 fds->events = POLLOUT;
409 return;
412 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
413 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
414 return;
415 goodbye(fds, c);
416 return;
419 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
420 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
421 return;
422 goodbye(fds, c);
423 return;
426 LOGI(c, "GET %s%s%s",
427 *iri.path ? iri.path : "/",
428 *iri.query ? "?" : "",
429 *iri.query ? iri.query : "");
431 send_file(iri.path, iri.query, fds, c);
434 void
435 handle(struct pollfd *fds, struct client *client)
437 switch (client->state) {
438 case S_HANDSHAKE:
439 handle_handshake(fds, client);
440 break;
442 case S_OPEN:
443 handle_open_conn(fds, client);
444 break;
446 case S_INITIALIZING:
447 if (!start_reply(fds, client, client->code, client->meta))
448 return;
450 if (client->code != SUCCESS) {
451 /* we don't need a body */
452 goodbye(fds, client);
453 return;
456 client->state = S_SENDING;
458 /* fallthrough */
460 case S_SENDING:
461 if (client->child != -1)
462 handle_cgi(fds, client);
463 else
464 send_file(NULL, NULL, fds, client);
465 break;
467 case S_CLOSING:
468 goodbye(fds, client);
469 break;
471 default:
472 /* unreachable */
473 abort();
477 void
478 mark_nonblock(int fd)
480 int flags;
482 if ((flags = fcntl(fd, F_GETFL)) == -1)
483 fatal("fcntl(F_GETFL): %s", strerror(errno));
484 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
485 fatal("fcntl(F_SETFL): %s", strerror(errno));
488 int
489 make_socket(int port, int family)
491 int sock, v;
492 struct sockaddr_in addr4;
493 struct sockaddr_in6 addr6;
494 struct sockaddr *addr;
495 socklen_t len;
497 switch (family) {
498 case AF_INET:
499 bzero(&addr4, sizeof(addr4));
500 addr4.sin_family = family;
501 addr4.sin_port = htons(port);
502 addr4.sin_addr.s_addr = INADDR_ANY;
503 addr = (struct sockaddr*)&addr4;
504 len = sizeof(addr4);
505 break;
507 case AF_INET6:
508 bzero(&addr6, sizeof(addr6));
509 addr6.sin6_family = AF_INET6;
510 addr6.sin6_port = htons(port);
511 addr6.sin6_addr = in6addr_any;
512 addr = (struct sockaddr*)&addr6;
513 len = sizeof(addr6);
514 break;
516 default:
517 /* unreachable */
518 abort();
521 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
522 fatal("socket: %s", strerror(errno));
524 v = 1;
525 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
526 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
528 v = 1;
529 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
530 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
532 mark_nonblock(sock);
534 if (bind(sock, addr, len) == -1)
535 fatal("bind: %s", strerror(errno));
537 if (listen(sock, 16) == -1)
538 fatal("listen: %s", strerror(errno));
540 return sock;
543 void
544 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
546 int i, fd;
547 struct sockaddr_storage addr;
548 socklen_t len;
550 len = sizeof(addr);
551 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
552 if (errno == EWOULDBLOCK)
553 return;
554 fatal("accept: %s", strerror(errno));
557 mark_nonblock(fd);
559 for (i = 0; i < MAX_USERS; ++i) {
560 if (fds[i].fd == -1) {
561 bzero(&clients[i], sizeof(struct client));
562 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
563 break; /* goodbye fd! */
565 fds[i].fd = fd;
566 fds[i].events = POLLIN;
568 clients[i].state = S_HANDSHAKE;
569 clients[i].fd = -1;
570 clients[i].child = -1;
571 clients[i].buf = MAP_FAILED;
572 clients[i].af = AF_INET;
573 clients[i].addr = addr;
575 connected_clients++;
576 return;
580 close(fd);
583 void
584 goodbye(struct pollfd *pfd, struct client *c)
586 c->state = S_CLOSING;
588 switch (tls_close(c->ctx)) {
589 case TLS_WANT_POLLIN:
590 pfd->events = POLLIN;
591 return;
592 case TLS_WANT_POLLOUT:
593 pfd->events = POLLOUT;
594 return;
597 connected_clients--;
599 tls_free(c->ctx);
600 c->ctx = NULL;
602 if (c->buf != MAP_FAILED)
603 munmap(c->buf, c->len);
605 if (c->fd != -1)
606 close(c->fd);
608 close(pfd->fd);
609 pfd->fd = -1;
612 void
613 loop(struct tls *ctx, int sock4, int sock6)
615 int i;
616 struct client clients[MAX_USERS];
617 struct pollfd fds[MAX_USERS];
619 for (i = 0; i < MAX_USERS; ++i) {
620 fds[i].fd = -1;
621 fds[i].events = POLLIN;
622 bzero(&clients[i], sizeof(struct client));
625 fds[0].fd = sock4;
626 fds[1].fd = sock6;
628 for (;;) {
629 if (poll(fds, MAX_USERS, INFTIM) == -1) {
630 if (errno == EINTR) {
631 warnx("connected clients: %d",
632 connected_clients);
633 continue;
635 fatal("poll: %s", strerror(errno));
638 for (i = 0; i < MAX_USERS; i++) {
639 if (fds[i].revents == 0)
640 continue;
642 if (fds[i].revents & (POLLERR|POLLNVAL))
643 fatal("bad fd %d: %s", fds[i].fd,
644 strerror(errno));
646 if (fds[i].revents & POLLHUP) {
647 /* fds[i] may be the fd of the stdin
648 * of a cgi script that has exited. */
649 if (!clients[i].waiting_on_child) {
650 goodbye(&fds[i], &clients[i]);
651 continue;
655 if (fds[i].fd == sock4)
656 do_accept(sock4, ctx, fds, clients);
657 else if (fds[i].fd == sock6)
658 do_accept(sock6, ctx, fds, clients);
659 else
660 handle(&fds[i], &clients[i]);
665 char *
666 absolutify_path(const char *path)
668 char *wd, *r;
670 if (*path == '/')
671 return strdup(path);
673 wd = getwd(NULL);
674 if (asprintf(&r, "%s/%s", wd, path) == -1)
675 err(1, "asprintf");
676 free(wd);
677 return r;
680 void
681 yyerror(const char *msg)
683 goterror = 1;
684 fprintf(stderr, "%d: %s\n", yylineno, msg);
687 int
688 parse_portno(const char *p)
690 char *ep;
691 long lval;
693 errno = 0;
694 lval = strtol(p, &ep, 10);
695 if (p[0] == '\0' || *ep != '\0')
696 errx(1, "not a number: %s", p);
697 if (lval < 0 || lval > UINT16_MAX)
698 errx(1, "port number out of range for domain %s: %ld", p, lval);
699 return lval;
702 void
703 parse_conf(const char *path)
705 if ((yyin = fopen(path, "r")) == NULL)
706 err(1, "cannot open config %s", path);
707 yyparse();
708 fclose(yyin);
710 if (goterror)
711 exit(1);
714 void
715 load_vhosts(struct tls_config *tlsconf)
717 struct vhost *h;
719 /* we need to set something, then we can add how many key we want */
720 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
721 errx(1, "tls_config_set_keypair_file failed");
723 for (h = hosts; h->domain != NULL; ++h) {
724 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
725 errx(1, "failed to load the keypair (%s, %s)",
726 h->cert, h->key);
728 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
729 err(1, "open %s for domain %s", h->dir, h->domain);
733 void
734 usage(const char *me)
736 fprintf(stderr,
737 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
738 "[-p port] [-x cgi-bin]\n",
739 me);
742 int
743 main(int argc, char **argv)
745 struct tls *ctx = NULL;
746 struct tls_config *tlsconf;
747 int sock4, sock6, ch;
748 const char *config_path = NULL;
749 size_t i;
750 int conftest = 0;
752 bzero(hosts, sizeof(hosts));
753 for (i = 0; i < HOSTSLEN; ++i)
754 hosts[i].dirfd = -1;
756 conf.foreground = 1;
757 conf.port = 1965;
758 conf.ipv6 = 0;
759 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
761 connected_clients = 0;
763 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
764 switch (ch) {
765 case '6':
766 conf.ipv6 = 1;
767 break;
769 case 'C':
770 hosts[0].cert = optarg;
771 break;
773 case 'c':
774 config_path = optarg;
775 break;
777 case 'd':
778 free((char*)hosts[0].dir);
779 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
780 err(1, "absolutify_path");
781 break;
783 case 'f':
784 conf.foreground = 1;
785 break;
787 case 'h':
788 usage(*argv);
789 return 0;
791 case 'K':
792 hosts[0].key = optarg;
793 break;
795 case 'n':
796 conftest = 1;
797 break;
799 case 'p':
800 conf.port = parse_portno(optarg);
802 case 'x':
803 /* drop the starting / (if any) */
804 if (*optarg == '/')
805 optarg++;
806 hosts[0].cgi = optarg;
807 break;
809 default:
810 usage(*argv);
811 return 1;
815 if (config_path != NULL) {
816 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
817 hosts[0].dir != NULL)
818 errx(1, "can't specify options in conf mode");
819 parse_conf(config_path);
820 } else {
821 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
822 hosts[0].dir == NULL)
823 errx(1, "missing cert, key or root directory to serve");
824 hosts[0].domain = "*";
827 if (conftest)
828 errx(0, "config OK");
830 signal(SIGPIPE, SIG_IGN);
831 signal(SIGCHLD, SIG_IGN);
833 #ifdef SIGINFO
834 signal(SIGINFO, sig_handler);
835 #endif
836 signal(SIGUSR2, sig_handler);
838 if (!conf.foreground)
839 signal(SIGHUP, SIG_IGN);
841 if ((tlsconf = tls_config_new()) == NULL)
842 err(1, "tls_config_new");
844 /* optionally accept client certs, but don't try to verify them */
845 tls_config_verify_client_optional(tlsconf);
846 tls_config_insecure_noverifycert(tlsconf);
848 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
849 err(1, "tls_config_set_protocols");
851 load_vhosts(tlsconf);
853 if ((ctx = tls_server()) == NULL)
854 err(1, "tls_server");
856 if (tls_configure(ctx, tlsconf) == -1)
857 errx(1, "tls_configure: %s", tls_error(ctx));
859 sock4 = make_socket(conf.port, AF_INET);
860 if (conf.ipv6)
861 sock6 = make_socket(conf.port, AF_INET6);
862 else
863 sock6 = -1;
865 if (!conf.foreground && daemon(0, 1) == -1)
866 exit(1);
868 sandbox();
870 loop(ctx, sock4, sock6);
872 close(sock4);
873 close(sock6);
874 tls_free(ctx);
875 tls_config_free(tlsconf);
877 return 0;