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 static inline void __dead
75 fatal(const char *fmt, ...)
76 {
77 va_list ap;
79 va_start(ap, fmt);
81 if (foreground) {
82 vfprintf(stderr, fmt, ap);
83 fprintf(stderr, "\n");
84 } else
85 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
87 va_end(ap);
88 exit(1);
89 }
91 __attribute__ ((format (printf, 3, 4)))
92 static inline void
93 logs(int priority, struct client *c,
94 const char *fmt, ...)
95 {
96 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
97 char *fmted, *s;
98 size_t len;
99 int ec;
100 va_list ap;
102 va_start(ap, fmt);
104 len = sizeof(c->addr);
105 ec = getnameinfo((struct sockaddr*)&c->addr, len,
106 hbuf, sizeof(hbuf),
107 sbuf, sizeof(sbuf),
108 NI_NUMERICHOST | NI_NUMERICSERV);
109 if (ec != 0)
110 fatal("getnameinfo: %s", gai_strerror(ec));
112 if (vasprintf(&fmted, fmt, ap) == -1)
113 fatal("vasprintf: %s", strerror(errno));
115 if (foreground)
116 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
117 else {
118 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
119 fatal("asprintf: %s", strerror(errno));
120 syslog(priority | LOG_DAEMON, "%s", s);
121 free(s);
124 free(fmted);
126 va_end(ap);
129 void
130 sig_handler(int sig)
132 (void)sig;
135 int
136 starts_with(const char *str, const char *prefix)
138 size_t i;
140 for (i = 0; prefix[i] != '\0'; ++i)
141 if (str[i] != prefix[i])
142 return 0;
143 return 1;
146 int
147 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
149 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
150 int len;
151 int ret;
153 client->code = code;
154 client->meta = reason;
155 client->state = S_INITIALIZING;
157 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
158 assert(len < (int)sizeof(buf));
159 ret = tls_write(client->ctx, buf, len);
160 if (ret == TLS_WANT_POLLIN) {
161 pfd->events = POLLIN;
162 return 0;
165 if (ret == TLS_WANT_POLLOUT) {
166 pfd->events = POLLOUT;
167 return 0;
170 return 1;
173 ssize_t
174 filesize(int fd)
176 ssize_t len;
178 if ((len = lseek(fd, 0, SEEK_END)) == -1)
179 return -1;
180 if (lseek(fd, 0, SEEK_SET) == -1)
181 return -1;
182 return len;
185 const char *
186 path_ext(const char *path)
188 const char *end;
190 end = path + strlen(path)-1; /* the last byte before the NUL */
191 for (; end != path; --end) {
192 if (*end == '.')
193 return end+1;
194 if (*end == '/')
195 break;
198 return NULL;
201 const char *
202 mime(const char *path)
204 const char *ext, *def = "application/octet-stream";
205 struct etm *t;
207 if ((ext = path_ext(path)) == NULL)
208 return def;
210 for (t = filetypes; t->mime != NULL; ++t)
211 if (!strcmp(ext, t->ext))
212 return t->mime;
214 return def;
217 int
218 check_path(struct client *c, const char *path, int *fd)
220 struct stat sb;
222 assert(path != NULL);
223 if ((*fd = openat(dirfd, *path ? path : ".",
224 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
225 return FILE_MISSING;
228 if (fstat(*fd, &sb) == -1) {
229 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
230 return FILE_MISSING;
233 if (S_ISDIR(sb.st_mode))
234 return FILE_DIRECTORY;
236 if (sb.st_mode & S_IXUSR)
237 return FILE_EXECUTABLE;
239 return FILE_EXISTS;
242 /*
243 * the inverse of this algorithm, i.e. starting from the start of the
244 * path + strlen(cgi), and checking if each component, should be
245 * faster. But it's tedious to write. This does the opposite: starts
246 * from the end and strip one component at a time, until either an
247 * executable is found or we emptied the path.
248 */
249 int
250 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
252 char *end;
253 end = strchr(path, '\0');
255 /* NB: assume CGI is enabled and path matches cgi */
257 while (end > path) {
258 /* go up one level. UNIX paths are simple and POSIX
259 * dirname, with its ambiguities on if the given path
260 * is changed or not, gives me headaches. */
261 while (*end != '/')
262 end--;
263 *end = '\0';
265 switch (check_path(c, path, &c->fd)) {
266 case FILE_EXECUTABLE:
267 return start_cgi(path, end+1, query, fds,c);
268 case FILE_MISSING:
269 break;
270 default:
271 goto err;
274 *end = '/';
275 end--;
278 err:
279 if (!start_reply(fds, c, NOT_FOUND, "not found"))
280 return 0;
281 goodbye(fds, c);
282 return 0;
286 int
287 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
289 switch (check_path(c, fpath, &c->fd)) {
290 case FILE_EXECUTABLE:
291 if (cgi != NULL && starts_with(fpath, cgi))
292 return start_cgi(fpath, "", query, fds, c);
294 /* fallthrough */
296 case FILE_EXISTS:
297 if ((c->len = filesize(c->fd)) == -1) {
298 LOGE(c, "failed to get file size for %s", fpath);
299 goodbye(fds, c);
300 return 0;
303 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
304 c->fd, 0)) == MAP_FAILED) {
305 warn("mmap: %s", fpath);
306 goodbye(fds, c);
307 return 0;
309 c->i = c->buf;
310 return start_reply(fds, c, SUCCESS, mime(fpath));
312 case FILE_DIRECTORY:
313 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
314 close(c->fd);
315 c->fd = -1;
316 send_dir(fpath, fds, c);
317 return 0;
319 case FILE_MISSING:
320 if (cgi != NULL && starts_with(fpath, cgi))
321 return check_for_cgi(fpath, query, fds, c);
323 if (!start_reply(fds, c, NOT_FOUND, "not found"))
324 return 0;
325 goodbye(fds, c);
326 return 0;
328 default:
329 /* unreachable */
330 abort();
334 int
335 start_cgi(const char *spath, const char *relpath, const char *query,
336 struct pollfd *fds, struct client *c)
338 pid_t pid;
339 int p[2]; /* read end, write end */
341 if (pipe(p) == -1)
342 goto err;
344 switch (pid = fork()) {
345 case -1:
346 goto err;
348 case 0: { /* child */
349 char *ex, *requri, *portno;
350 char addr[NI_MAXHOST];
351 char *argv[] = { NULL, NULL, NULL };
352 int ec;
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 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
362 addr, sizeof(addr),
363 NULL, 0,
364 NI_NUMERICHOST | NI_NUMERICSERV);
365 if (ec != 0)
366 goto childerr;
368 if (asprintf(&portno, "%d", port) == -1)
369 goto childerr;
371 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
372 goto childerr;
374 if (asprintf(&requri, "%s%s%s", spath,
375 *relpath == '\0' ? "" : "/",
376 relpath) == -1)
377 goto childerr;
379 argv[0] = argv[1] = ex;
381 /* fix the env */
382 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
383 safe_setenv("SERVER_SOFTWARE", "gmid");
384 safe_setenv("SERVER_PORT", portno);
385 /* setenv("SERVER_NAME", "", 1); */
386 safe_setenv("SCRIPT_NAME", spath);
387 safe_setenv("SCRIPT_EXECUTABLE", ex);
388 safe_setenv("REQUEST_URI", requri);
389 safe_setenv("REQUEST_RELATIVE", relpath);
390 safe_setenv("QUERY_STRING", query);
391 safe_setenv("REMOTE_HOST", addr);
392 safe_setenv("REMOTE_ADDR", addr);
393 safe_setenv("DOCUMENT_ROOT", dir);
395 if (tls_peer_cert_provided(c->ctx)) {
396 safe_setenv("AUTH_TYPE", "Certificate");
397 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
398 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
399 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
402 execvp(ex, argv);
403 goto childerr;
406 default: /* parent */
407 close(p[1]);
408 close(c->fd);
409 c->fd = p[0];
410 c->child = pid;
411 mark_nonblock(c->fd);
412 c->state = S_SENDING;
413 handle_cgi(fds, c);
414 return 0;
417 err:
418 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
419 return 0;
420 goodbye(fds, c);
421 return 0;
423 childerr:
424 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
425 close(p[1]);
426 _exit(1);
429 void
430 cgi_poll_on_child(struct pollfd *fds, struct client *c)
432 int fd;
434 if (c->waiting_on_child)
435 return;
436 c->waiting_on_child = 1;
438 fds->events = POLLIN;
440 fd = fds->fd;
441 fds->fd = c->fd;
442 c->fd = fd;
445 void
446 cgi_poll_on_client(struct pollfd *fds, struct client *c)
448 int fd;
450 if (!c->waiting_on_child)
451 return;
452 c->waiting_on_child = 0;
454 fd = fds->fd;
455 fds->fd = c->fd;
456 c->fd = fd;
459 void
460 handle_cgi(struct pollfd *fds, struct client *c)
462 ssize_t r;
464 /* ensure c->fd is the child and fds->fd the client */
465 cgi_poll_on_client(fds, c);
467 while (1) {
468 if (c->len == 0) {
469 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
470 goto end;
471 if (r == -1) {
472 if (errno == EAGAIN || errno == EWOULDBLOCK) {
473 cgi_poll_on_child(fds, c);
474 return;
476 goto end;
478 c->len = r;
479 c->off = 0;
482 while (c->len > 0) {
483 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
484 case -1:
485 goto end;
487 case TLS_WANT_POLLOUT:
488 fds->events = POLLOUT;
489 return;
491 case TLS_WANT_POLLIN:
492 fds->events = POLLIN;
493 return;
495 default:
496 c->off += r;
497 c->len -= r;
498 break;
503 end:
504 goodbye(fds, c);
507 void
508 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
510 ssize_t ret, len;
512 if (c->fd == -1) {
513 if (!open_file(path, query, fds, c))
514 return;
515 c->state = S_SENDING;
518 len = (c->buf + c->len) - c->i;
520 while (len > 0) {
521 switch (ret = tls_write(c->ctx, c->i, len)) {
522 case -1:
523 LOGE(c, "tls_write: %s", tls_error(c->ctx));
524 goodbye(fds, c);
525 return;
527 case TLS_WANT_POLLIN:
528 fds->events = POLLIN;
529 return;
531 case TLS_WANT_POLLOUT:
532 fds->events = POLLOUT;
533 return;
535 default:
536 c->i += ret;
537 len -= ret;
538 break;
542 goodbye(fds, c);
545 void
546 send_dir(char *path, struct pollfd *fds, struct client *client)
548 char fpath[PATHBUF];
549 size_t len;
551 bzero(fpath, PATHBUF);
553 if (path[0] != '.')
554 fpath[0] = '.';
556 /* this cannot fail since sizeof(fpath) > maxlen of path */
557 strlcat(fpath, path, PATHBUF);
558 len = strlen(fpath);
560 /* add a trailing / in case. */
561 if (fpath[len-1] != '/') {
562 fpath[len] = '/';
565 strlcat(fpath, "index.gmi", sizeof(fpath));
567 send_file(fpath, NULL, fds, client);
570 void
571 handle(struct pollfd *fds, struct client *client)
573 char buf[GEMINI_URL_LEN];
574 const char *parse_err;
575 struct iri iri;
577 switch (client->state) {
578 case S_OPEN:
579 bzero(buf, GEMINI_URL_LEN);
580 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
581 case -1:
582 LOGE(client, "tls_read: %s", tls_error(client->ctx));
583 goodbye(fds, client);
584 return;
586 case TLS_WANT_POLLIN:
587 fds->events = POLLIN;
588 return;
590 case TLS_WANT_POLLOUT:
591 fds->events = POLLOUT;
592 return;
595 parse_err = "invalid request";
596 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
597 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
598 return;
599 goodbye(fds, client);
600 return;
603 LOGI(client, "GET %s%s%s",
604 *iri.path ? iri.path : "/",
605 *iri.query ? "?" : "",
606 *iri.query ? iri.query : "");
608 send_file(iri.path, iri.query, fds, client);
609 break;
611 case S_INITIALIZING:
612 if (!start_reply(fds, client, client->code, client->meta))
613 return;
615 if (client->code != SUCCESS) {
616 /* we don't need a body */
617 goodbye(fds, client);
618 return;
621 client->state = S_SENDING;
623 /* fallthrough */
625 case S_SENDING:
626 if (client->child != -1)
627 handle_cgi(fds, client);
628 else
629 send_file(NULL, NULL, fds, client);
630 break;
632 case S_CLOSING:
633 goodbye(fds, client);
634 break;
636 default:
637 /* unreachable */
638 abort();
642 void
643 mark_nonblock(int fd)
645 int flags;
647 if ((flags = fcntl(fd, F_GETFL)) == -1)
648 fatal("fcntl(F_GETFL): %s", strerror(errno));
649 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
650 fatal("fcntl(F_SETFL): %s", strerror(errno));
653 int
654 make_socket(int port, int family)
656 int sock, v;
657 struct sockaddr_in addr4;
658 struct sockaddr_in6 addr6;
659 struct sockaddr *addr;
660 socklen_t len;
662 switch (family) {
663 case AF_INET:
664 bzero(&addr4, sizeof(addr4));
665 addr4.sin_family = family;
666 addr4.sin_port = htons(port);
667 addr4.sin_addr.s_addr = INADDR_ANY;
668 addr = (struct sockaddr*)&addr4;
669 len = sizeof(addr4);
670 break;
672 case AF_INET6:
673 bzero(&addr6, sizeof(addr6));
674 addr6.sin6_family = AF_INET6;
675 addr6.sin6_port = htons(port);
676 addr6.sin6_addr = in6addr_any;
677 addr = (struct sockaddr*)&addr6;
678 len = sizeof(addr6);
679 break;
681 default:
682 /* unreachable */
683 abort();
686 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
687 fatal("socket: %s", strerror(errno));
689 v = 1;
690 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
691 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
693 v = 1;
694 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
695 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
697 mark_nonblock(sock);
699 if (bind(sock, addr, len) == -1)
700 fatal("bind: %s", strerror(errno));
702 if (listen(sock, 16) == -1)
703 fatal("listen: %s", strerror(errno));
705 return sock;
708 void
709 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
711 int i, fd;
712 struct sockaddr_storage addr;
713 socklen_t len;
715 len = sizeof(addr);
716 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
717 if (errno == EWOULDBLOCK)
718 return;
719 fatal("accept: %s", strerror(errno));
722 mark_nonblock(fd);
724 for (i = 0; i < MAX_USERS; ++i) {
725 if (fds[i].fd == -1) {
726 bzero(&clients[i], sizeof(struct client));
727 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
728 break; /* goodbye fd! */
730 fds[i].fd = fd;
731 fds[i].events = POLLIN;
733 clients[i].state = S_OPEN;
734 clients[i].fd = -1;
735 clients[i].child = -1;
736 clients[i].buf = MAP_FAILED;
737 clients[i].af = AF_INET;
738 clients[i].addr = addr;
740 connected_clients++;
741 return;
745 close(fd);
748 void
749 goodbye(struct pollfd *pfd, struct client *c)
751 ssize_t ret;
753 c->state = S_CLOSING;
755 ret = tls_close(c->ctx);
756 if (ret == TLS_WANT_POLLIN) {
757 pfd->events = POLLIN;
758 return;
760 if (ret == TLS_WANT_POLLOUT) {
761 pfd->events = POLLOUT;
762 return;
765 connected_clients--;
767 tls_free(c->ctx);
768 c->ctx = NULL;
770 if (c->buf != MAP_FAILED)
771 munmap(c->buf, c->len);
773 if (c->fd != -1)
774 close(c->fd);
776 close(pfd->fd);
777 pfd->fd = -1;
780 void
781 loop(struct tls *ctx, int sock4, int sock6)
783 int i;
784 struct client clients[MAX_USERS];
785 struct pollfd fds[MAX_USERS];
787 for (i = 0; i < MAX_USERS; ++i) {
788 fds[i].fd = -1;
789 fds[i].events = POLLIN;
790 bzero(&clients[i], sizeof(struct client));
793 fds[0].fd = sock4;
794 fds[1].fd = sock6;
796 for (;;) {
797 if (poll(fds, MAX_USERS, INFTIM) == -1) {
798 if (errno == EINTR) {
799 warnx("connected clients: %d",
800 connected_clients);
801 continue;
803 fatal("poll: %s", strerror(errno));
806 for (i = 0; i < MAX_USERS; i++) {
807 if (fds[i].revents == 0)
808 continue;
810 if (fds[i].revents & (POLLERR|POLLNVAL))
811 fatal("bad fd %d: %s", fds[i].fd,
812 strerror(errno));
814 if (fds[i].revents & POLLHUP) {
815 /* fds[i] may be the fd of the stdin
816 * of a cgi script that has exited. */
817 if (!clients[i].waiting_on_child) {
818 goodbye(&fds[i], &clients[i]);
819 continue;
823 if (fds[i].fd == sock4)
824 do_accept(sock4, ctx, fds, clients);
825 else if (fds[i].fd == sock6)
826 do_accept(sock6, ctx, fds, clients);
827 else
828 handle(&fds[i], &clients[i]);
833 char *
834 absolutify_path(const char *path)
836 char *wd, *r;
838 if (*path == '/')
839 return strdup(path);
841 wd = getwd(NULL);
842 if (asprintf(&r, "%s/%s", wd, path) == -1)
843 err(1, "asprintf");
844 free(wd);
845 return r;
848 void
849 usage(const char *me)
851 fprintf(stderr,
852 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
853 "[-l logfile] [-p port] [-x cgi-bin]\n",
854 me);
857 int
858 main(int argc, char **argv)
860 const char *cert = "cert.pem", *key = "key.pem";
861 struct tls *ctx = NULL;
862 struct tls_config *conf;
863 int sock4, sock6, enable_ipv6, ch;
864 connected_clients = 0;
866 if ((dir = absolutify_path("docs")) == NULL)
867 err(1, "absolutify_path");
869 cgi = NULL;
870 port = 1965;
871 foreground = 0;
872 enable_ipv6 = 0;
874 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
875 switch (ch) {
876 case '6':
877 enable_ipv6 = 1;
878 break;
880 case 'c':
881 cert = optarg;
882 break;
884 case 'd':
885 free((char*)dir);
886 if ((dir = absolutify_path(optarg)) == NULL)
887 err(1, "absolutify_path");
888 break;
890 case 'f':
891 foreground = 1;
892 break;
894 case 'h':
895 usage(*argv);
896 return 0;
898 case 'k':
899 key = optarg;
900 break;
902 case 'p': {
903 char *ep;
904 long lval;
906 errno = 0;
907 lval = strtol(optarg, &ep, 10);
908 if (optarg[0] == '\0' || *ep != '\0')
909 err(1, "not a number: %s", optarg);
910 if (lval < 0 || lval > UINT16_MAX)
911 err(1, "port number out of range: %s", optarg);
912 port = lval;
913 break;
916 case 'x':
917 cgi = optarg;
918 break;
920 default:
921 usage(*argv);
922 return 1;
926 signal(SIGPIPE, SIG_IGN);
927 signal(SIGCHLD, SIG_IGN);
929 #ifdef SIGINFO
930 signal(SIGINFO, sig_handler);
931 #endif
932 signal(SIGUSR2, sig_handler);
934 if (!foreground)
935 signal(SIGHUP, SIG_IGN);
937 if ((conf = tls_config_new()) == NULL)
938 err(1, "tls_config_new");
940 /* optionally accept client certs, but don't try to verify them */
941 tls_config_verify_client_optional(conf);
942 tls_config_insecure_noverifycert(conf);
944 if (tls_config_set_protocols(conf,
945 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
946 err(1, "tls_config_set_protocols");
948 if (tls_config_set_cert_file(conf, cert) == -1)
949 err(1, "tls_config_set_cert_file: %s", cert);
951 if (tls_config_set_key_file(conf, key) == -1)
952 err(1, "tls_config_set_key_file: %s", key);
954 if ((ctx = tls_server()) == NULL)
955 err(1, "tls_server");
957 if (tls_configure(ctx, conf) == -1)
958 errx(1, "tls_configure: %s", tls_error(ctx));
960 sock4 = make_socket(port, AF_INET);
961 if (enable_ipv6)
962 sock6 = make_socket(port, AF_INET6);
963 else
964 sock6 = -1;
966 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
967 err(1, "open: %s", dir);
969 if (!foreground && daemon(0, 1) == -1)
970 exit(1);
972 if (unveil(dir, "rx") == -1)
973 err(1, "unveil");
975 if (pledge("stdio rpath inet proc exec", NULL) == -1)
976 err(1, "pledge");
978 /* drop proc and exec if cgi isn't enabled */
979 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
980 err(1, "pledge");
982 loop(ctx, sock4, sock6);
984 close(sock4);
985 close(sock6);
986 tls_free(ctx);
987 tls_config_free(conf);