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/socket.h>
19 #include <sys/stat.h>
21 #include <assert.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <netdb.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <string.h>
31 #include "gmid.h"
33 #define LOGE(c, fmt, ...) logs(LOG_ERR, c, fmt, __VA_ARGS__)
34 #define LOGN(c, fmt, ...) logs(LOG_NOTICE, c, fmt, __VA_ARGS__)
35 #define LOGI(c, fmt, ...) logs(LOG_INFO, c, fmt, __VA_ARGS__)
36 #define LOGD(c, fmt, ...) logs(LOG_DEBUG, c, fmt, __VA_ARGS__)
38 const char *dir, *cgi;
39 int dirfd;
40 int port;
41 int foreground;
42 int connected_clients;
44 struct etm { /* file extension to mime */
45 const char *mime;
46 const char *ext;
47 } filetypes[] = {
48 {"application/pdf", "pdf"},
50 {"image/gif", "gif"},
51 {"image/jpeg", "jpg"},
52 {"image/jpeg", "jpeg"},
53 {"image/png", "png"},
54 {"image/svg+xml", "svg"},
56 {"text/gemini", "gemini"},
57 {"text/gemini", "gmi"},
58 {"text/markdown", "markdown"},
59 {"text/markdown", "md"},
60 {"text/plain", "txt"},
61 {"text/xml", "xml"},
63 {NULL, NULL}
64 };
66 static inline void
67 safe_setenv(const char *name, const char *val)
68 {
69 if (val == NULL)
70 val = "";
71 setenv(name, val, 1);
72 }
74 __attribute__ ((format (printf, 1, 2)))
75 static inline void __dead
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[INET_ADDRSTRLEN];
352 char *argv[] = { NULL, NULL, NULL };
354 close(p[0]);
355 if (dup2(p[1], 1) == -1)
356 goto childerr;
358 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
359 goto childerr;
361 if (asprintf(&portno, "%d", port) == -1)
362 goto childerr;
364 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
365 goto childerr;
367 if (asprintf(&requri, "%s%s%s", spath,
368 *relpath == '\0' ? "" : "/",
369 relpath) == -1)
370 goto childerr;
372 argv[0] = argv[1] = ex;
374 /* fix the env */
375 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
376 safe_setenv("SERVER_SOFTWARE", "gmid");
377 safe_setenv("SERVER_PORT", portno);
378 /* setenv("SERVER_NAME", "", 1); */
379 safe_setenv("SCRIPT_NAME", spath);
380 safe_setenv("SCRIPT_EXECUTABLE", ex);
381 safe_setenv("REQUEST_URI", requri);
382 safe_setenv("REQUEST_RELATIVE", relpath);
383 safe_setenv("QUERY_STRING", query);
384 safe_setenv("REMOTE_HOST", addr);
385 safe_setenv("REMOTE_ADDR", addr);
386 safe_setenv("DOCUMENT_ROOT", dir);
388 if (tls_peer_cert_provided(c->ctx)) {
389 safe_setenv("AUTH_TYPE", "Certificate");
390 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
391 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
392 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
395 execvp(ex, argv);
396 goto childerr;
399 default: /* parent */
400 close(p[1]);
401 close(c->fd);
402 c->fd = p[0];
403 c->child = pid;
404 mark_nonblock(c->fd);
405 c->state = S_SENDING;
406 handle_cgi(fds, c);
407 return 0;
410 err:
411 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
412 return 0;
413 goodbye(fds, c);
414 return 0;
416 childerr:
417 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
418 close(p[1]);
419 _exit(1);
422 void
423 cgi_poll_on_child(struct pollfd *fds, struct client *c)
425 int fd;
427 if (c->waiting_on_child)
428 return;
429 c->waiting_on_child = 1;
431 fds->events = POLLIN;
433 fd = fds->fd;
434 fds->fd = c->fd;
435 c->fd = fd;
438 void
439 cgi_poll_on_client(struct pollfd *fds, struct client *c)
441 int fd;
443 if (!c->waiting_on_child)
444 return;
445 c->waiting_on_child = 0;
447 fd = fds->fd;
448 fds->fd = c->fd;
449 c->fd = fd;
452 void
453 handle_cgi(struct pollfd *fds, struct client *c)
455 ssize_t r;
457 /* ensure c->fd is the child and fds->fd the client */
458 cgi_poll_on_client(fds, c);
460 while (1) {
461 if (c->len == 0) {
462 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
463 goto end;
464 if (r == -1) {
465 if (errno == EAGAIN || errno == EWOULDBLOCK) {
466 cgi_poll_on_child(fds, c);
467 return;
469 goto end;
471 c->len = r;
472 c->off = 0;
475 while (c->len > 0) {
476 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
477 case -1:
478 goto end;
480 case TLS_WANT_POLLOUT:
481 fds->events = POLLOUT;
482 return;
484 case TLS_WANT_POLLIN:
485 fds->events = POLLIN;
486 return;
488 default:
489 c->off += r;
490 c->len -= r;
491 break;
496 end:
497 goodbye(fds, c);
500 void
501 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
503 ssize_t ret, len;
505 if (c->fd == -1) {
506 if (!open_file(path, query, fds, c))
507 return;
508 c->state = S_SENDING;
511 len = (c->buf + c->len) - c->i;
513 while (len > 0) {
514 switch (ret = tls_write(c->ctx, c->i, len)) {
515 case -1:
516 LOGE(c, "tls_write: %s", tls_error(c->ctx));
517 goodbye(fds, c);
518 return;
520 case TLS_WANT_POLLIN:
521 fds->events = POLLIN;
522 return;
524 case TLS_WANT_POLLOUT:
525 fds->events = POLLOUT;
526 return;
528 default:
529 c->i += ret;
530 len -= ret;
531 break;
535 goodbye(fds, c);
538 void
539 send_dir(char *path, struct pollfd *fds, struct client *client)
541 char fpath[PATHBUF];
542 size_t len;
544 bzero(fpath, PATHBUF);
546 if (path[0] != '.')
547 fpath[0] = '.';
549 /* this cannot fail since sizeof(fpath) > maxlen of path */
550 strlcat(fpath, path, PATHBUF);
551 len = strlen(fpath);
553 /* add a trailing / in case. */
554 if (fpath[len-1] != '/') {
555 fpath[len] = '/';
558 strlcat(fpath, "index.gmi", sizeof(fpath));
560 send_file(fpath, NULL, fds, client);
563 void
564 handle(struct pollfd *fds, struct client *client)
566 char buf[GEMINI_URL_LEN];
567 const char *parse_err;
568 struct uri uri;
570 switch (client->state) {
571 case S_OPEN:
572 bzero(buf, GEMINI_URL_LEN);
573 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
574 case -1:
575 LOGE(client, "tls_read: %s", tls_error(client->ctx));
576 goodbye(fds, client);
577 return;
579 case TLS_WANT_POLLIN:
580 fds->events = POLLIN;
581 return;
583 case TLS_WANT_POLLOUT:
584 fds->events = POLLOUT;
585 return;
588 parse_err = "invalid request";
589 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
590 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
591 return;
592 goodbye(fds, client);
593 return;
596 LOGI(client, "GET %s%s%s",
597 *uri.path ? uri.path : "/",
598 *uri.query ? "?" : "",
599 *uri.query ? uri.query : "");
601 send_file(uri.path, uri.query, fds, client);
602 break;
604 case S_INITIALIZING:
605 if (!start_reply(fds, client, client->code, client->meta))
606 return;
608 if (client->code != SUCCESS) {
609 /* we don't need a body */
610 goodbye(fds, client);
611 return;
614 client->state = S_SENDING;
616 /* fallthrough */
618 case S_SENDING:
619 if (client->child != -1)
620 handle_cgi(fds, client);
621 else
622 send_file(NULL, NULL, fds, client);
623 break;
625 case S_CLOSING:
626 goodbye(fds, client);
627 break;
629 default:
630 /* unreachable */
631 abort();
635 void
636 mark_nonblock(int fd)
638 int flags;
640 if ((flags = fcntl(fd, F_GETFL)) == -1)
641 fatal("fcntl(F_GETFL): %s", strerror(errno));
642 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
643 fatal("fcntl(F_SETFL): %s", strerror(errno));
646 int
647 make_socket(int port, int family)
649 int sock, v;
650 struct sockaddr_in addr4;
651 struct sockaddr_in6 addr6;
652 struct sockaddr *addr;
653 socklen_t len;
655 switch (family) {
656 case AF_INET:
657 bzero(&addr4, sizeof(addr4));
658 addr4.sin_family = family;
659 addr4.sin_port = htons(port);
660 addr4.sin_addr.s_addr = INADDR_ANY;
661 addr = (struct sockaddr*)&addr4;
662 len = sizeof(addr4);
663 break;
665 case AF_INET6:
666 bzero(&addr6, sizeof(addr6));
667 addr6.sin6_family = AF_INET6;
668 addr6.sin6_port = htons(port);
669 addr6.sin6_addr = in6addr_any;
670 addr = (struct sockaddr*)&addr6;
671 len = sizeof(addr6);
672 break;
674 default:
675 /* unreachable */
676 abort();
679 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
680 fatal("socket: %s", strerror(errno));
682 v = 1;
683 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
684 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
686 v = 1;
687 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
688 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
690 mark_nonblock(sock);
692 if (bind(sock, addr, len) == -1)
693 fatal("bind: %s", strerror(errno));
695 if (listen(sock, 16) == -1)
696 fatal("listen: %s", strerror(errno));
698 return sock;
701 void
702 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
704 int i, fd;
705 struct sockaddr_storage addr;
706 socklen_t len;
708 len = sizeof(addr);
709 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
710 if (errno == EWOULDBLOCK)
711 return;
712 fatal("accept: %s", strerror(errno));
715 mark_nonblock(fd);
717 for (i = 0; i < MAX_USERS; ++i) {
718 if (fds[i].fd == -1) {
719 bzero(&clients[i], sizeof(struct client));
720 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
721 break; /* goodbye fd! */
723 fds[i].fd = fd;
724 fds[i].events = POLLIN;
726 clients[i].state = S_OPEN;
727 clients[i].fd = -1;
728 clients[i].child = -1;
729 clients[i].buf = MAP_FAILED;
730 clients[i].af = AF_INET;
731 clients[i].addr = addr;
733 connected_clients++;
734 return;
738 close(fd);
741 void
742 goodbye(struct pollfd *pfd, struct client *c)
744 ssize_t ret;
746 c->state = S_CLOSING;
748 ret = tls_close(c->ctx);
749 if (ret == TLS_WANT_POLLIN) {
750 pfd->events = POLLIN;
751 return;
753 if (ret == TLS_WANT_POLLOUT) {
754 pfd->events = POLLOUT;
755 return;
758 connected_clients--;
760 tls_free(c->ctx);
761 c->ctx = NULL;
763 if (c->buf != MAP_FAILED)
764 munmap(c->buf, c->len);
766 if (c->fd != -1)
767 close(c->fd);
769 close(pfd->fd);
770 pfd->fd = -1;
773 void
774 loop(struct tls *ctx, int sock)
776 int i;
777 struct client clients[MAX_USERS];
778 struct pollfd fds[MAX_USERS];
780 for (i = 0; i < MAX_USERS; ++i) {
781 fds[i].fd = -1;
782 fds[i].events = POLLIN;
783 bzero(&clients[i], sizeof(struct client));
786 fds[0].fd = sock;
788 for (;;) {
789 if (poll(fds, MAX_USERS, INFTIM) == -1) {
790 if (errno == EINTR) {
791 warnx("connected clients: %d",
792 connected_clients);
793 continue;
795 fatal("poll: %s", strerror(errno));
798 for (i = 0; i < MAX_USERS; i++) {
799 if (fds[i].revents == 0)
800 continue;
802 if (fds[i].revents & (POLLERR|POLLNVAL))
803 fatal("bad fd %d: %s", fds[i].fd,
804 strerror(errno));
806 if (fds[i].revents & POLLHUP) {
807 /* fds[i] may be the fd of the stdin
808 * of a cgi script that has exited. */
809 if (!clients[i].waiting_on_child) {
810 goodbye(&fds[i], &clients[i]);
811 continue;
815 if (i == 0) { /* new client */
816 do_accept(sock, ctx, fds, clients);
817 continue;
820 handle(&fds[i], &clients[i]);
825 char *
826 absolutify_path(const char *path)
828 char *wd, *r;
830 if (*path == '/')
831 return strdup(path);
833 wd = getwd(NULL);
834 if (asprintf(&r, "%s/%s", wd, path) == -1)
835 err(1, "asprintf");
836 free(wd);
837 return r;
840 void
841 usage(const char *me)
843 fprintf(stderr,
844 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
845 "[-l logfile] [-p port] [-x cgi-bin]\n",
846 me);
849 int
850 main(int argc, char **argv)
852 const char *cert = "cert.pem", *key = "key.pem";
853 struct tls *ctx = NULL;
854 struct tls_config *conf;
855 int sock, ch;
856 connected_clients = 0;
858 if ((dir = absolutify_path("docs")) == NULL)
859 err(1, "absolutify_path");
861 cgi = NULL;
862 port = 1965;
863 foreground = 0;
865 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
866 switch (ch) {
867 case 'c':
868 cert = optarg;
869 break;
871 case 'd':
872 free((char*)dir);
873 if ((dir = absolutify_path(optarg)) == NULL)
874 err(1, "absolutify_path");
875 break;
877 case 'f':
878 foreground = 1;
879 break;
881 case 'h':
882 usage(*argv);
883 return 0;
885 case 'k':
886 key = optarg;
887 break;
889 case 'p': {
890 char *ep;
891 long lval;
893 errno = 0;
894 lval = strtol(optarg, &ep, 10);
895 if (optarg[0] == '\0' || *ep != '\0')
896 err(1, "not a number: %s", optarg);
897 if (lval < 0 || lval > UINT16_MAX)
898 err(1, "port number out of range: %s", optarg);
899 port = lval;
900 break;
903 case 'x':
904 cgi = optarg;
905 break;
907 default:
908 usage(*argv);
909 return 1;
913 signal(SIGPIPE, SIG_IGN);
914 signal(SIGCHLD, SIG_IGN);
916 #ifdef SIGINFO
917 signal(SIGINFO, sig_handler);
918 #endif
919 signal(SIGUSR2, sig_handler);
921 if (!foreground)
922 signal(SIGHUP, SIG_IGN);
924 if ((conf = tls_config_new()) == NULL)
925 err(1, "tls_config_new");
927 /* optionally accept client certs, but don't try to verify them */
928 tls_config_verify_client_optional(conf);
929 tls_config_insecure_noverifycert(conf);
931 if (tls_config_set_protocols(conf,
932 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
933 err(1, "tls_config_set_protocols");
935 if (tls_config_set_cert_file(conf, cert) == -1)
936 err(1, "tls_config_set_cert_file: %s", cert);
938 if (tls_config_set_key_file(conf, key) == -1)
939 err(1, "tls_config_set_key_file: %s", key);
941 if ((ctx = tls_server()) == NULL)
942 err(1, "tls_server");
944 if (tls_configure(ctx, conf) == -1)
945 errx(1, "tls_configure: %s", tls_error(ctx));
947 sock = make_socket(port, AF_INET);
949 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
950 err(1, "open: %s", dir);
952 if (!foreground && daemon(0, 1) == -1)
953 exit(1);
955 if (unveil(dir, "rx") == -1)
956 err(1, "unveil");
958 if (pledge("stdio rpath inet proc exec", NULL) == -1)
959 err(1, "pledge");
961 /* drop proc and exec if cgi isn't enabled */
962 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
963 err(1, "pledge");
965 loop(ctx, sock);
967 close(sock);
968 tls_free(ctx);
969 tls_config_free(conf);