2 * Copyright (c) 2020 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.
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'},
38 struct fcgi fcgi[FCGI_MAX];
40 struct vhosthead hosts;
44 struct imsgbuf logibuf, exibuf, servibuf[PROC_MAX];
46 const char *config_path, *certs_dir, *hostname, *pidfile, *cgi;
50 struct tls_config *tlsconf;
54 dummy_handler(int signo)
59 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
61 pdirname(const char *path, char *dn)
66 strlcpy(p, path, sizeof(p));
68 memmove(dn, t, strlen(t)+1);
72 mkdirs(const char *path, mode_t mode)
74 char dname[PATH_MAX+1];
76 pdirname(path, dname);
77 if (!strcmp(dname, "/"))
80 if (mkdir(path, mode) != 0 && errno != EEXIST)
81 fatal("can't mkdir %s: %s", path, strerror(errno));
84 /* $XDG_DATA_HOME/gmid */
88 const char *home, *xdg;
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)
97 if (asprintf(&t, "%s/gmid", xdg) == -1)
106 load_local_cert(const char *hostname, const char *dir)
111 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
113 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
116 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
117 gen_certificate(hostname, cert, key);
119 h = TAILQ_FIRST(&hosts);
122 h->domain = hostname;
131 TAILQ_FOREACH(h, &hosts, vhosts) {
132 TAILQ_FOREACH(l, &h->locations, locations) {
135 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
136 fatal("open %s for domain %s", l->dir, h->domain);
142 make_socket(int port, int family)
145 struct sockaddr_in addr4;
146 struct sockaddr_in6 addr6;
147 struct sockaddr *addr;
152 bzero(&addr4, sizeof(addr4));
153 addr4.sin_family = family;
154 addr4.sin_port = htons(port);
155 addr4.sin_addr.s_addr = INADDR_ANY;
156 addr = (struct sockaddr*)&addr4;
161 bzero(&addr6, sizeof(addr6));
162 addr6.sin6_family = AF_INET6;
163 addr6.sin6_port = htons(port);
164 addr6.sin6_addr = in6addr_any;
165 addr = (struct sockaddr*)&addr6;
174 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
175 fatal("socket: %s", strerror(errno));
178 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
179 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
182 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
183 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
187 if (bind(sock, addr, len) == -1)
188 fatal("bind: %s", strerror(errno));
190 if (listen(sock, 16) == -1)
191 fatal("listen: %s", strerror(errno));
201 if ((tlsconf = tls_config_new()) == NULL)
202 fatal("tls_config_new");
204 /* optionally accept client certs, but don't try to verify them */
205 tls_config_verify_client_optional(tlsconf);
206 tls_config_insecure_noverifycert(tlsconf);
208 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
209 fatal("tls_config_set_protocols");
211 if ((ctx = tls_server()) == NULL)
212 fatal("tls_server failure");
214 h = TAILQ_FIRST(&hosts);
216 /* we need to set something, then we can add how many key we want */
217 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
218 fatal("tls_config_set_keypair_file failed for (%s, %s)",
221 while ((h = TAILQ_NEXT(h, vhosts)) != NULL) {
222 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
223 fatal("failed to load the keypair (%s, %s)",
227 if (tls_configure(ctx, tlsconf) == -1)
228 fatal("tls_configure: %s", tls_error(ctx));
232 listener_main(struct imsgbuf *ibuf)
235 load_default_mime(&conf.mime);
237 loop(ctx, sock4, sock6, ibuf);
248 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
250 init_mime(&conf.mime);
261 struct vhost *h, *th;
262 struct location *l, *tl;
263 struct envlist *e, *te;
264 struct alist *a, *ta;
271 memset(&conf, 0, sizeof(conf));
275 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
276 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
277 TAILQ_REMOVE(&h->locations, l, locations);
279 free((char*)l->match);
280 free((char*)l->lang);
281 free((char*)l->default_mime);
282 free((char*)l->index);
283 free((char*)l->block_fmt);
292 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
293 TAILQ_REMOVE(&h->env, e, envs);
300 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
301 TAILQ_REMOVE(&h->params, e, envs);
308 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
309 TAILQ_REMOVE(&h->aliases, a, aliases);
315 free((char*)h->domain);
316 free((char*)h->cert);
319 free((char*)h->entrypoint);
321 TAILQ_REMOVE(&hosts, h, vhosts);
325 for (i = 0; i < FCGI_MAX; ++i) {
326 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
337 fcgi[i].s = FCGI_OFF;
341 tls_config_free(tlsconf);
351 sigaddset(&mask, SIGHUP);
352 sigaddset(&mask, SIGINT);
353 sigaddset(&mask, SIGTERM);
354 sigwait(&mask, &signo);
356 return signo == SIGHUP;
362 struct passwd *pw = NULL;
364 if (conf.chroot != NULL && conf.user == NULL)
365 fatal("can't chroot without an user to switch to after.");
367 if (conf.user != NULL) {
368 if ((pw = getpwnam(conf.user)) == NULL)
369 fatal("can't find user %s", conf.user);
372 if (conf.chroot != NULL) {
373 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
374 fatal("%s: %s", conf.chroot, strerror(errno));
378 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
379 fatal("setresuid(%d): %s", pw->pw_uid,
384 log_warn(NULL, "not a good idea to run a network daemon as root");
391 "Version: " GMID_STRING "\n"
392 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
393 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
403 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
404 err(1, "socketpair");
410 signal(SIGHUP, SIG_IGN);
412 setproctitle("logger");
413 imsg_init(&logibuf, p[1]);
415 _exit(logger_main(p[1], &logibuf));
418 imsg_init(&logibuf, p[0]);
424 serve(int argc, char **argv, struct imsgbuf *ibuf)
431 if (config_path == NULL) {
432 if (hostname == NULL)
433 hostname = "localhost";
434 if (certs_dir == NULL)
435 certs_dir = data_dir();
436 load_local_cert(hostname, certs_dir);
438 h = TAILQ_FIRST(&hosts);
441 l = TAILQ_FIRST(&h->locations);
447 l->dir = getcwd(path, sizeof(path));
450 l->dir = absolutify_path(argv[0]);
457 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
460 /* setup tls before dropping privileges: we don't want user
461 * to put private certs inside the chroot. */
464 for (i = 0; i < conf.prefork; ++i) {
465 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
467 fatal("socketpair: %s", strerror(errno));
471 fatal("fork: %s", strerror(errno));
474 imsg_init(&exibuf, p[1]);
475 setproctitle("server");
476 _exit(listener_main(&exibuf));
479 imsg_init(&servibuf[i], p[0]);
483 setproctitle("executor");
485 _exit(executor_main(ibuf));
489 write_pidfile(const char *pidfile)
497 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
498 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
502 lock.l_type = F_WRLCK;
503 lock.l_whence = SEEK_SET;
505 if (fcntl(fd, F_SETLK, &lock) == -1)
506 fatal("can't lock %s, gmid is already running?", pidfile);
508 if (ftruncate(fd, 0) == -1)
509 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
511 dprintf(fd, "%d\n", getpid());
517 setup_configless(int argc, char **argv, const char *cgi)
520 struct location *loc;
522 host = xcalloc(1, sizeof(*host));
524 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
526 loc = xcalloc(1, sizeof(*loc));
527 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
529 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, 2, NULL, 0);
530 imsg_flush(&logibuf);
532 serve(argc, argv, NULL);
534 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
535 imsg_flush(&logibuf);
539 main(int argc, char **argv)
541 struct imsgbuf exibuf;
542 int ch, conftest = 0, configless = 0;
543 int pidfd, old_ipv6, old_port;
547 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
555 config_path = absolutify_path(optarg);
559 if (cmdline_symset(optarg) == -1)
560 errx(1, "invalid macro: %s", optarg);
590 conf.port = parse_portno(optarg);
595 puts("Version: " GMID_STRING);
603 /* drop the starting / (if any) */
618 if (config_path == NULL) {
625 if (config_path != NULL && (argc > 0 || configless))
626 errx(1, "can't specify options in config mode.");
629 parse_conf(config_path);
634 if (!conf.foreground && !configless) {
635 if (daemon(1, 1) == -1)
639 if (config_path != NULL)
640 parse_conf(config_path);
644 sock4 = make_socket(conf.port, AF_INET);
647 sock6 = make_socket(conf.port, AF_INET6);
649 signal(SIGPIPE, SIG_IGN);
650 signal(SIGCHLD, SIG_IGN);
653 setup_configless(argc, argv, cgi);
657 if (conf.foreground) {
658 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, 2, NULL, 0);
659 imsg_flush(&logibuf);
662 pidfd = write_pidfile(pidfile);
664 /* Linux seems to call the event handlers even when we're
665 * doing a sigwait. These dummy handlers are here to avoid
666 * being terminated on SIGHUP, SIGINT or SIGTERM. */
667 signal(SIGHUP, dummy_handler);
668 signal(SIGINT, dummy_handler);
669 signal(SIGTERM, dummy_handler);
671 /* wait a sighup and reload the daemon */
675 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
677 fatal("socketpair: %s", strerror(errno));
681 fatal("fork: %s", strerror(errno));
684 imsg_init(&exibuf, p[1]);
685 _exit(serve(argc, argv, &exibuf));
689 imsg_init(&exibuf, p[0]);
694 log_info(NULL, "reloading configuration %s", config_path);
696 /* close the executor (it'll close the servers too) */
697 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
701 old_ipv6 = conf.ipv6;
702 old_port = conf.port;
706 parse_conf(config_path);
708 if (old_port != conf.port) {
715 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
721 sock4 = make_socket(conf.port, AF_INET);
722 if (sock6 == -1 && conf.ipv6)
723 sock6 = make_socket(conf.port, AF_INET6);
726 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
729 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
730 imsg_flush(&logibuf);