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 "gmid.h"
19 #include <sys/stat.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <getopt.h>
24 #include <libgen.h>
25 #include <limits.h>
26 #include <pwd.h>
27 #include <signal.h>
28 #include <string.h>
30 static const char *opts = "6c:D:d:fH:hnP:p:Vvx:";
32 static struct option longopts[] = {
33 {"help", no_argument, NULL, 'h'},
34 {"version", no_argument, NULL, 'V'},
35 {NULL, 0, NULL, 0},
36 };
38 struct fcgi fcgi[FCGI_MAX];
40 struct vhosthead hosts;
42 int sock4, sock6;
44 struct imsgbuf logibuf, exibuf, servibuf[PROC_MAX];
46 const char *config_path, *certs_dir, *hostname, *pidfile, *cgi;
48 struct conf conf;
50 struct tls_config *tlsconf;
51 struct tls *ctx;
53 static void
54 dummy_handler(int signo)
55 {
56 return;
57 }
59 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
60 static void
61 pdirname(const char *path, char *dn)
62 {
63 char p[PATH_MAX+1];
64 char *t;
66 strlcpy(p, path, sizeof(p));
67 t = dirname(p);
68 memmove(dn, t, strlen(t)+1);
69 }
71 static void
72 mkdirs(const char *path, mode_t mode)
73 {
74 char dname[PATH_MAX+1];
76 pdirname(path, dname);
77 if (!strcmp(dname, "/"))
78 return;
79 mkdirs(dname, mode);
80 if (mkdir(path, mode) != 0 && errno != EEXIST)
81 fatal("can't mkdir %s: %s", path, strerror(errno));
82 }
84 /* $XDG_DATA_HOME/gmid */
85 char *
86 data_dir(void)
87 {
88 const char *home, *xdg;
89 char *t;
91 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
92 if ((home = getenv("HOME")) == NULL)
93 errx(1, "XDG_DATA_HOME and HOME both empty");
94 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
95 err(1, "asprintf");
96 } else {
97 if (asprintf(&t, "%s/gmid", xdg) == -1)
98 err(1, "asprintf");
99 }
101 mkdirs(t, 0755);
102 return t;
105 void
106 load_local_cert(const char *hostname, const char *dir)
108 char *cert, *key;
109 struct vhost *h;
111 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
112 errx(1, "asprintf");
113 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
114 errx(1, "asprintf");
116 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
117 gen_certificate(hostname, cert, key);
119 h = TAILQ_FIRST(&hosts);
120 h->cert = cert;
121 h->key = key;
122 h->domain = hostname;
125 void
126 load_vhosts(void)
128 struct vhost *h;
129 struct location *l;
131 TAILQ_FOREACH(h, &hosts, vhosts) {
132 TAILQ_FOREACH(l, &h->locations, locations) {
133 if (l->dir == NULL)
134 continue;
135 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
136 fatal("open %s for domain %s: %s", l->dir, h->domain,
137 strerror(errno));
142 int
143 make_socket(int port, int family)
145 int sock, v;
146 struct sockaddr_in addr4;
147 struct sockaddr_in6 addr6;
148 struct sockaddr *addr;
149 socklen_t len;
151 switch (family) {
152 case AF_INET:
153 memset(&addr4, 0, sizeof(addr4));
154 addr4.sin_family = family;
155 addr4.sin_port = htons(port);
156 addr4.sin_addr.s_addr = INADDR_ANY;
157 addr = (struct sockaddr*)&addr4;
158 len = sizeof(addr4);
159 break;
161 case AF_INET6:
162 memset(&addr6, 0, sizeof(addr6));
163 addr6.sin6_family = AF_INET6;
164 addr6.sin6_port = htons(port);
165 addr6.sin6_addr = in6addr_any;
166 addr = (struct sockaddr*)&addr6;
167 len = sizeof(addr6);
168 break;
170 default:
171 /* unreachable */
172 abort();
175 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
176 fatal("socket: %s", strerror(errno));
178 v = 1;
179 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
180 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
182 v = 1;
183 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
184 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
186 mark_nonblock(sock);
188 if (bind(sock, addr, len) == -1)
189 fatal("bind: %s", strerror(errno));
191 if (listen(sock, 16) == -1)
192 fatal("listen: %s", strerror(errno));
194 return sock;
197 static void
198 add_keypair(struct vhost *h)
200 if (h->ocsp == NULL) {
201 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
202 fatal("failed to load the keypair (%s, %s)",
203 h->cert, h->key);
204 } else {
205 if (tls_config_add_keypair_ocsp_file(tlsconf, h->cert, h->key,
206 h->ocsp) == -1)
207 fatal("failed to load the keypair (%s, %s, %s)",
208 h->cert, h->key, h->ocsp);
212 void
213 setup_tls(void)
215 struct vhost *h;
217 if ((tlsconf = tls_config_new()) == NULL)
218 fatal("tls_config_new");
220 /* optionally accept client certs, but don't try to verify them */
221 tls_config_verify_client_optional(tlsconf);
222 tls_config_insecure_noverifycert(tlsconf);
224 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
225 fatal("tls_config_set_protocols");
227 if ((ctx = tls_server()) == NULL)
228 fatal("tls_server failure");
230 h = TAILQ_FIRST(&hosts);
232 /* we need to set something, then we can add how many key we want */
233 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
234 fatal("tls_config_set_keypair_file failed for (%s, %s)",
235 h->cert, h->key);
237 /* same for OCSP */
238 if (h->ocsp != NULL &&
239 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
240 fatal("tls_config_set_ocsp_staple_file failed for (%s)",
241 h->ocsp);
243 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
244 add_keypair(h);
246 if (tls_configure(ctx, tlsconf) == -1)
247 fatal("tls_configure: %s", tls_error(ctx));
250 static int
251 listener_main(struct imsgbuf *ibuf)
253 drop_priv();
254 load_default_mime(&conf.mime);
255 load_vhosts();
256 loop(ctx, sock4, sock6, ibuf);
257 return 0;
260 void
261 init_config(void)
263 TAILQ_INIT(&hosts);
265 conf.port = 1965;
266 conf.ipv6 = 0;
267 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
269 init_mime(&conf.mime);
271 conf.chroot = NULL;
272 conf.user = NULL;
274 conf.prefork = 3;
277 void
278 free_config(void)
280 struct vhost *h, *th;
281 struct location *l, *tl;
282 struct envlist *e, *te;
283 struct alist *a, *ta;
284 int v, i;
286 v = conf.verbose;
288 free(conf.chroot);
289 free(conf.user);
290 memset(&conf, 0, sizeof(conf));
292 conf.verbose = v;
294 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
295 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
296 TAILQ_REMOVE(&h->locations, l, locations);
298 free((char*)l->match);
299 free((char*)l->lang);
300 free((char*)l->default_mime);
301 free((char*)l->index);
302 free((char*)l->block_fmt);
303 free((char*)l->dir);
305 if (l->dirfd != -1)
306 close(l->dirfd);
308 free(l);
311 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
312 TAILQ_REMOVE(&h->env, e, envs);
314 free(e->name);
315 free(e->value);
316 free(e);
319 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
320 TAILQ_REMOVE(&h->params, e, envs);
322 free(e->name);
323 free(e->value);
324 free(e);
327 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
328 TAILQ_REMOVE(&h->aliases, a, aliases);
330 free(a->alias);
331 free(a);
334 free((char*)h->domain);
335 free((char*)h->cert);
336 free((char*)h->key);
337 free((char*)h->ocsp);
338 free((char*)h->cgi);
339 free((char*)h->entrypoint);
341 free(h->proxy.host);
342 tls_unload_file(h->proxy.cert, h->proxy.certlen);
343 tls_unload_file(h->proxy.key, h->proxy.keylen);
345 TAILQ_REMOVE(&hosts, h, vhosts);
346 free(h);
349 for (i = 0; i < FCGI_MAX; ++i) {
350 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
351 break;
352 free(fcgi[i].path);
353 free(fcgi[i].port);
354 free(fcgi[i].prog);
356 fcgi[i].path = NULL;
357 fcgi[i].port = NULL;
358 fcgi[i].prog = NULL;
361 tls_free(ctx);
362 tls_config_free(tlsconf);
365 static int
366 wait_signal(void)
368 sigset_t mask;
369 int signo;
371 sigemptyset(&mask);
372 sigaddset(&mask, SIGHUP);
373 sigaddset(&mask, SIGINT);
374 sigaddset(&mask, SIGTERM);
375 sigwait(&mask, &signo);
377 return signo == SIGHUP;
380 void
381 drop_priv(void)
383 struct passwd *pw = NULL;
385 if (conf.chroot != NULL && conf.user == NULL)
386 fatal("can't chroot without an user to switch to after.");
388 if (conf.user != NULL) {
389 if ((pw = getpwnam(conf.user)) == NULL)
390 fatal("can't find user %s", conf.user);
393 if (conf.chroot != NULL) {
394 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
395 fatal("%s: %s", conf.chroot, strerror(errno));
398 if (pw != NULL) {
399 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
400 fatal("setresuid(%d): %s", pw->pw_uid,
401 strerror(errno));
404 if (getuid() == 0)
405 log_warn(NULL, "not a good idea to run a network daemon as root");
408 static void
409 usage(void)
411 fprintf(stderr,
412 "Version: " GMID_STRING "\n"
413 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
414 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
415 getprogname(),
416 getprogname());
419 static void
420 logger_init(void)
422 int p[2];
424 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
425 err(1, "socketpair");
427 switch (fork()) {
428 case -1:
429 err(1, "fork");
430 case 0:
431 signal(SIGHUP, SIG_IGN);
432 close(p[0]);
433 setproctitle("logger");
434 imsg_init(&logibuf, p[1]);
435 drop_priv();
436 _exit(logger_main(p[1], &logibuf));
437 default:
438 close(p[1]);
439 imsg_init(&logibuf, p[0]);
440 return;
444 static int
445 serve(int argc, char **argv, struct imsgbuf *ibuf)
447 char path[PATH_MAX];
448 int i, p[2];
449 struct vhost *h;
450 struct location *l;
452 if (config_path == NULL) {
453 if (hostname == NULL)
454 hostname = "localhost";
455 if (certs_dir == NULL)
456 certs_dir = data_dir();
457 load_local_cert(hostname, certs_dir);
459 h = TAILQ_FIRST(&hosts);
460 h->domain = "*";
462 l = TAILQ_FIRST(&h->locations);
463 l->auto_index = 1;
464 l->match = "*";
466 switch (argc) {
467 case 0:
468 l->dir = getcwd(path, sizeof(path));
469 break;
470 case 1:
471 l->dir = absolutify_path(argv[0]);
472 break;
473 default:
474 usage();
475 return 1;
478 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
481 /* setup tls before dropping privileges: we don't want user
482 * to put private certs inside the chroot. */
483 setup_tls();
485 for (i = 0; i < conf.prefork; ++i) {
486 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
487 PF_UNSPEC, p) == -1)
488 fatal("socketpair: %s", strerror(errno));
490 switch (fork()) {
491 case -1:
492 fatal("fork: %s", strerror(errno));
493 case 0: /* child */
494 close(p[0]);
495 imsg_init(&exibuf, p[1]);
496 setproctitle("server");
497 _exit(listener_main(&exibuf));
498 default:
499 close(p[1]);
500 imsg_init(&servibuf[i], p[0]);
504 setproctitle("executor");
505 drop_priv();
506 _exit(executor_main(ibuf));
509 static int
510 write_pidfile(const char *pidfile)
512 struct flock lock;
513 int fd;
515 if (pidfile == NULL)
516 return -1;
518 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
519 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
521 lock.l_start = 0;
522 lock.l_len = 0;
523 lock.l_type = F_WRLCK;
524 lock.l_whence = SEEK_SET;
526 if (fcntl(fd, F_SETLK, &lock) == -1)
527 fatal("can't lock %s, gmid is already running?", pidfile);
529 if (ftruncate(fd, 0) == -1)
530 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
532 dprintf(fd, "%d\n", getpid());
534 return fd;
537 static void
538 setup_configless(int argc, char **argv, const char *cgi)
540 struct vhost *host;
541 struct location *loc;
543 host = xcalloc(1, sizeof(*host));
544 host->cgi = cgi;
545 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
547 loc = xcalloc(1, sizeof(*loc));
548 loc->fcgi = -1;
549 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
551 serve(argc, argv, NULL);
553 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
554 imsg_flush(&logibuf);
557 static int
558 parse_portno(const char *p)
560 const char *errstr;
561 int n;
563 n = strtonum(p, 0, UINT16_MAX, &errstr);
564 if (errstr != NULL)
565 yyerror("port number is %s: %s", errstr, p);
566 return n;
569 int
570 main(int argc, char **argv)
572 struct imsgbuf exibuf;
573 int ch, conftest = 0, configless = 0;
574 int pidfd, old_ipv6, old_port;
576 logger_init();
577 init_config();
579 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
580 switch (ch) {
581 case '6':
582 conf.ipv6 = 1;
583 configless = 1;
584 break;
586 case 'c':
587 config_path = absolutify_path(optarg);
588 break;
590 case 'D':
591 if (cmdline_symset(optarg) == -1)
592 fatal("could not parse macro definition: %s",
593 optarg);
594 break;
596 case 'd':
597 certs_dir = optarg;
598 configless = 1;
599 break;
601 case 'f':
602 conf.foreground = 1;
603 break;
605 case 'H':
606 hostname = optarg;
607 configless = 1;
608 break;
610 case 'h':
611 usage();
612 return 0;
614 case 'n':
615 conftest++;
616 break;
618 case 'P':
619 pidfile = optarg;
620 break;
622 case 'p':
623 conf.port = parse_portno(optarg);
624 configless = 1;
625 break;
627 case 'V':
628 puts("Version: " GMID_STRING);
629 return 0;
631 case 'v':
632 conf.verbose++;
633 break;
635 case 'x':
636 /* drop the starting / (if any) */
637 if (*optarg == '/')
638 optarg++;
639 cgi = optarg;
640 configless = 1;
641 break;
643 default:
644 usage();
645 return 1;
648 argc -= optind;
649 argv += optind;
651 if (config_path == NULL) {
652 configless = 1;
653 conf.foreground = 1;
654 conf.prefork = 1;
655 conf.verbose++;
658 if (config_path != NULL && (argc > 0 || configless))
659 fatal("can't specify options in config mode.");
661 if (conftest) {
662 if (config_path == NULL)
663 fatal("missing configuration");
664 parse_conf(config_path);
665 fprintf(stderr, "config OK\n");
666 if (conftest > 1)
667 print_conf();
668 return 0;
671 if (!conf.foreground && !configless) {
672 /* log to syslog */
673 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
674 imsg_flush(&logibuf);
676 if (daemon(1, 1) == -1)
677 fatal("daemon: %s", strerror(errno));
680 if (config_path != NULL)
681 parse_conf(config_path);
683 sock4 = make_socket(conf.port, AF_INET);
684 sock6 = -1;
685 if (conf.ipv6)
686 sock6 = make_socket(conf.port, AF_INET6);
688 signal(SIGPIPE, SIG_IGN);
689 signal(SIGCHLD, SIG_IGN);
691 if (configless) {
692 setup_configless(argc, argv, cgi);
693 return 0;
696 pidfd = write_pidfile(pidfile);
698 /*
699 * Linux seems to call the event handlers even when we're
700 * doing a sigwait. These dummy handlers are here to avoid
701 * being terminated on SIGHUP, SIGINT or SIGTERM.
702 */
703 signal(SIGHUP, dummy_handler);
704 signal(SIGINT, dummy_handler);
705 signal(SIGTERM, dummy_handler);
707 /* wait a sighup and reload the daemon */
708 for (;;) {
709 int p[2];
711 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
712 PF_UNSPEC, p) == -1)
713 fatal("socketpair: %s", strerror(errno));
715 switch (fork()) {
716 case -1:
717 fatal("fork: %s", strerror(errno));
718 case 0:
719 close(p[0]);
720 imsg_init(&exibuf, p[1]);
721 _exit(serve(argc, argv, &exibuf));
724 close(p[1]);
725 imsg_init(&exibuf, p[0]);
727 if (!wait_signal())
728 break;
730 log_info(NULL, "reloading configuration %s", config_path);
732 /* close the executor (it'll close the servers too) */
733 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
734 imsg_flush(&exibuf);
735 close(p[0]);
737 old_ipv6 = conf.ipv6;
738 old_port = conf.port;
740 free_config();
741 init_config();
742 parse_conf(config_path);
744 if (old_port != conf.port) {
745 close(sock4);
746 close(sock6);
747 sock4 = -1;
748 sock6 = -1;
751 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
752 close(sock6);
753 sock6 = -1;
756 if (sock4 == -1)
757 sock4 = make_socket(conf.port, AF_INET);
758 if (sock6 == -1 && conf.ipv6)
759 sock6 = make_socket(conf.port, AF_INET6);
762 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
763 imsg_flush(&exibuf);
765 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
766 imsg_flush(&logibuf);
768 if (pidfd != -1)
769 close(pidfd);
771 return 0;