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]; /* status + ' ' + max reply len + \r\n\0 */
151 int len;
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));
160 switch (tls_write(client->ctx, buf, len)) {
161 case TLS_WANT_POLLIN:
162 pfd->events = POLLIN;
163 return 0;
164 case TLS_WANT_POLLOUT:
165 pfd->events = POLLOUT;
166 return 0;
167 default:
168 return 1;
172 ssize_t
173 filesize(int fd)
175 ssize_t len;
177 if ((len = lseek(fd, 0, SEEK_END)) == -1)
178 return -1;
179 if (lseek(fd, 0, SEEK_SET) == -1)
180 return -1;
181 return len;
184 const char *
185 path_ext(const char *path)
187 const char *end;
189 end = path + strlen(path)-1;
190 for (; end != path; --end) {
191 if (*end == '.')
192 return end+1;
193 if (*end == '/')
194 break;
197 return NULL;
200 const char *
201 mime(const char *path)
203 const char *ext, *def = "application/octet-stream";
204 struct etm *t;
206 if ((ext = path_ext(path)) == NULL)
207 return def;
209 for (t = filetypes; t->mime != NULL; ++t)
210 if (!strcmp(ext, t->ext))
211 return t->mime;
213 return def;
216 int
217 check_path(struct client *c, const char *path, int *fd)
219 struct stat sb;
221 assert(path != NULL);
222 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
223 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
224 return FILE_MISSING;
227 if (fstat(*fd, &sb) == -1) {
228 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
229 return FILE_MISSING;
232 if (S_ISDIR(sb.st_mode))
233 return FILE_DIRECTORY;
235 if (sb.st_mode & S_IXUSR)
236 return FILE_EXECUTABLE;
238 return FILE_EXISTS;
241 /*
242 * the inverse of this algorithm, i.e. starting from the start of the
243 * path + strlen(cgi), and checking if each component, should be
244 * faster. But it's tedious to write. This does the opposite: starts
245 * from the end and strip one component at a time, until either an
246 * executable is found or we emptied the path.
247 */
248 int
249 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
251 char *end;
252 end = strchr(path, '\0');
254 /* NB: assume CGI is enabled and path matches cgi */
256 while (end > path) {
257 /* go up one level. UNIX paths are simple and POSIX
258 * dirname, with its ambiguities on if the given path
259 * is changed or not, gives me headaches. */
260 while (*end != '/')
261 end--;
262 *end = '\0';
264 switch (check_path(c, path, &c->fd)) {
265 case FILE_EXECUTABLE:
266 return start_cgi(path, end+1, query, fds,c);
267 case FILE_MISSING:
268 break;
269 default:
270 goto err;
273 *end = '/';
274 end--;
277 err:
278 if (!start_reply(fds, c, NOT_FOUND, "not found"))
279 return 0;
280 goodbye(fds, c);
281 return 0;
284 int
285 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
287 switch (check_path(c, fpath, &c->fd)) {
288 case FILE_EXECUTABLE:
289 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
290 return start_cgi(fpath, "", query, fds, c);
292 /* fallthrough */
294 case FILE_EXISTS:
295 if ((c->len = filesize(c->fd)) == -1) {
296 LOGE(c, "failed to get file size for %s", fpath);
297 goodbye(fds, c);
298 return 0;
301 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
302 c->fd, 0)) == MAP_FAILED) {
303 warn("mmap: %s", fpath);
304 goodbye(fds, c);
305 return 0;
307 c->i = c->buf;
308 return start_reply(fds, c, SUCCESS, mime(fpath));
310 case FILE_DIRECTORY:
311 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
312 close(c->fd);
313 c->fd = -1;
314 send_dir(fpath, fds, c);
315 return 0;
317 case FILE_MISSING:
318 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
319 return check_for_cgi(fpath, query, fds, c);
321 if (!start_reply(fds, c, NOT_FOUND, "not found"))
322 return 0;
323 goodbye(fds, c);
324 return 0;
326 default:
327 /* unreachable */
328 abort();
332 int
333 start_cgi(const char *spath, const char *relpath, const char *query,
334 struct pollfd *fds, struct client *c)
336 pid_t pid;
337 int p[2]; /* read end, write end */
339 if (pipe(p) == -1)
340 goto err;
342 switch (pid = fork()) {
343 case -1:
344 goto err;
346 case 0: { /* child */
347 char *ex, *requri, *portno;
348 char addr[NI_MAXHOST];
349 char *argv[] = { NULL, NULL, NULL };
350 int ec;
352 close(p[0]);
353 if (dup2(p[1], 1) == -1)
354 goto childerr;
356 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
357 goto childerr;
359 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
360 addr, sizeof(addr),
361 NULL, 0,
362 NI_NUMERICHOST | NI_NUMERICSERV);
363 if (ec != 0)
364 goto childerr;
366 if (asprintf(&portno, "%d", conf.port) == -1)
367 goto childerr;
369 if (asprintf(&ex, "%s/%s", c->host->dir, spath) == -1)
370 goto childerr;
372 if (asprintf(&requri, "%s%s%s", spath,
373 *relpath == '\0' ? "" : "/", relpath) == -1)
374 goto childerr;
376 argv[0] = argv[1] = ex;
378 /* fix the env */
379 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
380 safe_setenv("SERVER_SOFTWARE", "gmid");
381 safe_setenv("SERVER_PORT", portno);
382 /* setenv("SERVER_NAME", "", 1); */
383 safe_setenv("SCRIPT_NAME", spath);
384 safe_setenv("SCRIPT_EXECUTABLE", ex);
385 safe_setenv("REQUEST_URI", requri);
386 safe_setenv("REQUEST_RELATIVE", relpath);
387 safe_setenv("QUERY_STRING", query);
388 safe_setenv("REMOTE_HOST", addr);
389 safe_setenv("REMOTE_ADDR", addr);
390 safe_setenv("DOCUMENT_ROOT", c->host->dir);
392 if (tls_peer_cert_provided(c->ctx)) {
393 safe_setenv("AUTH_TYPE", "Certificate");
394 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
395 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
396 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
399 execvp(ex, argv);
400 goto childerr;
403 default: /* parent */
404 close(p[1]);
405 close(c->fd);
406 c->fd = p[0];
407 c->child = pid;
408 mark_nonblock(c->fd);
409 c->state = S_SENDING;
410 handle_cgi(fds, c);
411 return 0;
414 err:
415 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
416 return 0;
417 goodbye(fds, c);
418 return 0;
420 childerr:
421 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
422 close(p[1]);
423 _exit(1);
426 void
427 cgi_poll_on_child(struct pollfd *fds, struct client *c)
429 int fd;
431 if (c->waiting_on_child)
432 return;
433 c->waiting_on_child = 1;
435 fds->events = POLLIN;
437 fd = fds->fd;
438 fds->fd = c->fd;
439 c->fd = fd;
442 void
443 cgi_poll_on_client(struct pollfd *fds, struct client *c)
445 int fd;
447 if (!c->waiting_on_child)
448 return;
449 c->waiting_on_child = 0;
451 fd = fds->fd;
452 fds->fd = c->fd;
453 c->fd = fd;
456 void
457 handle_cgi(struct pollfd *fds, struct client *c)
459 ssize_t r;
461 /* ensure c->fd is the child and fds->fd the client */
462 cgi_poll_on_client(fds, c);
464 while (1) {
465 if (c->len == 0) {
466 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
467 goto end;
468 if (r == -1) {
469 if (errno == EAGAIN || errno == EWOULDBLOCK) {
470 cgi_poll_on_child(fds, c);
471 return;
473 goto end;
475 c->len = r;
476 c->off = 0;
479 while (c->len > 0) {
480 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
481 case -1:
482 goto end;
484 case TLS_WANT_POLLOUT:
485 fds->events = POLLOUT;
486 return;
488 case TLS_WANT_POLLIN:
489 fds->events = POLLIN;
490 return;
492 default:
493 c->off += r;
494 c->len -= r;
495 break;
500 end:
501 goodbye(fds, c);
504 void
505 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
507 ssize_t ret, len;
509 if (c->fd == -1) {
510 if (!open_file(path, query, fds, c))
511 return;
512 c->state = S_SENDING;
515 len = (c->buf + c->len) - c->i;
517 while (len > 0) {
518 switch (ret = tls_write(c->ctx, c->i, len)) {
519 case -1:
520 LOGE(c, "tls_write: %s", tls_error(c->ctx));
521 goodbye(fds, c);
522 return;
524 case TLS_WANT_POLLIN:
525 fds->events = POLLIN;
526 return;
528 case TLS_WANT_POLLOUT:
529 fds->events = POLLOUT;
530 return;
532 default:
533 c->i += ret;
534 len -= ret;
535 break;
539 goodbye(fds, c);
542 void
543 send_dir(char *path, struct pollfd *fds, struct client *client)
545 char fpath[PATHBUF];
546 size_t len;
548 bzero(fpath, PATHBUF);
550 if (path[0] != '.')
551 fpath[0] = '.';
553 /* this cannot fail since sizeof(fpath) > maxlen of path */
554 strlcat(fpath, path, PATHBUF);
555 len = strlen(fpath);
557 /* add a trailing / in case. */
558 if (fpath[len-1] != '/') {
559 fpath[len] = '/';
562 strlcat(fpath, "index.gmi", sizeof(fpath));
564 send_file(fpath, NULL, fds, client);
567 void
568 handle_handshake(struct pollfd *fds, struct client *c)
570 struct vhost *h;
571 const char *servname;
573 switch (tls_handshake(c->ctx)) {
574 case 0: /* success */
575 case -1: /* already handshaked */
576 break;
577 case TLS_WANT_POLLIN:
578 fds->events = POLLIN;
579 return;
580 case TLS_WANT_POLLOUT:
581 fds->events = POLLOUT;
582 return;
583 default:
584 /* unreachable */
585 abort();
588 servname = tls_conn_servername(c->ctx);
589 if (servname == NULL)
590 goto hostnotfound;
592 for (h = hosts; h->domain != NULL; ++h) {
593 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
594 break;
597 if (h->domain != NULL) {
598 c->state = S_OPEN;
599 c->host = h;
600 handle_open_conn(fds, c);
601 return;
604 hostnotfound:
605 /* XXX: check the correct response */
606 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
607 return;
608 goodbye(fds, c);
611 void
612 handle_open_conn(struct pollfd *fds, struct client *c)
614 char buf[GEMINI_URL_LEN];
615 const char *parse_err = "invalid request";
616 struct iri iri;
618 bzero(buf, sizeof(buf));
620 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
621 case -1:
622 LOGE(c, "tls_read: %s", tls_error(c->ctx));
623 goodbye(fds, c);
624 return;
626 case TLS_WANT_POLLIN:
627 fds->events = POLLIN;
628 return;
630 case TLS_WANT_POLLOUT:
631 fds->events = POLLOUT;
632 return;
635 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
636 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
637 return;
638 goodbye(fds, c);
639 return;
642 if (strcmp(iri.schema, "gemini")) {
643 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
644 return;
645 goodbye(fds, c);
646 return;
649 LOGI(c, "GET %s%s%s",
650 *iri.path ? iri.path : "/",
651 *iri.query ? "?" : "",
652 *iri.query ? iri.query : "");
654 send_file(iri.path, iri.query, fds, c);
657 void
658 handle(struct pollfd *fds, struct client *client)
660 switch (client->state) {
661 case S_HANDSHAKE:
662 handle_handshake(fds, client);
663 break;
665 case S_OPEN:
666 handle_open_conn(fds, client);
667 break;
669 case S_INITIALIZING:
670 if (!start_reply(fds, client, client->code, client->meta))
671 return;
673 if (client->code != SUCCESS) {
674 /* we don't need a body */
675 goodbye(fds, client);
676 return;
679 client->state = S_SENDING;
681 /* fallthrough */
683 case S_SENDING:
684 if (client->child != -1)
685 handle_cgi(fds, client);
686 else
687 send_file(NULL, NULL, fds, client);
688 break;
690 case S_CLOSING:
691 goodbye(fds, client);
692 break;
694 default:
695 /* unreachable */
696 abort();
700 void
701 mark_nonblock(int fd)
703 int flags;
705 if ((flags = fcntl(fd, F_GETFL)) == -1)
706 fatal("fcntl(F_GETFL): %s", strerror(errno));
707 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
708 fatal("fcntl(F_SETFL): %s", strerror(errno));
711 int
712 make_socket(int port, int family)
714 int sock, v;
715 struct sockaddr_in addr4;
716 struct sockaddr_in6 addr6;
717 struct sockaddr *addr;
718 socklen_t len;
720 switch (family) {
721 case AF_INET:
722 bzero(&addr4, sizeof(addr4));
723 addr4.sin_family = family;
724 addr4.sin_port = htons(port);
725 addr4.sin_addr.s_addr = INADDR_ANY;
726 addr = (struct sockaddr*)&addr4;
727 len = sizeof(addr4);
728 break;
730 case AF_INET6:
731 bzero(&addr6, sizeof(addr6));
732 addr6.sin6_family = AF_INET6;
733 addr6.sin6_port = htons(port);
734 addr6.sin6_addr = in6addr_any;
735 addr = (struct sockaddr*)&addr6;
736 len = sizeof(addr6);
737 break;
739 default:
740 /* unreachable */
741 abort();
744 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
745 fatal("socket: %s", strerror(errno));
747 v = 1;
748 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
749 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
751 v = 1;
752 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
753 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
755 mark_nonblock(sock);
757 if (bind(sock, addr, len) == -1)
758 fatal("bind: %s", strerror(errno));
760 if (listen(sock, 16) == -1)
761 fatal("listen: %s", strerror(errno));
763 return sock;
766 void
767 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
769 int i, fd;
770 struct sockaddr_storage addr;
771 socklen_t len;
773 len = sizeof(addr);
774 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
775 if (errno == EWOULDBLOCK)
776 return;
777 fatal("accept: %s", strerror(errno));
780 mark_nonblock(fd);
782 for (i = 0; i < MAX_USERS; ++i) {
783 if (fds[i].fd == -1) {
784 bzero(&clients[i], sizeof(struct client));
785 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
786 break; /* goodbye fd! */
788 fds[i].fd = fd;
789 fds[i].events = POLLIN;
791 clients[i].state = S_HANDSHAKE;
792 clients[i].fd = -1;
793 clients[i].child = -1;
794 clients[i].buf = MAP_FAILED;
795 clients[i].af = AF_INET;
796 clients[i].addr = addr;
798 connected_clients++;
799 return;
803 close(fd);
806 void
807 goodbye(struct pollfd *pfd, struct client *c)
809 c->state = S_CLOSING;
811 switch (tls_close(c->ctx)) {
812 case TLS_WANT_POLLIN:
813 pfd->events = POLLIN;
814 return;
815 case TLS_WANT_POLLOUT:
816 pfd->events = POLLOUT;
817 return;
820 connected_clients--;
822 tls_free(c->ctx);
823 c->ctx = NULL;
825 if (c->buf != MAP_FAILED)
826 munmap(c->buf, c->len);
828 if (c->fd != -1)
829 close(c->fd);
831 close(pfd->fd);
832 pfd->fd = -1;
835 void
836 loop(struct tls *ctx, int sock4, int sock6)
838 int i;
839 struct client clients[MAX_USERS];
840 struct pollfd fds[MAX_USERS];
842 for (i = 0; i < MAX_USERS; ++i) {
843 fds[i].fd = -1;
844 fds[i].events = POLLIN;
845 bzero(&clients[i], sizeof(struct client));
848 fds[0].fd = sock4;
849 fds[1].fd = sock6;
851 for (;;) {
852 if (poll(fds, MAX_USERS, INFTIM) == -1) {
853 if (errno == EINTR) {
854 warnx("connected clients: %d",
855 connected_clients);
856 continue;
858 fatal("poll: %s", strerror(errno));
861 for (i = 0; i < MAX_USERS; i++) {
862 if (fds[i].revents == 0)
863 continue;
865 if (fds[i].revents & (POLLERR|POLLNVAL))
866 fatal("bad fd %d: %s", fds[i].fd,
867 strerror(errno));
869 if (fds[i].revents & POLLHUP) {
870 /* fds[i] may be the fd of the stdin
871 * of a cgi script that has exited. */
872 if (!clients[i].waiting_on_child) {
873 goodbye(&fds[i], &clients[i]);
874 continue;
878 if (fds[i].fd == sock4)
879 do_accept(sock4, ctx, fds, clients);
880 else if (fds[i].fd == sock6)
881 do_accept(sock6, ctx, fds, clients);
882 else
883 handle(&fds[i], &clients[i]);
888 char *
889 absolutify_path(const char *path)
891 char *wd, *r;
893 if (*path == '/')
894 return strdup(path);
896 wd = getwd(NULL);
897 if (asprintf(&r, "%s/%s", wd, path) == -1)
898 err(1, "asprintf");
899 free(wd);
900 return r;
903 void
904 yyerror(const char *msg)
906 goterror = 1;
907 fprintf(stderr, "%d: %s\n", yylineno, msg);
910 int
911 parse_portno(const char *p)
913 char *ep;
914 long lval;
916 errno = 0;
917 lval = strtol(p, &ep, 10);
918 if (p[0] == '\0' || *ep != '\0')
919 errx(1, "not a number: %s", p);
920 if (lval < 0 || lval > UINT16_MAX)
921 errx(1, "port number out of range for domain %s: %ld", p, lval);
922 return lval;
925 void
926 parse_conf(const char *path)
928 if ((yyin = fopen(path, "r")) == NULL)
929 err(1, "cannot open config %s", path);
930 yyparse();
931 fclose(yyin);
933 if (goterror)
934 exit(1);
937 void
938 load_vhosts(struct tls_config *tlsconf)
940 struct vhost *h;
942 /* we need to set something, then we can add how many key we want */
943 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
944 errx(1, "tls_config_set_keypair_file failed");
946 for (h = hosts; h->domain != NULL; ++h) {
947 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
948 errx(1, "failed to load the keypair (%s, %s)",
949 h->cert, h->key);
951 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
952 err(1, "open %s for domain %s", h->dir, h->domain);
956 void
957 usage(const char *me)
959 fprintf(stderr,
960 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
961 "[-p port] [-x cgi-bin]\n",
962 me);
965 int
966 main(int argc, char **argv)
968 struct tls *ctx = NULL;
969 struct tls_config *tlsconf;
970 int sock4, sock6, ch;
971 const char *config_path = NULL;
972 size_t i;
973 int conftest = 0;
975 bzero(hosts, sizeof(hosts));
976 for (i = 0; i < HOSTSLEN; ++i)
977 hosts[i].dirfd = -1;
979 conf.foreground = 1;
980 conf.port = 1965;
981 conf.ipv6 = 0;
983 connected_clients = 0;
985 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
986 switch (ch) {
987 case '6':
988 conf.ipv6 = 1;
989 break;
991 case 'C':
992 hosts[0].cert = optarg;
993 break;
995 case 'c':
996 config_path = optarg;
997 break;
999 case 'd':
1000 free((char*)hosts[0].dir);
1001 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
1002 err(1, "absolutify_path");
1003 break;
1005 case 'f':
1006 conf.foreground = 1;
1007 break;
1009 case 'h':
1010 usage(*argv);
1011 return 0;
1013 case 'K':
1014 hosts[0].key = optarg;
1015 break;
1017 case 'n':
1018 conftest = 1;
1019 break;
1021 case 'p':
1022 conf.port = parse_portno(optarg);
1024 case 'x':
1025 /* drop the starting / (if any) */
1026 if (*optarg == '/')
1027 optarg++;
1028 hosts[0].cgi = optarg;
1029 break;
1031 default:
1032 usage(*argv);
1033 return 1;
1037 if (config_path != NULL) {
1038 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
1039 hosts[0].dir != NULL)
1040 errx(1, "can't specify options in conf mode");
1041 parse_conf(config_path);
1042 } else {
1043 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
1044 hosts[0].dir == NULL)
1045 errx(1, "missing cert, key or root directory to serve");
1046 hosts[0].domain = "*";
1049 if (conftest)
1050 errx(0, "config OK");
1052 signal(SIGPIPE, SIG_IGN);
1053 signal(SIGCHLD, SIG_IGN);
1055 #ifdef SIGINFO
1056 signal(SIGINFO, sig_handler);
1057 #endif
1058 signal(SIGUSR2, sig_handler);
1060 if (!conf.foreground)
1061 signal(SIGHUP, SIG_IGN);
1063 if ((tlsconf = tls_config_new()) == NULL)
1064 err(1, "tls_config_new");
1066 /* optionally accept client certs, but don't try to verify them */
1067 tls_config_verify_client_optional(tlsconf);
1068 tls_config_insecure_noverifycert(tlsconf);
1070 if (tls_config_set_protocols(tlsconf,
1071 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1072 err(1, "tls_config_set_protocols");
1074 load_vhosts(tlsconf);
1076 if ((ctx = tls_server()) == NULL)
1077 err(1, "tls_server");
1079 if (tls_configure(ctx, tlsconf) == -1)
1080 errx(1, "tls_configure: %s", tls_error(ctx));
1082 sock4 = make_socket(conf.port, AF_INET);
1083 if (conf.ipv6)
1084 sock6 = make_socket(conf.port, AF_INET6);
1085 else
1086 sock6 = -1;
1088 if (!conf.foreground && daemon(0, 1) == -1)
1089 exit(1);
1091 sandbox();
1093 loop(ctx, sock4, sock6);
1095 close(sock4);
1096 close(sock6);
1097 tls_free(ctx);
1098 tls_config_free(tlsconf);
1100 return 0;