2 * Copyright (c) 2020, 2021, 2022 Omar Polo <op@omarpolo.com>
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.
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.
31 static const char *opts = "6c:D:d:fH:hnP:p:Vvx:";
33 static const struct option longopts[] = {
34 {"help", no_argument, NULL, 'h'},
35 {"version", no_argument, NULL, 'V'},
39 struct fcgi fcgi[FCGI_MAX];
41 struct vhosthead hosts;
45 struct imsgbuf logibuf, exibuf, servibuf[PROC_MAX];
47 const char *config_path, *certs_dir, *hostname, *pidfile, *cgi;
51 struct tls_config *tlsconf;
55 dummy_handler(int signo)
60 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
62 pdirname(const char *path, char *dn)
67 strlcpy(p, path, sizeof(p));
69 memmove(dn, t, strlen(t)+1);
73 mkdirs(const char *path, mode_t mode)
75 char dname[PATH_MAX+1];
77 pdirname(path, dname);
78 if (!strcmp(dname, "/"))
81 if (mkdir(path, mode) != 0 && errno != EEXIST)
82 fatal("can't mkdir %s: %s", path, strerror(errno));
85 /* $XDG_DATA_HOME/gmid */
89 const char *home, *xdg;
92 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
93 if ((home = getenv("HOME")) == NULL)
94 errx(1, "XDG_DATA_HOME and HOME both empty");
95 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
98 if (asprintf(&t, "%s/gmid", xdg) == -1)
107 load_local_cert(const char *hostname, const char *dir)
112 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
114 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
117 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
118 gen_certificate(hostname, cert, key);
120 h = TAILQ_FIRST(&hosts);
123 h->domain = hostname;
132 TAILQ_FOREACH(h, &hosts, vhosts) {
133 TAILQ_FOREACH(l, &h->locations, locations) {
136 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
137 fatal("open %s for domain %s: %s", l->dir, h->domain,
144 make_socket(int port, int family)
147 struct sockaddr_in addr4;
148 struct sockaddr_in6 addr6;
149 struct sockaddr *addr;
154 memset(&addr4, 0, sizeof(addr4));
155 addr4.sin_family = family;
156 addr4.sin_port = htons(port);
157 addr4.sin_addr.s_addr = INADDR_ANY;
158 addr = (struct sockaddr*)&addr4;
163 memset(&addr6, 0, sizeof(addr6));
164 addr6.sin6_family = AF_INET6;
165 addr6.sin6_port = htons(port);
166 addr6.sin6_addr = in6addr_any;
167 addr = (struct sockaddr*)&addr6;
176 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
177 fatal("socket: %s", strerror(errno));
180 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
181 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
184 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
185 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
189 if (bind(sock, addr, len) == -1)
190 fatal("bind: %s", strerror(errno));
192 if (listen(sock, 16) == -1)
193 fatal("listen: %s", strerror(errno));
199 add_keypair(struct vhost *h)
201 if (h->ocsp == NULL) {
202 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
203 fatal("failed to load the keypair (%s, %s)",
206 if (tls_config_add_keypair_ocsp_file(tlsconf, h->cert, h->key,
208 fatal("failed to load the keypair (%s, %s, %s)",
209 h->cert, h->key, h->ocsp);
218 if ((tlsconf = tls_config_new()) == NULL)
219 fatal("tls_config_new");
221 /* optionally accept client certs, but don't try to verify them */
222 tls_config_verify_client_optional(tlsconf);
223 tls_config_insecure_noverifycert(tlsconf);
225 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
226 fatal("tls_config_set_protocols");
228 if ((ctx = tls_server()) == NULL)
229 fatal("tls_server failure");
231 h = TAILQ_FIRST(&hosts);
233 /* we need to set something, then we can add how many key we want */
234 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
235 fatal("tls_config_set_keypair_file failed for (%s, %s)",
239 if (h->ocsp != NULL &&
240 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
241 fatal("tls_config_set_ocsp_staple_file failed for (%s)",
244 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
247 if (tls_configure(ctx, tlsconf) == -1)
248 fatal("tls_configure: %s", tls_error(ctx));
252 listener_main(struct imsgbuf *ibuf)
255 if (!conf.mime.skip_defaults && load_default_mime(&conf.mime) == -1)
256 fatal("load_default_mime: %s", strerror(errno));
257 sort_mime(&conf.mime);
259 loop(ctx, sock4, sock6, ibuf);
270 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
272 init_mime(&conf.mime);
283 struct vhost *h, *th;
284 struct location *l, *tl;
285 struct proxy *p, *tp;
286 struct envlist *e, *te;
287 struct alist *a, *ta;
292 free_mime(&conf.mime);
295 memset(&conf, 0, sizeof(conf));
299 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
300 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
301 TAILQ_REMOVE(&h->locations, l, locations);
303 free((char*)l->match);
304 free((char*)l->lang);
305 free((char*)l->default_mime);
306 free((char*)l->index);
307 free((char*)l->block_fmt);
316 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
317 TAILQ_REMOVE(&h->env, e, envs);
324 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
325 TAILQ_REMOVE(&h->params, e, envs);
332 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
333 TAILQ_REMOVE(&h->aliases, a, aliases);
339 TAILQ_FOREACH_SAFE(p, &h->proxies, proxies, tp) {
340 TAILQ_REMOVE(&h->proxies, p, proxies);
342 free(p->match_proto);
346 tls_unload_file(p->cert, p->certlen);
347 tls_unload_file(p->key, p->keylen);
351 free((char*)h->domain);
352 free((char*)h->cert);
354 free((char*)h->ocsp);
356 free((char*)h->entrypoint);
358 TAILQ_REMOVE(&hosts, h, vhosts);
362 for (i = 0; i < FCGI_MAX; ++i) {
363 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
375 tls_config_free(tlsconf);
385 sigaddset(&mask, SIGHUP);
386 sigaddset(&mask, SIGINT);
387 sigaddset(&mask, SIGTERM);
388 sigwait(&mask, &signo);
390 return signo == SIGHUP;
396 struct passwd *pw = NULL;
398 if (conf.chroot != NULL && conf.user == NULL)
399 fatal("can't chroot without an user to switch to after.");
401 if (conf.user != NULL) {
402 if ((pw = getpwnam(conf.user)) == NULL)
403 fatal("can't find user %s", conf.user);
406 if (conf.chroot != NULL) {
407 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
408 fatal("%s: %s", conf.chroot, strerror(errno));
412 if (setgroups(1, &pw->pw_gid) == -1 ||
413 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1 ||
414 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
415 fatal("cannot drop privileges");
419 log_warn(NULL, "not a good idea to run a network daemon as root");
426 "Version: " GMID_STRING "\n"
427 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
428 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
438 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
439 err(1, "socketpair");
445 signal(SIGHUP, SIG_IGN);
447 setproctitle("logger");
448 imsg_init(&logibuf, p[1]);
450 _exit(logger_main(p[1], &logibuf));
453 imsg_init(&logibuf, p[0]);
459 serve(int argc, char **argv, struct imsgbuf *ibuf)
466 if (config_path == NULL) {
467 if (hostname == NULL)
468 hostname = "localhost";
469 if (certs_dir == NULL)
470 certs_dir = data_dir();
471 load_local_cert(hostname, certs_dir);
473 h = TAILQ_FIRST(&hosts);
476 l = TAILQ_FIRST(&h->locations);
482 l->dir = getcwd(path, sizeof(path));
485 l->dir = absolutify_path(argv[0]);
492 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
495 /* setup tls before dropping privileges: we don't want user
496 * to put private certs inside the chroot. */
499 for (i = 0; i < conf.prefork; ++i) {
500 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
502 fatal("socketpair: %s", strerror(errno));
506 fatal("fork: %s", strerror(errno));
509 imsg_init(&exibuf, p[1]);
510 setproctitle("server");
511 _exit(listener_main(&exibuf));
514 imsg_init(&servibuf[i], p[0]);
518 setproctitle("executor");
520 _exit(executor_main(ibuf));
524 write_pidfile(const char *pidfile)
532 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
533 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
537 lock.l_type = F_WRLCK;
538 lock.l_whence = SEEK_SET;
540 if (fcntl(fd, F_SETLK, &lock) == -1)
541 fatal("can't lock %s, gmid is already running?", pidfile);
543 if (ftruncate(fd, 0) == -1)
544 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
546 dprintf(fd, "%d\n", getpid());
552 setup_configless(int argc, char **argv, const char *cgi)
555 struct location *loc;
557 host = xcalloc(1, sizeof(*host));
559 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
561 loc = xcalloc(1, sizeof(*loc));
563 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
565 serve(argc, argv, NULL);
567 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
568 imsg_flush(&logibuf);
572 parse_portno(const char *p)
577 n = strtonum(p, 0, UINT16_MAX, &errstr);
579 yyerror("port number is %s: %s", errstr, p);
584 main(int argc, char **argv)
586 struct imsgbuf exibuf;
587 int ch, conftest = 0, configless = 0;
588 int pidfd, old_ipv6, old_port;
593 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
601 config_path = absolutify_path(optarg);
605 if (cmdline_symset(optarg) == -1)
606 fatal("could not parse macro definition: %s",
637 conf.port = parse_portno(optarg);
642 puts("Version: " GMID_STRING);
650 /* drop the starting / (if any) */
665 if (config_path == NULL) {
672 if (config_path != NULL && (argc > 0 || configless))
673 fatal("can't specify options in config mode.");
676 if (config_path == NULL)
677 fatal("missing configuration");
678 parse_conf(config_path);
679 fprintf(stderr, "config OK\n");
685 if (!conf.foreground && !configless) {
687 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
688 imsg_flush(&logibuf);
690 if (daemon(1, 1) == -1)
691 fatal("daemon: %s", strerror(errno));
694 if (config_path != NULL)
695 parse_conf(config_path);
697 sock4 = make_socket(conf.port, AF_INET);
700 sock6 = make_socket(conf.port, AF_INET6);
702 signal(SIGPIPE, SIG_IGN);
703 signal(SIGCHLD, SIG_IGN);
706 setup_configless(argc, argv, cgi);
710 pidfd = write_pidfile(pidfile);
713 * Linux seems to call the event handlers even when we're
714 * doing a sigwait. These dummy handlers are here to avoid
715 * being terminated on SIGHUP, SIGINT or SIGTERM.
717 signal(SIGHUP, dummy_handler);
718 signal(SIGINT, dummy_handler);
719 signal(SIGTERM, dummy_handler);
721 /* wait a sighup and reload the daemon */
725 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
727 fatal("socketpair: %s", strerror(errno));
731 fatal("fork: %s", strerror(errno));
734 imsg_init(&exibuf, p[1]);
735 _exit(serve(argc, argv, &exibuf));
739 imsg_init(&exibuf, p[0]);
744 log_info(NULL, "reloading configuration %s", config_path);
746 /* close the executor (it'll close the servers too) */
747 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
751 old_ipv6 = conf.ipv6;
752 old_port = conf.port;
756 parse_conf(config_path);
758 if (old_port != conf.port) {
765 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
771 sock4 = make_socket(conf.port, AF_INET);
772 if (sock6 == -1 && conf.ipv6)
773 sock6 = make_socket(conf.port, AF_INET6);
776 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
779 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
780 imsg_flush(&logibuf);