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;
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(struct vhost *h, const char *hostname, const char *dir)
110 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
112 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
115 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
116 gen_certificate(hostname, cert, key);
120 h->domain = hostname;
129 TAILQ_FOREACH(h, &hosts, vhosts) {
130 TAILQ_FOREACH(l, &h->locations, locations) {
133 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
134 fatal("open %s for domain %s: %s", l->dir, h->domain,
141 make_socket(int port, int family)
144 struct sockaddr_in addr4;
145 struct sockaddr_in6 addr6;
146 struct sockaddr *addr;
151 memset(&addr4, 0, sizeof(addr4));
152 addr4.sin_family = family;
153 addr4.sin_port = htons(port);
154 addr4.sin_addr.s_addr = INADDR_ANY;
155 addr = (struct sockaddr*)&addr4;
160 memset(&addr6, 0, sizeof(addr6));
161 addr6.sin6_family = AF_INET6;
162 addr6.sin6_port = htons(port);
163 addr6.sin6_addr = in6addr_any;
164 addr = (struct sockaddr*)&addr6;
173 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
174 fatal("socket: %s", strerror(errno));
177 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
178 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
181 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
182 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
186 if (bind(sock, addr, len) == -1)
187 fatal("bind: %s", strerror(errno));
189 if (listen(sock, 16) == -1)
190 fatal("listen: %s", strerror(errno));
196 add_keypair(struct vhost *h)
198 if (h->ocsp == NULL) {
199 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
200 fatal("failed to load the keypair (%s, %s)",
203 if (tls_config_add_keypair_ocsp_file(tlsconf, h->cert, h->key,
205 fatal("failed to load the keypair (%s, %s, %s)",
206 h->cert, h->key, h->ocsp);
215 if ((tlsconf = tls_config_new()) == NULL)
216 fatal("tls_config_new");
218 /* optionally accept client certs, but don't try to verify them */
219 tls_config_verify_client_optional(tlsconf);
220 tls_config_insecure_noverifycert(tlsconf);
222 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
223 fatal("tls_config_set_protocols");
225 if ((ctx = tls_server()) == NULL)
226 fatal("tls_server failure");
228 h = TAILQ_FIRST(&hosts);
230 /* we need to set something, then we can add how many key we want */
231 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
232 fatal("tls_config_set_keypair_file failed for (%s, %s)",
236 if (h->ocsp != NULL &&
237 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
238 fatal("tls_config_set_ocsp_staple_file failed for (%s)",
241 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
244 if (tls_configure(ctx, tlsconf) == -1)
245 fatal("tls_configure: %s", tls_error(ctx));
249 listener_main(struct imsgbuf *ibuf)
252 if (!conf.mime.skip_defaults && load_default_mime(&conf.mime) == -1)
253 fatal("load_default_mime: %s", strerror(errno));
254 sort_mime(&conf.mime);
256 loop(ctx, sock4, sock6, ibuf);
267 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
269 init_mime(&conf.mime);
280 struct vhost *h, *th;
281 struct location *l, *tl;
282 struct proxy *p, *tp;
283 struct envlist *e, *te;
284 struct alist *a, *ta;
289 free_mime(&conf.mime);
292 memset(&conf, 0, sizeof(conf));
296 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
297 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
298 TAILQ_REMOVE(&h->locations, l, locations);
300 free((char*)l->match);
301 free((char*)l->lang);
302 free((char*)l->default_mime);
303 free((char*)l->index);
304 free((char*)l->block_fmt);
313 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
314 TAILQ_REMOVE(&h->env, e, envs);
321 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
322 TAILQ_REMOVE(&h->params, e, envs);
329 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
330 TAILQ_REMOVE(&h->aliases, a, aliases);
336 TAILQ_FOREACH_SAFE(p, &h->proxies, proxies, tp) {
337 TAILQ_REMOVE(&h->proxies, p, proxies);
339 free(p->match_proto);
343 tls_unload_file(p->cert, p->certlen);
344 tls_unload_file(p->key, p->keylen);
348 free((char*)h->domain);
349 free((char*)h->cert);
351 free((char*)h->ocsp);
352 free((char*)h->entrypoint);
354 TAILQ_REMOVE(&hosts, h, vhosts);
358 for (i = 0; i < FCGI_MAX; ++i) {
359 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
371 tls_config_free(tlsconf);
381 sigaddset(&mask, SIGHUP);
382 sigaddset(&mask, SIGINT);
383 sigaddset(&mask, SIGTERM);
384 sigwait(&mask, &signo);
386 return signo == SIGHUP;
392 struct passwd *pw = NULL;
394 if (conf.chroot != NULL && conf.user == NULL)
395 fatal("can't chroot without an user to switch to after.");
397 if (conf.user != NULL) {
398 if ((pw = getpwnam(conf.user)) == NULL)
399 fatal("can't find user %s", conf.user);
402 if (conf.chroot != NULL) {
403 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
404 fatal("%s: %s", conf.chroot, strerror(errno));
408 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
409 fatal("setresuid(%d): %s", pw->pw_uid,
414 log_warn(NULL, "not a good idea to run a network daemon as root");
421 "Version: " GMID_STRING "\n"
422 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
423 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [dir]\n",
433 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
434 err(1, "socketpair");
440 signal(SIGHUP, SIG_IGN);
442 setproctitle("logger");
443 imsg_init(&logibuf, p[1]);
445 _exit(logger_main(p[1], &logibuf));
448 imsg_init(&logibuf, p[0]);
458 /* setup tls before dropping privileges: we don't want user
459 * to put private certs inside the chroot. */
462 for (i = 0; i < conf.prefork; ++i) {
463 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
465 fatal("socketpair: %s", strerror(errno));
469 fatal("fork: %s", strerror(errno));
472 imsg_init(&exibuf, p[1]);
473 setproctitle("server");
474 _exit(listener_main(&exibuf));
477 imsg_init(&servibuf[i], p[0]);
483 write_pidfile(const char *pidfile)
491 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
492 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
496 lock.l_type = F_WRLCK;
497 lock.l_whence = SEEK_SET;
499 if (fcntl(fd, F_SETLK, &lock) == -1)
500 fatal("can't lock %s, gmid is already running?", pidfile);
502 if (ftruncate(fd, 0) == -1)
503 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
505 dprintf(fd, "%d\n", getpid());
511 setup_configless(const char *path)
515 struct location *loc;
517 if (hostname == NULL)
518 hostname = "localhost";
519 if (certs_dir == NULL)
520 certs_dir = data_dir();
522 host = xcalloc(1, sizeof(*host));
523 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
525 loc = xcalloc(1, sizeof(*loc));
527 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
529 load_local_cert(host, hostname, certs_dir);
535 loc->dir = getcwd(p, sizeof(p));
537 loc->dir = absolutify_path(path);
539 log_notice(NULL, "serving %s on port %d", loc->dir, conf.port);
543 parse_portno(const char *p)
548 n = strtonum(p, 0, UINT16_MAX, &errstr);
550 yyerror("port number is %s: %s", errstr, p);
555 main(int argc, char **argv)
557 int i, ch, conftest = 0, configless = 0;
558 int pidfd, old_ipv6, old_port;
563 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
571 config_path = absolutify_path(optarg);
575 if (cmdline_symset(optarg) == -1)
576 fatal("could not parse macro definition: %s",
607 conf.port = parse_portno(optarg);
612 puts("Version: " GMID_STRING);
627 if (config_path == NULL) {
634 if (argc > 1 || (configless && argc != 0))
637 if (config_path != NULL && (argc > 0 || configless))
638 fatal("can't specify options in config mode.");
641 if (config_path == NULL)
642 fatal("missing configuration");
643 parse_conf(config_path);
644 fprintf(stderr, "config OK\n");
650 if (!conf.foreground && !configless) {
652 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
653 imsg_flush(&logibuf);
655 if (daemon(1, 1) == -1)
656 fatal("daemon: %s", strerror(errno));
659 if (config_path != NULL)
660 parse_conf(config_path);
662 setup_configless(*argv);
664 sock4 = make_socket(conf.port, AF_INET);
667 sock6 = make_socket(conf.port, AF_INET6);
669 signal(SIGPIPE, SIG_IGN);
671 pidfd = write_pidfile(pidfile);
674 * Linux seems to call the event handlers even when we're
675 * doing a sigwait. These dummy handlers are here to avoid
676 * being terminated on SIGHUP, SIGINT or SIGTERM.
678 signal(SIGHUP, dummy_handler);
679 signal(SIGINT, dummy_handler);
680 signal(SIGTERM, dummy_handler);
682 /* wait a sighup and reload the daemon */
686 if (!wait_signal() || configless)
689 log_info(NULL, "reloading configuration %s", config_path);
691 /* close the servers */
692 for (i = 0; i < conf.prefork; ++i) {
693 imsg_compose(&servibuf[i], IMSG_QUIT, 0, 0, -1, NULL, 0);
694 imsg_flush(&servibuf[i]);
695 close(servibuf[i].fd);
698 old_ipv6 = conf.ipv6;
699 old_port = conf.port;
703 parse_conf(config_path);
705 if (old_port != conf.port) {
712 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
718 sock4 = make_socket(conf.port, AF_INET);
719 if (sock6 == -1 && conf.ipv6)
720 sock6 = make_socket(conf.port, AF_INET6);
723 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
726 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
727 imsg_flush(&logibuf);