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.
30 static const char *opts = "6c:D:d:fH:hnP:p:Vvx:";
32 static const 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: %s", l->dir, h->domain,
143 make_socket(int port, int family)
146 struct sockaddr_in addr4;
147 struct sockaddr_in6 addr6;
148 struct sockaddr *addr;
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;
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;
175 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
176 fatal("socket: %s", strerror(errno));
179 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
180 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
183 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
184 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
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));
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)",
205 if (tls_config_add_keypair_ocsp_file(tlsconf, h->cert, h->key,
207 fatal("failed to load the keypair (%s, %s, %s)",
208 h->cert, h->key, h->ocsp);
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)",
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)",
243 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
246 if (tls_configure(ctx, tlsconf) == -1)
247 fatal("tls_configure: %s", tls_error(ctx));
251 listener_main(struct imsgbuf *ibuf)
254 if (!conf.mime.skip_defaults && load_default_mime(&conf.mime) == -1)
255 fatal("load_default_mime: %s", strerror(errno));
256 sort_mime(&conf.mime);
258 loop(ctx, sock4, sock6, ibuf);
269 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
271 init_mime(&conf.mime);
282 struct vhost *h, *th;
283 struct location *l, *tl;
284 struct proxy *p, *tp;
285 struct envlist *e, *te;
286 struct alist *a, *ta;
291 free_mime(&conf.mime);
294 memset(&conf, 0, sizeof(conf));
298 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
299 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
300 TAILQ_REMOVE(&h->locations, l, locations);
302 free((char*)l->match);
303 free((char*)l->lang);
304 free((char*)l->default_mime);
305 free((char*)l->index);
306 free((char*)l->block_fmt);
315 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
316 TAILQ_REMOVE(&h->env, e, envs);
323 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
324 TAILQ_REMOVE(&h->params, e, envs);
331 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
332 TAILQ_REMOVE(&h->aliases, a, aliases);
338 TAILQ_FOREACH_SAFE(p, &h->proxies, proxies, tp) {
339 TAILQ_REMOVE(&h->proxies, p, proxies);
341 free(p->match_proto);
345 tls_unload_file(p->cert, p->certlen);
346 tls_unload_file(p->key, p->keylen);
350 free((char*)h->domain);
351 free((char*)h->cert);
353 free((char*)h->ocsp);
355 free((char*)h->entrypoint);
357 TAILQ_REMOVE(&hosts, h, vhosts);
361 for (i = 0; i < FCGI_MAX; ++i) {
362 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
374 tls_config_free(tlsconf);
384 sigaddset(&mask, SIGHUP);
385 sigaddset(&mask, SIGINT);
386 sigaddset(&mask, SIGTERM);
387 sigwait(&mask, &signo);
389 return signo == SIGHUP;
395 struct passwd *pw = NULL;
397 if (conf.chroot != NULL && conf.user == NULL)
398 fatal("can't chroot without an user to switch to after.");
400 if (conf.user != NULL) {
401 if ((pw = getpwnam(conf.user)) == NULL)
402 fatal("can't find user %s", conf.user);
405 if (conf.chroot != NULL) {
406 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
407 fatal("%s: %s", conf.chroot, strerror(errno));
411 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
412 fatal("setresuid(%d): %s", pw->pw_uid,
417 log_warn(NULL, "not a good idea to run a network daemon as root");
424 "Version: " GMID_STRING "\n"
425 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
426 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
436 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
437 err(1, "socketpair");
443 signal(SIGHUP, SIG_IGN);
445 setproctitle("logger");
446 imsg_init(&logibuf, p[1]);
448 _exit(logger_main(p[1], &logibuf));
451 imsg_init(&logibuf, p[0]);
457 serve(int argc, char **argv, struct imsgbuf *ibuf)
464 if (config_path == NULL) {
465 if (hostname == NULL)
466 hostname = "localhost";
467 if (certs_dir == NULL)
468 certs_dir = data_dir();
469 load_local_cert(hostname, certs_dir);
471 h = TAILQ_FIRST(&hosts);
474 l = TAILQ_FIRST(&h->locations);
480 l->dir = getcwd(path, sizeof(path));
483 l->dir = absolutify_path(argv[0]);
490 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
493 /* setup tls before dropping privileges: we don't want user
494 * to put private certs inside the chroot. */
497 for (i = 0; i < conf.prefork; ++i) {
498 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
500 fatal("socketpair: %s", strerror(errno));
504 fatal("fork: %s", strerror(errno));
507 imsg_init(&exibuf, p[1]);
508 setproctitle("server");
509 _exit(listener_main(&exibuf));
512 imsg_init(&servibuf[i], p[0]);
516 setproctitle("executor");
518 _exit(executor_main(ibuf));
522 write_pidfile(const char *pidfile)
530 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
531 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
535 lock.l_type = F_WRLCK;
536 lock.l_whence = SEEK_SET;
538 if (fcntl(fd, F_SETLK, &lock) == -1)
539 fatal("can't lock %s, gmid is already running?", pidfile);
541 if (ftruncate(fd, 0) == -1)
542 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
544 dprintf(fd, "%d\n", getpid());
550 setup_configless(int argc, char **argv, const char *cgi)
553 struct location *loc;
555 host = xcalloc(1, sizeof(*host));
557 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
559 loc = xcalloc(1, sizeof(*loc));
561 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
563 serve(argc, argv, NULL);
565 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
566 imsg_flush(&logibuf);
570 parse_portno(const char *p)
575 n = strtonum(p, 0, UINT16_MAX, &errstr);
577 yyerror("port number is %s: %s", errstr, p);
582 main(int argc, char **argv)
584 struct imsgbuf exibuf;
585 int ch, conftest = 0, configless = 0;
586 int pidfd, old_ipv6, old_port;
591 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
599 config_path = absolutify_path(optarg);
603 if (cmdline_symset(optarg) == -1)
604 fatal("could not parse macro definition: %s",
635 conf.port = parse_portno(optarg);
640 puts("Version: " GMID_STRING);
648 /* drop the starting / (if any) */
663 if (config_path == NULL) {
670 if (config_path != NULL && (argc > 0 || configless))
671 fatal("can't specify options in config mode.");
674 if (config_path == NULL)
675 fatal("missing configuration");
676 parse_conf(config_path);
677 fprintf(stderr, "config OK\n");
683 if (!conf.foreground && !configless) {
685 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
686 imsg_flush(&logibuf);
688 if (daemon(1, 1) == -1)
689 fatal("daemon: %s", strerror(errno));
692 if (config_path != NULL)
693 parse_conf(config_path);
695 sock4 = make_socket(conf.port, AF_INET);
698 sock6 = make_socket(conf.port, AF_INET6);
700 signal(SIGPIPE, SIG_IGN);
701 signal(SIGCHLD, SIG_IGN);
704 setup_configless(argc, argv, cgi);
708 pidfd = write_pidfile(pidfile);
711 * Linux seems to call the event handlers even when we're
712 * doing a sigwait. These dummy handlers are here to avoid
713 * being terminated on SIGHUP, SIGINT or SIGTERM.
715 signal(SIGHUP, dummy_handler);
716 signal(SIGINT, dummy_handler);
717 signal(SIGTERM, dummy_handler);
719 /* wait a sighup and reload the daemon */
723 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
725 fatal("socketpair: %s", strerror(errno));
729 fatal("fork: %s", strerror(errno));
732 imsg_init(&exibuf, p[1]);
733 _exit(serve(argc, argv, &exibuf));
737 imsg_init(&exibuf, p[0]);
742 log_info(NULL, "reloading configuration %s", config_path);
744 /* close the executor (it'll close the servers too) */
745 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
749 old_ipv6 = conf.ipv6;
750 old_port = conf.port;
754 parse_conf(config_path);
756 if (old_port != conf.port) {
763 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
769 sock4 = make_socket(conf.port, AF_INET);
770 if (sock6 == -1 && conf.ipv6)
771 sock6 = make_socket(conf.port, AF_INET6);
774 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
777 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
778 imsg_flush(&logibuf);