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 if (strcmp(iri.schema, "gemini")) {
604 if (!start_reply(fds, client, PROXY_REFUSED, "won't proxy request"))
605 return;
606 goodbye(fds, client);
607 return;
610 LOGI(client, "GET %s%s%s",
611 *iri.path ? iri.path : "/",
612 *iri.query ? "?" : "",
613 *iri.query ? iri.query : "");
615 send_file(iri.path, iri.query, fds, client);
616 break;
618 case S_INITIALIZING:
619 if (!start_reply(fds, client, client->code, client->meta))
620 return;
622 if (client->code != SUCCESS) {
623 /* we don't need a body */
624 goodbye(fds, client);
625 return;
628 client->state = S_SENDING;
630 /* fallthrough */
632 case S_SENDING:
633 if (client->child != -1)
634 handle_cgi(fds, client);
635 else
636 send_file(NULL, NULL, fds, client);
637 break;
639 case S_CLOSING:
640 goodbye(fds, client);
641 break;
643 default:
644 /* unreachable */
645 abort();
649 void
650 mark_nonblock(int fd)
652 int flags;
654 if ((flags = fcntl(fd, F_GETFL)) == -1)
655 fatal("fcntl(F_GETFL): %s", strerror(errno));
656 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
657 fatal("fcntl(F_SETFL): %s", strerror(errno));
660 int
661 make_socket(int port, int family)
663 int sock, v;
664 struct sockaddr_in addr4;
665 struct sockaddr_in6 addr6;
666 struct sockaddr *addr;
667 socklen_t len;
669 switch (family) {
670 case AF_INET:
671 bzero(&addr4, sizeof(addr4));
672 addr4.sin_family = family;
673 addr4.sin_port = htons(port);
674 addr4.sin_addr.s_addr = INADDR_ANY;
675 addr = (struct sockaddr*)&addr4;
676 len = sizeof(addr4);
677 break;
679 case AF_INET6:
680 bzero(&addr6, sizeof(addr6));
681 addr6.sin6_family = AF_INET6;
682 addr6.sin6_port = htons(port);
683 addr6.sin6_addr = in6addr_any;
684 addr = (struct sockaddr*)&addr6;
685 len = sizeof(addr6);
686 break;
688 default:
689 /* unreachable */
690 abort();
693 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
694 fatal("socket: %s", strerror(errno));
696 v = 1;
697 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
698 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
700 v = 1;
701 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
702 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
704 mark_nonblock(sock);
706 if (bind(sock, addr, len) == -1)
707 fatal("bind: %s", strerror(errno));
709 if (listen(sock, 16) == -1)
710 fatal("listen: %s", strerror(errno));
712 return sock;
715 void
716 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
718 int i, fd;
719 struct sockaddr_storage addr;
720 socklen_t len;
722 len = sizeof(addr);
723 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
724 if (errno == EWOULDBLOCK)
725 return;
726 fatal("accept: %s", strerror(errno));
729 mark_nonblock(fd);
731 for (i = 0; i < MAX_USERS; ++i) {
732 if (fds[i].fd == -1) {
733 bzero(&clients[i], sizeof(struct client));
734 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
735 break; /* goodbye fd! */
737 fds[i].fd = fd;
738 fds[i].events = POLLIN;
740 clients[i].state = S_OPEN;
741 clients[i].fd = -1;
742 clients[i].child = -1;
743 clients[i].buf = MAP_FAILED;
744 clients[i].af = AF_INET;
745 clients[i].addr = addr;
747 connected_clients++;
748 return;
752 close(fd);
755 void
756 goodbye(struct pollfd *pfd, struct client *c)
758 ssize_t ret;
760 c->state = S_CLOSING;
762 ret = tls_close(c->ctx);
763 if (ret == TLS_WANT_POLLIN) {
764 pfd->events = POLLIN;
765 return;
767 if (ret == TLS_WANT_POLLOUT) {
768 pfd->events = POLLOUT;
769 return;
772 connected_clients--;
774 tls_free(c->ctx);
775 c->ctx = NULL;
777 if (c->buf != MAP_FAILED)
778 munmap(c->buf, c->len);
780 if (c->fd != -1)
781 close(c->fd);
783 close(pfd->fd);
784 pfd->fd = -1;
787 void
788 loop(struct tls *ctx, int sock4, int sock6)
790 int i;
791 struct client clients[MAX_USERS];
792 struct pollfd fds[MAX_USERS];
794 for (i = 0; i < MAX_USERS; ++i) {
795 fds[i].fd = -1;
796 fds[i].events = POLLIN;
797 bzero(&clients[i], sizeof(struct client));
800 fds[0].fd = sock4;
801 fds[1].fd = sock6;
803 for (;;) {
804 if (poll(fds, MAX_USERS, INFTIM) == -1) {
805 if (errno == EINTR) {
806 warnx("connected clients: %d",
807 connected_clients);
808 continue;
810 fatal("poll: %s", strerror(errno));
813 for (i = 0; i < MAX_USERS; i++) {
814 if (fds[i].revents == 0)
815 continue;
817 if (fds[i].revents & (POLLERR|POLLNVAL))
818 fatal("bad fd %d: %s", fds[i].fd,
819 strerror(errno));
821 if (fds[i].revents & POLLHUP) {
822 /* fds[i] may be the fd of the stdin
823 * of a cgi script that has exited. */
824 if (!clients[i].waiting_on_child) {
825 goodbye(&fds[i], &clients[i]);
826 continue;
830 if (fds[i].fd == sock4)
831 do_accept(sock4, ctx, fds, clients);
832 else if (fds[i].fd == sock6)
833 do_accept(sock6, ctx, fds, clients);
834 else
835 handle(&fds[i], &clients[i]);
840 char *
841 absolutify_path(const char *path)
843 char *wd, *r;
845 if (*path == '/')
846 return strdup(path);
848 wd = getwd(NULL);
849 if (asprintf(&r, "%s/%s", wd, path) == -1)
850 err(1, "asprintf");
851 free(wd);
852 return r;
855 void
856 usage(const char *me)
858 fprintf(stderr,
859 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
860 "[-l logfile] [-p port] [-x cgi-bin]\n",
861 me);
864 int
865 main(int argc, char **argv)
867 const char *cert = "cert.pem", *key = "key.pem";
868 struct tls *ctx = NULL;
869 struct tls_config *conf;
870 int sock4, sock6, enable_ipv6, ch;
871 connected_clients = 0;
873 if ((dir = absolutify_path("docs")) == NULL)
874 err(1, "absolutify_path");
876 cgi = NULL;
877 port = 1965;
878 foreground = 0;
879 enable_ipv6 = 0;
881 while ((ch = getopt(argc, argv, "6c:d:fhk:p:x:")) != -1) {
882 switch (ch) {
883 case '6':
884 enable_ipv6 = 1;
885 break;
887 case 'c':
888 cert = optarg;
889 break;
891 case 'd':
892 free((char*)dir);
893 if ((dir = absolutify_path(optarg)) == NULL)
894 err(1, "absolutify_path");
895 break;
897 case 'f':
898 foreground = 1;
899 break;
901 case 'h':
902 usage(*argv);
903 return 0;
905 case 'k':
906 key = optarg;
907 break;
909 case 'p': {
910 char *ep;
911 long lval;
913 errno = 0;
914 lval = strtol(optarg, &ep, 10);
915 if (optarg[0] == '\0' || *ep != '\0')
916 err(1, "not a number: %s", optarg);
917 if (lval < 0 || lval > UINT16_MAX)
918 err(1, "port number out of range: %s", optarg);
919 port = lval;
920 break;
923 case 'x':
924 cgi = optarg;
925 break;
927 default:
928 usage(*argv);
929 return 1;
933 signal(SIGPIPE, SIG_IGN);
934 signal(SIGCHLD, SIG_IGN);
936 #ifdef SIGINFO
937 signal(SIGINFO, sig_handler);
938 #endif
939 signal(SIGUSR2, sig_handler);
941 if (!foreground)
942 signal(SIGHUP, SIG_IGN);
944 if ((conf = tls_config_new()) == NULL)
945 err(1, "tls_config_new");
947 /* optionally accept client certs, but don't try to verify them */
948 tls_config_verify_client_optional(conf);
949 tls_config_insecure_noverifycert(conf);
951 if (tls_config_set_protocols(conf,
952 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
953 err(1, "tls_config_set_protocols");
955 if (tls_config_set_cert_file(conf, cert) == -1)
956 err(1, "tls_config_set_cert_file: %s", cert);
958 if (tls_config_set_key_file(conf, key) == -1)
959 err(1, "tls_config_set_key_file: %s", key);
961 if ((ctx = tls_server()) == NULL)
962 err(1, "tls_server");
964 if (tls_configure(ctx, conf) == -1)
965 errx(1, "tls_configure: %s", tls_error(ctx));
967 sock4 = make_socket(port, AF_INET);
968 if (enable_ipv6)
969 sock6 = make_socket(port, AF_INET6);
970 else
971 sock6 = -1;
973 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
974 err(1, "open: %s", dir);
976 if (!foreground && daemon(0, 1) == -1)
977 exit(1);
979 if (unveil(dir, "rx") == -1)
980 err(1, "unveil");
982 if (pledge("stdio rpath inet proc exec", NULL) == -1)
983 err(1, "pledge");
985 /* drop proc and exec if cgi isn't enabled */
986 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
987 err(1, "pledge");
989 loop(ctx, sock4, sock6);
991 close(sock4);
992 close(sock6);
993 tls_free(ctx);
994 tls_config_free(conf);