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 static inline void
62 safe_setenv(const char *name, const char *val)
63 {
64 if (val == NULL)
65 val = "";
66 setenv(name, val, 1);
67 }
69 __attribute__ ((format (printf, 1, 2)))
70 __attribute__ ((__noreturn__))
71 static inline void
72 fatal(const char *fmt, ...)
73 {
74 va_list ap;
76 va_start(ap, fmt);
78 if (conf.foreground) {
79 vfprintf(stderr, fmt, ap);
80 fprintf(stderr, "\n");
81 } else
82 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
84 va_end(ap);
85 exit(1);
86 }
88 void
89 logs(int priority, struct client *c,
90 const char *fmt, ...)
91 {
92 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
93 char *fmted, *s;
94 size_t len;
95 int ec;
96 va_list ap;
98 va_start(ap, fmt);
100 if (c == NULL) {
101 strncpy(hbuf, "<internal>", sizeof(hbuf));
102 sbuf[0] = '\0';
103 } else {
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));
113 if (vasprintf(&fmted, fmt, ap) == -1)
114 fatal("vasprintf: %s", strerror(errno));
116 if (conf.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(c->host->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 (c->host->cgi != NULL && starts_with(fpath, c->host->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 (c->host->cgi != NULL && starts_with(fpath, c->host->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", conf.port) == -1)
370 goto childerr;
372 if (asprintf(&ex, "%s/%s", c->host->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", c->host->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 struct vhost *h;
575 const char *servname;
577 switch (tls_handshake(c->ctx)) {
578 case 0: /* success */
579 case -1: /* already handshaked */
580 break;
581 case TLS_WANT_POLLIN:
582 fds->events = POLLIN;
583 return;
584 case TLS_WANT_POLLOUT:
585 fds->events = POLLOUT;
586 return;
587 default:
588 /* unreachable */
589 abort();
592 servname = tls_conn_servername(c->ctx);
593 if (servname == NULL)
594 goto wronghost;
596 for (h = hosts; h->domain != NULL; ++h) {
597 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
598 break;
601 if (h->domain != NULL) {
602 c->state = S_OPEN;
603 c->host = h;
604 handle_open_conn(fds, c);
605 return;
608 wronghost:
609 /* XXX: check the correct response */
610 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
611 return;
612 goodbye(fds, c);
615 void
616 handle_open_conn(struct pollfd *fds, struct client *c)
618 char buf[GEMINI_URL_LEN];
619 const char *parse_err = "invalid request";
620 struct iri iri;
622 bzero(buf, sizeof(buf));
624 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
625 case -1:
626 LOGE(c, "tls_read: %s", tls_error(c->ctx));
627 goodbye(fds, c);
628 return;
630 case TLS_WANT_POLLIN:
631 fds->events = POLLIN;
632 return;
634 case TLS_WANT_POLLOUT:
635 fds->events = POLLOUT;
636 return;
639 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
640 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
641 return;
642 goodbye(fds, c);
643 return;
646 if (strcmp(iri.schema, "gemini")) {
647 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
648 return;
649 goodbye(fds, c);
650 return;
653 LOGI(c, "GET %s%s%s",
654 *iri.path ? iri.path : "/",
655 *iri.query ? "?" : "",
656 *iri.query ? iri.query : "");
658 send_file(iri.path, iri.query, fds, c);
661 void
662 handle(struct pollfd *fds, struct client *client)
664 switch (client->state) {
665 case S_HANDSHAKE:
666 handle_handshake(fds, client);
667 break;
669 case S_OPEN:
670 handle_open_conn(fds, client);
671 break;
673 case S_INITIALIZING:
674 if (!start_reply(fds, client, client->code, client->meta))
675 return;
677 if (client->code != SUCCESS) {
678 /* we don't need a body */
679 goodbye(fds, client);
680 return;
683 client->state = S_SENDING;
685 /* fallthrough */
687 case S_SENDING:
688 if (client->child != -1)
689 handle_cgi(fds, client);
690 else
691 send_file(NULL, NULL, fds, client);
692 break;
694 case S_CLOSING:
695 goodbye(fds, client);
696 break;
698 default:
699 /* unreachable */
700 abort();
704 void
705 mark_nonblock(int fd)
707 int flags;
709 if ((flags = fcntl(fd, F_GETFL)) == -1)
710 fatal("fcntl(F_GETFL): %s", strerror(errno));
711 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
712 fatal("fcntl(F_SETFL): %s", strerror(errno));
715 int
716 make_socket(int port, int family)
718 int sock, v;
719 struct sockaddr_in addr4;
720 struct sockaddr_in6 addr6;
721 struct sockaddr *addr;
722 socklen_t len;
724 switch (family) {
725 case AF_INET:
726 bzero(&addr4, sizeof(addr4));
727 addr4.sin_family = family;
728 addr4.sin_port = htons(port);
729 addr4.sin_addr.s_addr = INADDR_ANY;
730 addr = (struct sockaddr*)&addr4;
731 len = sizeof(addr4);
732 break;
734 case AF_INET6:
735 bzero(&addr6, sizeof(addr6));
736 addr6.sin6_family = AF_INET6;
737 addr6.sin6_port = htons(port);
738 addr6.sin6_addr = in6addr_any;
739 addr = (struct sockaddr*)&addr6;
740 len = sizeof(addr6);
741 break;
743 default:
744 /* unreachable */
745 abort();
748 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
749 fatal("socket: %s", strerror(errno));
751 v = 1;
752 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
753 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
755 v = 1;
756 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
757 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
759 mark_nonblock(sock);
761 if (bind(sock, addr, len) == -1)
762 fatal("bind: %s", strerror(errno));
764 if (listen(sock, 16) == -1)
765 fatal("listen: %s", strerror(errno));
767 return sock;
770 void
771 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
773 int i, fd;
774 struct sockaddr_storage addr;
775 socklen_t len;
777 len = sizeof(addr);
778 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
779 if (errno == EWOULDBLOCK)
780 return;
781 fatal("accept: %s", strerror(errno));
784 mark_nonblock(fd);
786 for (i = 0; i < MAX_USERS; ++i) {
787 if (fds[i].fd == -1) {
788 bzero(&clients[i], sizeof(struct client));
789 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
790 break; /* goodbye fd! */
792 fds[i].fd = fd;
793 fds[i].events = POLLIN;
795 clients[i].state = S_HANDSHAKE;
796 clients[i].fd = -1;
797 clients[i].child = -1;
798 clients[i].buf = MAP_FAILED;
799 clients[i].af = AF_INET;
800 clients[i].addr = addr;
802 connected_clients++;
803 return;
807 close(fd);
810 void
811 goodbye(struct pollfd *pfd, struct client *c)
813 ssize_t ret;
815 c->state = S_CLOSING;
817 ret = tls_close(c->ctx);
818 if (ret == TLS_WANT_POLLIN) {
819 pfd->events = POLLIN;
820 return;
822 if (ret == TLS_WANT_POLLOUT) {
823 pfd->events = POLLOUT;
824 return;
827 connected_clients--;
829 tls_free(c->ctx);
830 c->ctx = NULL;
832 if (c->buf != MAP_FAILED)
833 munmap(c->buf, c->len);
835 if (c->fd != -1)
836 close(c->fd);
838 close(pfd->fd);
839 pfd->fd = -1;
842 void
843 loop(struct tls *ctx, int sock4, int sock6)
845 int i;
846 struct client clients[MAX_USERS];
847 struct pollfd fds[MAX_USERS];
849 for (i = 0; i < MAX_USERS; ++i) {
850 fds[i].fd = -1;
851 fds[i].events = POLLIN;
852 bzero(&clients[i], sizeof(struct client));
855 fds[0].fd = sock4;
856 fds[1].fd = sock6;
858 for (;;) {
859 if (poll(fds, MAX_USERS, INFTIM) == -1) {
860 if (errno == EINTR) {
861 warnx("connected clients: %d",
862 connected_clients);
863 continue;
865 fatal("poll: %s", strerror(errno));
868 for (i = 0; i < MAX_USERS; i++) {
869 if (fds[i].revents == 0)
870 continue;
872 if (fds[i].revents & (POLLERR|POLLNVAL))
873 fatal("bad fd %d: %s", fds[i].fd,
874 strerror(errno));
876 if (fds[i].revents & POLLHUP) {
877 /* fds[i] may be the fd of the stdin
878 * of a cgi script that has exited. */
879 if (!clients[i].waiting_on_child) {
880 goodbye(&fds[i], &clients[i]);
881 continue;
885 if (fds[i].fd == sock4)
886 do_accept(sock4, ctx, fds, clients);
887 else if (fds[i].fd == sock6)
888 do_accept(sock6, ctx, fds, clients);
889 else
890 handle(&fds[i], &clients[i]);
895 char *
896 absolutify_path(const char *path)
898 char *wd, *r;
900 if (*path == '/')
901 return strdup(path);
903 wd = getwd(NULL);
904 if (asprintf(&r, "%s/%s", wd, path) == -1)
905 err(1, "asprintf");
906 free(wd);
907 return r;
910 void
911 yyerror(const char *msg)
913 goterror = 1;
914 fprintf(stderr, "%d: %s\n", yylineno, msg);
917 int
918 parse_portno(const char *p)
920 char *ep;
921 long lval;
923 errno = 0;
924 lval = strtol(p, &ep, 10);
925 if (p[0] == '\0' || *ep != '\0')
926 errx(1, "not a number: %s", p);
927 if (lval < 0 || lval > UINT16_MAX)
928 errx(1, "port number out of range for domain %s: %ld", p, lval);
929 return lval;
932 void
933 parse_conf(const char *path)
935 if ((yyin = fopen(path, "r")) == NULL)
936 err(1, "cannot open config %s", path);
937 yyparse();
938 fclose(yyin);
940 if (goterror)
941 exit(1);
944 void
945 load_vhosts(struct tls_config *tlsconf)
947 struct vhost *h;
949 /* we need to set something, then we can add how many key we want */
950 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
951 errx(1, "tls_config_set_keypair_file failed");
953 for (h = hosts; h->domain != NULL; ++h) {
954 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
955 errx(1, "failed to load the keypair (%s, %s)",
956 h->cert, h->key);
958 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
959 err(1, "open %s for domain %s", h->dir, h->domain);
963 void
964 usage(const char *me)
966 fprintf(stderr,
967 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
968 "[-p port] [-x cgi-bin]\n",
969 me);
972 int
973 main(int argc, char **argv)
975 struct tls *ctx = NULL;
976 struct tls_config *tlsconf;
977 int sock4, sock6, ch;
978 const char *config_path = NULL;
979 size_t i;
980 int conftest = 0;
982 bzero(hosts, sizeof(hosts));
983 for (i = 0; i < HOSTSLEN; ++i)
984 hosts[i].dirfd = -1;
986 conf.foreground = 1;
987 conf.port = 1965;
988 conf.ipv6 = 0;
990 connected_clients = 0;
992 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
993 switch (ch) {
994 case '6':
995 conf.ipv6 = 1;
996 break;
998 case 'C':
999 hosts[0].cert = optarg;
1000 break;
1002 case 'c':
1003 config_path = optarg;
1004 break;
1006 case 'd':
1007 free((char*)hosts[0].dir);
1008 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
1009 err(1, "absolutify_path");
1010 break;
1012 case 'f':
1013 conf.foreground = 1;
1014 break;
1016 case 'h':
1017 usage(*argv);
1018 return 0;
1020 case 'K':
1021 hosts[0].key = optarg;
1022 break;
1024 case 'n':
1025 conftest = 1;
1026 break;
1028 case 'p':
1029 conf.port = parse_portno(optarg);
1031 case 'x':
1032 /* drop the starting / (if any) */
1033 if (*optarg == '/')
1034 optarg++;
1035 hosts[0].cgi = optarg;
1036 break;
1038 default:
1039 usage(*argv);
1040 return 1;
1044 if (config_path != NULL) {
1045 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
1046 hosts[0].dir != NULL)
1047 errx(1, "can't specify options in conf mode");
1048 parse_conf(config_path);
1049 } else {
1050 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
1051 hosts[0].dir == NULL)
1052 errx(1, "missing cert, key or root directory to serve");
1053 hosts[0].domain = "*";
1056 if (conftest)
1057 errx(0, "config OK");
1059 signal(SIGPIPE, SIG_IGN);
1060 signal(SIGCHLD, SIG_IGN);
1062 #ifdef SIGINFO
1063 signal(SIGINFO, sig_handler);
1064 #endif
1065 signal(SIGUSR2, sig_handler);
1067 if (!conf.foreground)
1068 signal(SIGHUP, SIG_IGN);
1070 if ((tlsconf = tls_config_new()) == NULL)
1071 err(1, "tls_config_new");
1073 /* optionally accept client certs, but don't try to verify them */
1074 tls_config_verify_client_optional(tlsconf);
1075 tls_config_insecure_noverifycert(tlsconf);
1077 if (tls_config_set_protocols(tlsconf,
1078 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1079 err(1, "tls_config_set_protocols");
1081 load_vhosts(tlsconf);
1083 if ((ctx = tls_server()) == NULL)
1084 err(1, "tls_server");
1086 if (tls_configure(ctx, tlsconf) == -1)
1087 errx(1, "tls_configure: %s", tls_error(ctx));
1089 sock4 = make_socket(conf.port, AF_INET);
1090 if (conf.ipv6)
1091 sock6 = make_socket(conf.port, AF_INET6);
1092 else
1093 sock6 = -1;
1096 if (!conf.foreground && daemon(0, 1) == -1)
1097 exit(1);
1099 sandbox();
1101 loop(ctx, sock4, sock6);
1103 close(sock4);
1104 close(sock6);
1105 tls_free(ctx);
1106 tls_config_free(tlsconf);
1108 return 0;