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 #define LOGE(c, fmt, ...) logs(LOG_ERR, c, fmt, __VA_ARGS__)
33 #define LOGN(c, fmt, ...) logs(LOG_NOTICE, c, fmt, __VA_ARGS__)
34 #define LOGI(c, fmt, ...) logs(LOG_INFO, c, fmt, __VA_ARGS__)
35 #define LOGD(c, fmt, ...) logs(LOG_DEBUG, c, fmt, __VA_ARGS__)
37 const char *dir, *cgi;
38 int dirfd;
39 int port;
40 int foreground;
41 int connected_clients;
43 struct etm { /* file extension to mime */
44 const char *mime;
45 const char *ext;
46 } filetypes[] = {
47 {"application/pdf", "pdf"},
49 {"image/gif", "gif"},
50 {"image/jpeg", "jpg"},
51 {"image/jpeg", "jpeg"},
52 {"image/png", "png"},
53 {"image/svg+xml", "svg"},
55 {"text/gemini", "gemini"},
56 {"text/gemini", "gmi"},
57 {"text/markdown", "markdown"},
58 {"text/markdown", "md"},
59 {"text/plain", "txt"},
60 {"text/xml", "xml"},
62 {NULL, NULL}
63 };
65 static inline void
66 safe_setenv(const char *name, const char *val)
67 {
68 if (val == NULL)
69 val = "";
70 setenv(name, val, 1);
71 }
73 __attribute__ ((format (printf, 1, 2)))
74 __attribute__ ((__noreturn__))
75 static inline void
76 fatal(const char *fmt, ...)
77 {
78 va_list ap;
80 va_start(ap, fmt);
82 if (foreground) {
83 vfprintf(stderr, fmt, ap);
84 fprintf(stderr, "\n");
85 } else
86 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
88 va_end(ap);
89 exit(1);
90 }
92 __attribute__ ((format (printf, 3, 4)))
93 static inline void
94 logs(int priority, struct client *c,
95 const char *fmt, ...)
96 {
97 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
98 char *fmted, *s;
99 size_t len;
100 int ec;
101 va_list ap;
103 va_start(ap, fmt);
105 len = sizeof(c->addr);
106 ec = getnameinfo((struct sockaddr*)&c->addr, len,
107 hbuf, sizeof(hbuf),
108 sbuf, sizeof(sbuf),
109 NI_NUMERICHOST | NI_NUMERICSERV);
110 if (ec != 0)
111 fatal("getnameinfo: %s", gai_strerror(ec));
113 if (vasprintf(&fmted, fmt, ap) == -1)
114 fatal("vasprintf: %s", strerror(errno));
116 if (foreground)
117 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
118 else {
119 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
120 fatal("asprintf: %s", strerror(errno));
121 syslog(priority | LOG_DAEMON, "%s", s);
122 free(s);
125 free(fmted);
127 va_end(ap);
130 void
131 sig_handler(int sig)
133 (void)sig;
136 int
137 starts_with(const char *str, const char *prefix)
139 size_t i;
141 for (i = 0; prefix[i] != '\0'; ++i)
142 if (str[i] != prefix[i])
143 return 0;
144 return 1;
147 int
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 */
151 int len;
152 int ret;
154 client->code = code;
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;
163 return 0;
166 if (ret == TLS_WANT_POLLOUT) {
167 pfd->events = POLLOUT;
168 return 0;
171 return 1;
174 ssize_t
175 filesize(int fd)
177 ssize_t len;
179 if ((len = lseek(fd, 0, SEEK_END)) == -1)
180 return -1;
181 if (lseek(fd, 0, SEEK_SET) == -1)
182 return -1;
183 return len;
186 const char *
187 path_ext(const char *path)
189 const char *end;
191 end = path + strlen(path)-1; /* the last byte before the NUL */
192 for (; end != path; --end) {
193 if (*end == '.')
194 return end+1;
195 if (*end == '/')
196 break;
199 return NULL;
202 const char *
203 mime(const char *path)
205 const char *ext, *def = "application/octet-stream";
206 struct etm *t;
208 if ((ext = path_ext(path)) == NULL)
209 return def;
211 for (t = filetypes; t->mime != NULL; ++t)
212 if (!strcmp(ext, t->ext))
213 return t->mime;
215 return def;
218 int
219 check_path(struct client *c, const char *path, int *fd)
221 struct stat sb;
223 assert(path != NULL);
224 if ((*fd = openat(dirfd, *path ? path : ".",
225 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
226 return FILE_MISSING;
229 if (fstat(*fd, &sb) == -1) {
230 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
231 return FILE_MISSING;
234 if (S_ISDIR(sb.st_mode))
235 return FILE_DIRECTORY;
237 if (sb.st_mode & S_IXUSR)
238 return FILE_EXECUTABLE;
240 return FILE_EXISTS;
243 /*
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.
249 */
250 int
251 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
253 char *end;
254 end = strchr(path, '\0');
256 /* NB: assume CGI is enabled and path matches cgi */
258 while (end > path) {
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. */
262 while (*end != '/')
263 end--;
264 *end = '\0';
266 switch (check_path(c, path, &c->fd)) {
267 case FILE_EXECUTABLE:
268 return start_cgi(path, end+1, query, fds,c);
269 case FILE_MISSING:
270 break;
271 default:
272 goto err;
275 *end = '/';
276 end--;
279 err:
280 if (!start_reply(fds, c, NOT_FOUND, "not found"))
281 return 0;
282 goodbye(fds, c);
283 return 0;
287 int
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 (cgi != NULL && starts_with(fpath, cgi))
293 return start_cgi(fpath, "", query, fds, c);
295 /* fallthrough */
297 case FILE_EXISTS:
298 if ((c->len = filesize(c->fd)) == -1) {
299 LOGE(c, "failed to get file size for %s", fpath);
300 goodbye(fds, c);
301 return 0;
304 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
305 c->fd, 0)) == MAP_FAILED) {
306 warn("mmap: %s", fpath);
307 goodbye(fds, c);
308 return 0;
310 c->i = c->buf;
311 return start_reply(fds, c, SUCCESS, mime(fpath));
313 case FILE_DIRECTORY:
314 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
315 close(c->fd);
316 c->fd = -1;
317 send_dir(fpath, fds, c);
318 return 0;
320 case FILE_MISSING:
321 if (cgi != NULL && starts_with(fpath, cgi))
322 return check_for_cgi(fpath, query, fds, c);
324 if (!start_reply(fds, c, NOT_FOUND, "not found"))
325 return 0;
326 goodbye(fds, c);
327 return 0;
329 default:
330 /* unreachable */
331 abort();
335 int
336 start_cgi(const char *spath, const char *relpath, const char *query,
337 struct pollfd *fds, struct client *c)
339 pid_t pid;
340 int p[2]; /* read end, write end */
342 if (pipe(p) == -1)
343 goto err;
345 switch (pid = fork()) {
346 case -1:
347 goto err;
349 case 0: { /* child */
350 char *ex, *requri, *portno;
351 char addr[NI_MAXHOST];
352 char *argv[] = { NULL, NULL, NULL };
353 int ec;
355 close(p[0]);
356 if (dup2(p[1], 1) == -1)
357 goto childerr;
359 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
360 goto childerr;
362 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
363 addr, sizeof(addr),
364 NULL, 0,
365 NI_NUMERICHOST | NI_NUMERICSERV);
366 if (ec != 0)
367 goto childerr;
369 if (asprintf(&portno, "%d", port) == -1)
370 goto childerr;
372 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
373 goto childerr;
375 if (asprintf(&requri, "%s%s%s", spath,
376 *relpath == '\0' ? "" : "/",
377 relpath) == -1)
378 goto childerr;
380 argv[0] = argv[1] = ex;
382 /* fix the env */
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", 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));
403 execvp(ex, argv);
404 goto childerr;
407 default: /* parent */
408 close(p[1]);
409 close(c->fd);
410 c->fd = p[0];
411 c->child = pid;
412 mark_nonblock(c->fd);
413 c->state = S_SENDING;
414 handle_cgi(fds, c);
415 return 0;
418 err:
419 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
420 return 0;
421 goodbye(fds, c);
422 return 0;
424 childerr:
425 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
426 close(p[1]);
427 _exit(1);
430 void
431 cgi_poll_on_child(struct pollfd *fds, struct client *c)
433 int fd;
435 if (c->waiting_on_child)
436 return;
437 c->waiting_on_child = 1;
439 fds->events = POLLIN;
441 fd = fds->fd;
442 fds->fd = c->fd;
443 c->fd = fd;
446 void
447 cgi_poll_on_client(struct pollfd *fds, struct client *c)
449 int fd;
451 if (!c->waiting_on_child)
452 return;
453 c->waiting_on_child = 0;
455 fd = fds->fd;
456 fds->fd = c->fd;
457 c->fd = fd;
460 void
461 handle_cgi(struct pollfd *fds, struct client *c)
463 ssize_t r;
465 /* ensure c->fd is the child and fds->fd the client */
466 cgi_poll_on_client(fds, c);
468 while (1) {
469 if (c->len == 0) {
470 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
471 goto end;
472 if (r == -1) {
473 if (errno == EAGAIN || errno == EWOULDBLOCK) {
474 cgi_poll_on_child(fds, c);
475 return;
477 goto end;
479 c->len = r;
480 c->off = 0;
483 while (c->len > 0) {
484 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
485 case -1:
486 goto end;
488 case TLS_WANT_POLLOUT:
489 fds->events = POLLOUT;
490 return;
492 case TLS_WANT_POLLIN:
493 fds->events = POLLIN;
494 return;
496 default:
497 c->off += r;
498 c->len -= r;
499 break;
504 end:
505 goodbye(fds, c);
508 void
509 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
511 ssize_t ret, len;
513 if (c->fd == -1) {
514 if (!open_file(path, query, fds, c))
515 return;
516 c->state = S_SENDING;
519 len = (c->buf + c->len) - c->i;
521 while (len > 0) {
522 switch (ret = tls_write(c->ctx, c->i, len)) {
523 case -1:
524 LOGE(c, "tls_write: %s", tls_error(c->ctx));
525 goodbye(fds, c);
526 return;
528 case TLS_WANT_POLLIN:
529 fds->events = POLLIN;
530 return;
532 case TLS_WANT_POLLOUT:
533 fds->events = POLLOUT;
534 return;
536 default:
537 c->i += ret;
538 len -= ret;
539 break;
543 goodbye(fds, c);
546 void
547 send_dir(char *path, struct pollfd *fds, struct client *client)
549 char fpath[PATHBUF];
550 size_t len;
552 bzero(fpath, PATHBUF);
554 if (path[0] != '.')
555 fpath[0] = '.';
557 /* this cannot fail since sizeof(fpath) > maxlen of path */
558 strlcat(fpath, path, PATHBUF);
559 len = strlen(fpath);
561 /* add a trailing / in case. */
562 if (fpath[len-1] != '/') {
563 fpath[len] = '/';
566 strlcat(fpath, "index.gmi", sizeof(fpath));
568 send_file(fpath, NULL, fds, client);
571 void
572 handle_handshake(struct pollfd *fds, struct client *c)
574 switch (tls_handshake(c->ctx)) {
575 case 0: /* success */
576 case -1: /* already handshaked */
577 break;
578 case TLS_WANT_POLLIN:
579 fds->events = POLLIN;
580 return;
581 case TLS_WANT_POLLOUT:
582 fds->events = POLLOUT;
583 return;
584 default:
585 /* unreachable */
586 abort();
589 /* TODO: check SNI here */
590 logs(LOG_DEBUG, c, "client wanted to talk to: %s", tls_conn_servername(c->ctx));
592 c->state = S_OPEN;
593 handle_open_conn(fds, c);
596 void
597 handle_open_conn(struct pollfd *fds, struct client *c)
599 char buf[GEMINI_URL_LEN];
600 const char *parse_err = "invalid request";
601 struct iri iri;
603 bzero(buf, sizeof(buf));
605 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
606 case -1:
607 LOGE(c, "tls_read: %s", tls_error(c->ctx));
608 goodbye(fds, c);
609 return;
611 case TLS_WANT_POLLIN:
612 fds->events = POLLIN;
613 return;
615 case TLS_WANT_POLLOUT:
616 fds->events = POLLOUT;
617 return;
620 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
621 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
622 return;
623 goodbye(fds, c);
624 return;
627 if (strcmp(iri.schema, "gemini")) {
628 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
629 return;
630 goodbye(fds, c);
631 return;
634 LOGI(c, "GET %s%s%s",
635 *iri.path ? iri.path : "/",
636 *iri.query ? "?" : "",
637 *iri.query ? iri.query : "");
639 send_file(iri.path, iri.query, fds, c);
642 void
643 handle(struct pollfd *fds, struct client *client)
645 switch (client->state) {
646 case S_HANDSHAKE:
647 handle_handshake(fds, client);
648 break;
650 case S_OPEN:
651 handle_open_conn(fds, client);
652 break;
654 case S_INITIALIZING:
655 if (!start_reply(fds, client, client->code, client->meta))
656 return;
658 if (client->code != SUCCESS) {
659 /* we don't need a body */
660 goodbye(fds, client);
661 return;
664 client->state = S_SENDING;
666 /* fallthrough */
668 case S_SENDING:
669 if (client->child != -1)
670 handle_cgi(fds, client);
671 else
672 send_file(NULL, NULL, fds, client);
673 break;
675 case S_CLOSING:
676 goodbye(fds, client);
677 break;
679 default:
680 /* unreachable */
681 abort();
685 void
686 mark_nonblock(int fd)
688 int flags;
690 if ((flags = fcntl(fd, F_GETFL)) == -1)
691 fatal("fcntl(F_GETFL): %s", strerror(errno));
692 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
693 fatal("fcntl(F_SETFL): %s", strerror(errno));
696 int
697 make_socket(int port, int family)
699 int sock, v;
700 struct sockaddr_in addr4;
701 struct sockaddr_in6 addr6;
702 struct sockaddr *addr;
703 socklen_t len;
705 switch (family) {
706 case AF_INET:
707 bzero(&addr4, sizeof(addr4));
708 addr4.sin_family = family;
709 addr4.sin_port = htons(port);
710 addr4.sin_addr.s_addr = INADDR_ANY;
711 addr = (struct sockaddr*)&addr4;
712 len = sizeof(addr4);
713 break;
715 case AF_INET6:
716 bzero(&addr6, sizeof(addr6));
717 addr6.sin6_family = AF_INET6;
718 addr6.sin6_port = htons(port);
719 addr6.sin6_addr = in6addr_any;
720 addr = (struct sockaddr*)&addr6;
721 len = sizeof(addr6);
722 break;
724 default:
725 /* unreachable */
726 abort();
729 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
730 fatal("socket: %s", strerror(errno));
732 v = 1;
733 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
734 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
736 v = 1;
737 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
738 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
740 mark_nonblock(sock);
742 if (bind(sock, addr, len) == -1)
743 fatal("bind: %s", strerror(errno));
745 if (listen(sock, 16) == -1)
746 fatal("listen: %s", strerror(errno));
748 return sock;
751 void
752 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
754 int i, fd;
755 struct sockaddr_storage addr;
756 socklen_t len;
758 len = sizeof(addr);
759 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
760 if (errno == EWOULDBLOCK)
761 return;
762 fatal("accept: %s", strerror(errno));
765 mark_nonblock(fd);
767 for (i = 0; i < MAX_USERS; ++i) {
768 if (fds[i].fd == -1) {
769 bzero(&clients[i], sizeof(struct client));
770 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
771 break; /* goodbye fd! */
773 fds[i].fd = fd;
774 fds[i].events = POLLIN;
776 clients[i].state = S_HANDSHAKE;
777 clients[i].fd = -1;
778 clients[i].child = -1;
779 clients[i].buf = MAP_FAILED;
780 clients[i].af = AF_INET;
781 clients[i].addr = addr;
783 connected_clients++;
784 return;
788 close(fd);
791 void
792 goodbye(struct pollfd *pfd, struct client *c)
794 ssize_t ret;
796 c->state = S_CLOSING;
798 ret = tls_close(c->ctx);
799 if (ret == TLS_WANT_POLLIN) {
800 pfd->events = POLLIN;
801 return;
803 if (ret == TLS_WANT_POLLOUT) {
804 pfd->events = POLLOUT;
805 return;
808 connected_clients--;
810 tls_free(c->ctx);
811 c->ctx = NULL;
813 if (c->buf != MAP_FAILED)
814 munmap(c->buf, c->len);
816 if (c->fd != -1)
817 close(c->fd);
819 close(pfd->fd);
820 pfd->fd = -1;
823 void
824 loop(struct tls *ctx, int sock4, int sock6)
826 int i;
827 struct client clients[MAX_USERS];
828 struct pollfd fds[MAX_USERS];
830 for (i = 0; i < MAX_USERS; ++i) {
831 fds[i].fd = -1;
832 fds[i].events = POLLIN;
833 bzero(&clients[i], sizeof(struct client));
836 fds[0].fd = sock4;
837 fds[1].fd = sock6;
839 for (;;) {
840 if (poll(fds, MAX_USERS, INFTIM) == -1) {
841 if (errno == EINTR) {
842 warnx("connected clients: %d",
843 connected_clients);
844 continue;
846 fatal("poll: %s", strerror(errno));
849 for (i = 0; i < MAX_USERS; i++) {
850 if (fds[i].revents == 0)
851 continue;
853 if (fds[i].revents & (POLLERR|POLLNVAL))
854 fatal("bad fd %d: %s", fds[i].fd,
855 strerror(errno));
857 if (fds[i].revents & POLLHUP) {
858 /* fds[i] may be the fd of the stdin
859 * of a cgi script that has exited. */
860 if (!clients[i].waiting_on_child) {
861 goodbye(&fds[i], &clients[i]);
862 continue;
866 if (fds[i].fd == sock4)
867 do_accept(sock4, ctx, fds, clients);
868 else if (fds[i].fd == sock6)
869 do_accept(sock6, ctx, fds, clients);
870 else
871 handle(&fds[i], &clients[i]);
876 char *
877 absolutify_path(const char *path)
879 char *wd, *r;
881 if (*path == '/')
882 return strdup(path);
884 wd = getwd(NULL);
885 if (asprintf(&r, "%s/%s", wd, path) == -1)
886 err(1, "asprintf");
887 free(wd);
888 return r;
891 void
892 usage(const char *me)
894 fprintf(stderr,
895 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
896 "[-l logfile] [-p port] [-x cgi-bin]\n",
897 me);
900 int
901 main(int argc, char **argv)
903 const char *cert = "cert.pem", *key = "key.pem";
904 struct tls *ctx = NULL;
905 struct tls_config *conf;
906 int sock4, sock6, enable_ipv6, ch;
907 connected_clients = 0;
909 if ((dir = absolutify_path("docs")) == NULL)
910 err(1, "absolutify_path");
912 cgi = NULL;
913 port = 1965;
914 foreground = 0;
915 enable_ipv6 = 0;
917 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
918 switch (ch) {
919 case '6':
920 enable_ipv6 = 1;
921 break;
923 case 'c':
924 cert = optarg;
925 break;
927 case 'd':
928 free((char*)dir);
929 if ((dir = absolutify_path(optarg)) == NULL)
930 err(1, "absolutify_path");
931 break;
933 case 'f':
934 foreground = 1;
935 break;
937 case 'h':
938 usage(*argv);
939 return 0;
941 case 'k':
942 key = optarg;
943 break;
945 case 'p': {
946 char *ep;
947 long lval;
949 errno = 0;
950 lval = strtol(optarg, &ep, 10);
951 if (optarg[0] == '\0' || *ep != '\0')
952 err(1, "not a number: %s", optarg);
953 if (lval < 0 || lval > UINT16_MAX)
954 err(1, "port number out of range: %s", optarg);
955 port = lval;
956 break;
959 case 'x':
960 cgi = optarg;
961 break;
963 default:
964 usage(*argv);
965 return 1;
969 signal(SIGPIPE, SIG_IGN);
970 signal(SIGCHLD, SIG_IGN);
972 #ifdef SIGINFO
973 signal(SIGINFO, sig_handler);
974 #endif
975 signal(SIGUSR2, sig_handler);
977 if (!foreground)
978 signal(SIGHUP, SIG_IGN);
980 if ((conf = tls_config_new()) == NULL)
981 err(1, "tls_config_new");
983 /* optionally accept client certs, but don't try to verify them */
984 tls_config_verify_client_optional(conf);
985 tls_config_insecure_noverifycert(conf);
987 if (tls_config_set_protocols(conf,
988 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
989 err(1, "tls_config_set_protocols");
991 if (tls_config_set_cert_file(conf, cert) == -1)
992 err(1, "tls_config_set_cert_file: %s", cert);
994 if (tls_config_set_key_file(conf, key) == -1)
995 err(1, "tls_config_set_key_file: %s", key);
997 if ((ctx = tls_server()) == NULL)
998 err(1, "tls_server");
1000 if (tls_configure(ctx, conf) == -1)
1001 errx(1, "tls_configure: %s", tls_error(ctx));
1003 sock4 = make_socket(port, AF_INET);
1004 if (enable_ipv6)
1005 sock6 = make_socket(port, AF_INET6);
1006 else
1007 sock6 = -1;
1009 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
1010 err(1, "open: %s", dir);
1012 if (!foreground && daemon(0, 1) == -1)
1013 exit(1);
1015 if (unveil(dir, "rx") == -1)
1016 err(1, "unveil");
1018 if (pledge("stdio rpath inet proc exec", NULL) == -1)
1019 err(1, "pledge");
1021 /* drop proc and exec if cgi isn't enabled */
1022 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
1023 err(1, "pledge");
1025 loop(ctx, sock4, sock6);
1027 close(sock4);
1028 close(sock6);
1029 tls_free(ctx);
1030 tls_config_free(conf);
1032 return 0;