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 struct vhost hosts[HOSTSLEN];
39 int connected_clients;
40 int goterror;
42 struct conf conf;
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 __attribute__ ((__noreturn__))
76 static inline void
77 fatal(const char *fmt, ...)
78 {
79 va_list ap;
81 va_start(ap, fmt);
83 if (conf.foreground) {
84 vfprintf(stderr, fmt, ap);
85 fprintf(stderr, "\n");
86 } else
87 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
89 va_end(ap);
90 exit(1);
91 }
93 __attribute__ ((format (printf, 3, 4)))
94 static inline void
95 logs(int priority, struct client *c,
96 const char *fmt, ...)
97 {
98 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
99 char *fmted, *s;
100 size_t len;
101 int ec;
102 va_list ap;
104 va_start(ap, fmt);
106 len = sizeof(c->addr);
107 ec = getnameinfo((struct sockaddr*)&c->addr, len,
108 hbuf, sizeof(hbuf),
109 sbuf, sizeof(sbuf),
110 NI_NUMERICHOST | NI_NUMERICSERV);
111 if (ec != 0)
112 fatal("getnameinfo: %s", gai_strerror(ec));
114 if (vasprintf(&fmted, fmt, ap) == -1)
115 fatal("vasprintf: %s", strerror(errno));
117 if (conf.foreground)
118 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
119 else {
120 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
121 fatal("asprintf: %s", strerror(errno));
122 syslog(priority | LOG_DAEMON, "%s", s);
123 free(s);
126 free(fmted);
128 va_end(ap);
131 void
132 sig_handler(int sig)
134 (void)sig;
137 int
138 starts_with(const char *str, const char *prefix)
140 size_t i;
142 for (i = 0; prefix[i] != '\0'; ++i)
143 if (str[i] != prefix[i])
144 return 0;
145 return 1;
148 int
149 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
151 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
152 int len;
153 int ret;
155 client->code = code;
156 client->meta = reason;
157 client->state = S_INITIALIZING;
159 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
160 assert(len < (int)sizeof(buf));
161 ret = tls_write(client->ctx, buf, len);
162 if (ret == TLS_WANT_POLLIN) {
163 pfd->events = POLLIN;
164 return 0;
167 if (ret == TLS_WANT_POLLOUT) {
168 pfd->events = POLLOUT;
169 return 0;
172 return 1;
175 ssize_t
176 filesize(int fd)
178 ssize_t len;
180 if ((len = lseek(fd, 0, SEEK_END)) == -1)
181 return -1;
182 if (lseek(fd, 0, SEEK_SET) == -1)
183 return -1;
184 return len;
187 const char *
188 path_ext(const char *path)
190 const char *end;
192 end = path + strlen(path)-1; /* the last byte before the NUL */
193 for (; end != path; --end) {
194 if (*end == '.')
195 return end+1;
196 if (*end == '/')
197 break;
200 return NULL;
203 const char *
204 mime(const char *path)
206 const char *ext, *def = "application/octet-stream";
207 struct etm *t;
209 if ((ext = path_ext(path)) == NULL)
210 return def;
212 for (t = filetypes; t->mime != NULL; ++t)
213 if (!strcmp(ext, t->ext))
214 return t->mime;
216 return def;
219 int
220 check_path(struct client *c, const char *path, int *fd)
222 struct stat sb;
224 assert(path != NULL);
225 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
226 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
227 return FILE_MISSING;
230 if (fstat(*fd, &sb) == -1) {
231 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
232 return FILE_MISSING;
235 if (S_ISDIR(sb.st_mode))
236 return FILE_DIRECTORY;
238 if (sb.st_mode & S_IXUSR)
239 return FILE_EXECUTABLE;
241 return FILE_EXISTS;
244 /*
245 * the inverse of this algorithm, i.e. starting from the start of the
246 * path + strlen(cgi), and checking if each component, should be
247 * faster. But it's tedious to write. This does the opposite: starts
248 * from the end and strip one component at a time, until either an
249 * executable is found or we emptied the path.
250 */
251 int
252 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
254 char *end;
255 end = strchr(path, '\0');
257 /* NB: assume CGI is enabled and path matches cgi */
259 while (end > path) {
260 /* go up one level. UNIX paths are simple and POSIX
261 * dirname, with its ambiguities on if the given path
262 * is changed or not, gives me headaches. */
263 while (*end != '/')
264 end--;
265 *end = '\0';
267 switch (check_path(c, path, &c->fd)) {
268 case FILE_EXECUTABLE:
269 return start_cgi(path, end+1, query, fds,c);
270 case FILE_MISSING:
271 break;
272 default:
273 goto err;
276 *end = '/';
277 end--;
280 err:
281 if (!start_reply(fds, c, NOT_FOUND, "not found"))
282 return 0;
283 goodbye(fds, c);
284 return 0;
288 int
289 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
291 switch (check_path(c, fpath, &c->fd)) {
292 case FILE_EXECUTABLE:
293 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
294 return start_cgi(fpath, "", query, fds, c);
296 /* fallthrough */
298 case FILE_EXISTS:
299 if ((c->len = filesize(c->fd)) == -1) {
300 LOGE(c, "failed to get file size for %s", fpath);
301 goodbye(fds, c);
302 return 0;
305 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
306 c->fd, 0)) == MAP_FAILED) {
307 warn("mmap: %s", fpath);
308 goodbye(fds, c);
309 return 0;
311 c->i = c->buf;
312 return start_reply(fds, c, SUCCESS, mime(fpath));
314 case FILE_DIRECTORY:
315 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
316 close(c->fd);
317 c->fd = -1;
318 send_dir(fpath, fds, c);
319 return 0;
321 case FILE_MISSING:
322 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
323 return check_for_cgi(fpath, query, fds, c);
325 if (!start_reply(fds, c, NOT_FOUND, "not found"))
326 return 0;
327 goodbye(fds, c);
328 return 0;
330 default:
331 /* unreachable */
332 abort();
336 int
337 start_cgi(const char *spath, const char *relpath, const char *query,
338 struct pollfd *fds, struct client *c)
340 pid_t pid;
341 int p[2]; /* read end, write end */
343 if (pipe(p) == -1)
344 goto err;
346 switch (pid = fork()) {
347 case -1:
348 goto err;
350 case 0: { /* child */
351 char *ex, *requri, *portno;
352 char addr[NI_MAXHOST];
353 char *argv[] = { NULL, NULL, NULL };
354 int ec;
356 close(p[0]);
357 if (dup2(p[1], 1) == -1)
358 goto childerr;
360 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
361 goto childerr;
363 ec = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
364 addr, sizeof(addr),
365 NULL, 0,
366 NI_NUMERICHOST | NI_NUMERICSERV);
367 if (ec != 0)
368 goto childerr;
370 if (asprintf(&portno, "%d", conf.port) == -1)
371 goto childerr;
373 if (asprintf(&ex, "%s/%s", c->host->dir, spath) == -1)
374 goto childerr;
376 if (asprintf(&requri, "%s%s%s", spath,
377 *relpath == '\0' ? "" : "/",
378 relpath) == -1)
379 goto childerr;
381 argv[0] = argv[1] = ex;
383 /* fix the env */
384 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
385 safe_setenv("SERVER_SOFTWARE", "gmid");
386 safe_setenv("SERVER_PORT", portno);
387 /* setenv("SERVER_NAME", "", 1); */
388 safe_setenv("SCRIPT_NAME", spath);
389 safe_setenv("SCRIPT_EXECUTABLE", ex);
390 safe_setenv("REQUEST_URI", requri);
391 safe_setenv("REQUEST_RELATIVE", relpath);
392 safe_setenv("QUERY_STRING", query);
393 safe_setenv("REMOTE_HOST", addr);
394 safe_setenv("REMOTE_ADDR", addr);
395 safe_setenv("DOCUMENT_ROOT", c->host->dir);
397 if (tls_peer_cert_provided(c->ctx)) {
398 safe_setenv("AUTH_TYPE", "Certificate");
399 safe_setenv("REMOTE_USER", tls_peer_cert_subject(c->ctx));
400 safe_setenv("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
401 safe_setenv("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
404 execvp(ex, argv);
405 goto childerr;
408 default: /* parent */
409 close(p[1]);
410 close(c->fd);
411 c->fd = p[0];
412 c->child = pid;
413 mark_nonblock(c->fd);
414 c->state = S_SENDING;
415 handle_cgi(fds, c);
416 return 0;
419 err:
420 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
421 return 0;
422 goodbye(fds, c);
423 return 0;
425 childerr:
426 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
427 close(p[1]);
428 _exit(1);
431 void
432 cgi_poll_on_child(struct pollfd *fds, struct client *c)
434 int fd;
436 if (c->waiting_on_child)
437 return;
438 c->waiting_on_child = 1;
440 fds->events = POLLIN;
442 fd = fds->fd;
443 fds->fd = c->fd;
444 c->fd = fd;
447 void
448 cgi_poll_on_client(struct pollfd *fds, struct client *c)
450 int fd;
452 if (!c->waiting_on_child)
453 return;
454 c->waiting_on_child = 0;
456 fd = fds->fd;
457 fds->fd = c->fd;
458 c->fd = fd;
461 void
462 handle_cgi(struct pollfd *fds, struct client *c)
464 ssize_t r;
466 /* ensure c->fd is the child and fds->fd the client */
467 cgi_poll_on_client(fds, c);
469 while (1) {
470 if (c->len == 0) {
471 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
472 goto end;
473 if (r == -1) {
474 if (errno == EAGAIN || errno == EWOULDBLOCK) {
475 cgi_poll_on_child(fds, c);
476 return;
478 goto end;
480 c->len = r;
481 c->off = 0;
484 while (c->len > 0) {
485 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
486 case -1:
487 goto end;
489 case TLS_WANT_POLLOUT:
490 fds->events = POLLOUT;
491 return;
493 case TLS_WANT_POLLIN:
494 fds->events = POLLIN;
495 return;
497 default:
498 c->off += r;
499 c->len -= r;
500 break;
505 end:
506 goodbye(fds, c);
509 void
510 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
512 ssize_t ret, len;
514 if (c->fd == -1) {
515 if (!open_file(path, query, fds, c))
516 return;
517 c->state = S_SENDING;
520 len = (c->buf + c->len) - c->i;
522 while (len > 0) {
523 switch (ret = tls_write(c->ctx, c->i, len)) {
524 case -1:
525 LOGE(c, "tls_write: %s", tls_error(c->ctx));
526 goodbye(fds, c);
527 return;
529 case TLS_WANT_POLLIN:
530 fds->events = POLLIN;
531 return;
533 case TLS_WANT_POLLOUT:
534 fds->events = POLLOUT;
535 return;
537 default:
538 c->i += ret;
539 len -= ret;
540 break;
544 goodbye(fds, c);
547 void
548 send_dir(char *path, struct pollfd *fds, struct client *client)
550 char fpath[PATHBUF];
551 size_t len;
553 bzero(fpath, PATHBUF);
555 if (path[0] != '.')
556 fpath[0] = '.';
558 /* this cannot fail since sizeof(fpath) > maxlen of path */
559 strlcat(fpath, path, PATHBUF);
560 len = strlen(fpath);
562 /* add a trailing / in case. */
563 if (fpath[len-1] != '/') {
564 fpath[len] = '/';
567 strlcat(fpath, "index.gmi", sizeof(fpath));
569 send_file(fpath, NULL, fds, client);
572 void
573 handle_handshake(struct pollfd *fds, struct client *c)
575 struct vhost *h;
576 const char *servname;
578 switch (tls_handshake(c->ctx)) {
579 case 0: /* success */
580 case -1: /* already handshaked */
581 break;
582 case TLS_WANT_POLLIN:
583 fds->events = POLLIN;
584 return;
585 case TLS_WANT_POLLOUT:
586 fds->events = POLLOUT;
587 return;
588 default:
589 /* unreachable */
590 abort();
593 servname = tls_conn_servername(c->ctx);
594 if (servname == NULL)
595 goto wronghost;
597 for (h = hosts; h->domain != NULL; ++h) {
598 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
599 break;
602 if (h->domain != NULL) {
603 c->state = S_OPEN;
604 c->host = h;
605 handle_open_conn(fds, c);
606 return;
609 wronghost:
610 /* XXX: check the correct response */
611 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
612 return;
613 goodbye(fds, c);
616 void
617 handle_open_conn(struct pollfd *fds, struct client *c)
619 char buf[GEMINI_URL_LEN];
620 const char *parse_err = "invalid request";
621 struct iri iri;
623 bzero(buf, sizeof(buf));
625 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
626 case -1:
627 LOGE(c, "tls_read: %s", tls_error(c->ctx));
628 goodbye(fds, c);
629 return;
631 case TLS_WANT_POLLIN:
632 fds->events = POLLIN;
633 return;
635 case TLS_WANT_POLLOUT:
636 fds->events = POLLOUT;
637 return;
640 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
641 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
642 return;
643 goodbye(fds, c);
644 return;
647 if (strcmp(iri.schema, "gemini")) {
648 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
649 return;
650 goodbye(fds, c);
651 return;
654 LOGI(c, "GET %s%s%s",
655 *iri.path ? iri.path : "/",
656 *iri.query ? "?" : "",
657 *iri.query ? iri.query : "");
659 send_file(iri.path, iri.query, fds, c);
662 void
663 handle(struct pollfd *fds, struct client *client)
665 switch (client->state) {
666 case S_HANDSHAKE:
667 handle_handshake(fds, client);
668 break;
670 case S_OPEN:
671 handle_open_conn(fds, client);
672 break;
674 case S_INITIALIZING:
675 if (!start_reply(fds, client, client->code, client->meta))
676 return;
678 if (client->code != SUCCESS) {
679 /* we don't need a body */
680 goodbye(fds, client);
681 return;
684 client->state = S_SENDING;
686 /* fallthrough */
688 case S_SENDING:
689 if (client->child != -1)
690 handle_cgi(fds, client);
691 else
692 send_file(NULL, NULL, fds, client);
693 break;
695 case S_CLOSING:
696 goodbye(fds, client);
697 break;
699 default:
700 /* unreachable */
701 abort();
705 void
706 mark_nonblock(int fd)
708 int flags;
710 if ((flags = fcntl(fd, F_GETFL)) == -1)
711 fatal("fcntl(F_GETFL): %s", strerror(errno));
712 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
713 fatal("fcntl(F_SETFL): %s", strerror(errno));
716 int
717 make_socket(int port, int family)
719 int sock, v;
720 struct sockaddr_in addr4;
721 struct sockaddr_in6 addr6;
722 struct sockaddr *addr;
723 socklen_t len;
725 switch (family) {
726 case AF_INET:
727 bzero(&addr4, sizeof(addr4));
728 addr4.sin_family = family;
729 addr4.sin_port = htons(port);
730 addr4.sin_addr.s_addr = INADDR_ANY;
731 addr = (struct sockaddr*)&addr4;
732 len = sizeof(addr4);
733 break;
735 case AF_INET6:
736 bzero(&addr6, sizeof(addr6));
737 addr6.sin6_family = AF_INET6;
738 addr6.sin6_port = htons(port);
739 addr6.sin6_addr = in6addr_any;
740 addr = (struct sockaddr*)&addr6;
741 len = sizeof(addr6);
742 break;
744 default:
745 /* unreachable */
746 abort();
749 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
750 fatal("socket: %s", strerror(errno));
752 v = 1;
753 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
754 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
756 v = 1;
757 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
758 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
760 mark_nonblock(sock);
762 if (bind(sock, addr, len) == -1)
763 fatal("bind: %s", strerror(errno));
765 if (listen(sock, 16) == -1)
766 fatal("listen: %s", strerror(errno));
768 return sock;
771 void
772 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
774 int i, fd;
775 struct sockaddr_storage addr;
776 socklen_t len;
778 len = sizeof(addr);
779 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
780 if (errno == EWOULDBLOCK)
781 return;
782 fatal("accept: %s", strerror(errno));
785 mark_nonblock(fd);
787 for (i = 0; i < MAX_USERS; ++i) {
788 if (fds[i].fd == -1) {
789 bzero(&clients[i], sizeof(struct client));
790 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
791 break; /* goodbye fd! */
793 fds[i].fd = fd;
794 fds[i].events = POLLIN;
796 clients[i].state = S_HANDSHAKE;
797 clients[i].fd = -1;
798 clients[i].child = -1;
799 clients[i].buf = MAP_FAILED;
800 clients[i].af = AF_INET;
801 clients[i].addr = addr;
803 connected_clients++;
804 return;
808 close(fd);
811 void
812 goodbye(struct pollfd *pfd, struct client *c)
814 ssize_t ret;
816 c->state = S_CLOSING;
818 ret = tls_close(c->ctx);
819 if (ret == TLS_WANT_POLLIN) {
820 pfd->events = POLLIN;
821 return;
823 if (ret == TLS_WANT_POLLOUT) {
824 pfd->events = POLLOUT;
825 return;
828 connected_clients--;
830 tls_free(c->ctx);
831 c->ctx = NULL;
833 if (c->buf != MAP_FAILED)
834 munmap(c->buf, c->len);
836 if (c->fd != -1)
837 close(c->fd);
839 close(pfd->fd);
840 pfd->fd = -1;
843 void
844 loop(struct tls *ctx, int sock4, int sock6)
846 int i;
847 struct client clients[MAX_USERS];
848 struct pollfd fds[MAX_USERS];
850 for (i = 0; i < MAX_USERS; ++i) {
851 fds[i].fd = -1;
852 fds[i].events = POLLIN;
853 bzero(&clients[i], sizeof(struct client));
856 fds[0].fd = sock4;
857 fds[1].fd = sock6;
859 for (;;) {
860 if (poll(fds, MAX_USERS, INFTIM) == -1) {
861 if (errno == EINTR) {
862 warnx("connected clients: %d",
863 connected_clients);
864 continue;
866 fatal("poll: %s", strerror(errno));
869 for (i = 0; i < MAX_USERS; i++) {
870 if (fds[i].revents == 0)
871 continue;
873 if (fds[i].revents & (POLLERR|POLLNVAL))
874 fatal("bad fd %d: %s", fds[i].fd,
875 strerror(errno));
877 if (fds[i].revents & POLLHUP) {
878 /* fds[i] may be the fd of the stdin
879 * of a cgi script that has exited. */
880 if (!clients[i].waiting_on_child) {
881 goodbye(&fds[i], &clients[i]);
882 continue;
886 if (fds[i].fd == sock4)
887 do_accept(sock4, ctx, fds, clients);
888 else if (fds[i].fd == sock6)
889 do_accept(sock6, ctx, fds, clients);
890 else
891 handle(&fds[i], &clients[i]);
896 char *
897 absolutify_path(const char *path)
899 char *wd, *r;
901 if (*path == '/')
902 return strdup(path);
904 wd = getwd(NULL);
905 if (asprintf(&r, "%s/%s", wd, path) == -1)
906 err(1, "asprintf");
907 free(wd);
908 return r;
911 void
912 yyerror(const char *msg)
914 goterror = 1;
915 fprintf(stderr, "%d: %s\n", yylineno, msg);
918 int
919 parse_portno(const char *p)
921 char *ep;
922 long lval;
924 errno = 0;
925 lval = strtol(p, &ep, 10);
926 if (p[0] == '\0' || *ep != '\0')
927 errx(1, "not a number: %s", p);
928 if (lval < 0 || lval > UINT16_MAX)
929 errx(1, "port number out of range for domain %s: %ld", p, lval);
930 return lval;
933 void
934 parse_conf(const char *path)
936 if ((yyin = fopen(path, "r")) == NULL)
937 err(1, "cannot open config %s", path);
938 yyparse();
939 fclose(yyin);
941 if (goterror)
942 exit(1);
945 void
946 load_vhosts(struct tls_config *tlsconf)
948 struct vhost *h;
950 /* we need to set something, then we can add how many key we want */
951 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
952 errx(1, "tls_config_set_keypair_file failed");
954 for (h = hosts; h->domain != NULL; ++h) {
955 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
956 errx(1, "failed to load the keypair (%s, %s)",
957 h->cert, h->key);
959 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
960 err(1, "open %s for domain %s", h->dir, h->domain);
964 /* we can augment this function to handle also capsicum and seccomp eventually */
965 void
966 sandbox()
968 struct vhost *h;
969 int has_cgi = 0;
971 for (h = hosts; h->domain != NULL; ++h) {
972 if (unveil(h->dir, "rx") == -1)
973 err(1, "unveil %s for domain %s", h->dir, h->domain);
975 if (h->cgi != NULL)
976 has_cgi = 1;
979 if (pledge("stdio rpath inet proc exec", NULL) == -1)
980 err(1, "pledge");
982 /* drop proc and exec if cgi isn't enabled */
983 if (!has_cgi)
984 if (pledge("stdio rpath inet", NULL) == -1)
985 err(1, "pledge");
988 void
989 usage(const char *me)
991 fprintf(stderr,
992 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
993 "[-p port] [-x cgi-bin]\n",
994 me);
997 int
998 main(int argc, char **argv)
1000 struct tls *ctx = NULL;
1001 struct tls_config *tlsconf;
1002 int sock4, sock6, ch;
1003 const char *config_path = NULL;
1004 size_t i;
1005 int conftest = 0, has_cgi = 0;
1007 bzero(hosts, sizeof(hosts));
1008 for (i = 0; i < HOSTSLEN; ++i)
1009 hosts[i].dirfd = -1;
1011 conf.foreground = 1;
1012 conf.port = 1965;
1013 conf.ipv6 = 0;
1015 connected_clients = 0;
1017 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
1018 switch (ch) {
1019 case '6':
1020 conf.ipv6 = 1;
1021 break;
1023 case 'C':
1024 hosts[0].cert = optarg;
1025 break;
1027 case 'c':
1028 config_path = optarg;
1029 break;
1031 case 'd':
1032 free((char*)hosts[0].dir);
1033 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
1034 err(1, "absolutify_path");
1035 break;
1037 case 'f':
1038 conf.foreground = 1;
1039 break;
1041 case 'h':
1042 usage(*argv);
1043 return 0;
1045 case 'K':
1046 hosts[0].key = optarg;
1047 break;
1049 case 'n':
1050 conftest = 1;
1051 break;
1053 case 'p':
1054 conf.port = parse_portno(optarg);
1056 case 'x':
1057 /* drop the starting / (if any) */
1058 if (*optarg == '/')
1059 optarg++;
1060 hosts[0].cgi = optarg;
1061 break;
1063 default:
1064 usage(*argv);
1065 return 1;
1069 if (config_path != NULL) {
1070 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
1071 hosts[0].dir != NULL)
1072 errx(1, "can't specify options in conf mode");
1073 parse_conf(config_path);
1074 } else {
1075 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
1076 hosts[0].dir == NULL)
1077 errx(1, "missing cert, key or root directory to serve");
1078 hosts[0].domain = "*";
1081 if (conftest)
1082 errx(0, "config OK");
1084 signal(SIGPIPE, SIG_IGN);
1085 signal(SIGCHLD, SIG_IGN);
1087 #ifdef SIGINFO
1088 signal(SIGINFO, sig_handler);
1089 #endif
1090 signal(SIGUSR2, sig_handler);
1092 if (!conf.foreground)
1093 signal(SIGHUP, SIG_IGN);
1095 if ((tlsconf = tls_config_new()) == NULL)
1096 err(1, "tls_config_new");
1098 /* optionally accept client certs, but don't try to verify them */
1099 tls_config_verify_client_optional(tlsconf);
1100 tls_config_insecure_noverifycert(tlsconf);
1102 if (tls_config_set_protocols(tlsconf,
1103 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1104 err(1, "tls_config_set_protocols");
1106 load_vhosts(tlsconf);
1108 if ((ctx = tls_server()) == NULL)
1109 err(1, "tls_server");
1111 if (tls_configure(ctx, tlsconf) == -1)
1112 errx(1, "tls_configure: %s", tls_error(ctx));
1114 sock4 = make_socket(conf.port, AF_INET);
1115 if (conf.ipv6)
1116 sock6 = make_socket(conf.port, AF_INET6);
1117 else
1118 sock6 = -1;
1121 if (!conf.foreground && daemon(0, 1) == -1)
1122 exit(1);
1124 sandbox();
1126 loop(ctx, sock4, sock6);
1128 close(sock4);
1129 close(sock6);
1130 tls_free(ctx);
1131 tls_config_free(tlsconf);
1133 return 0;