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 proxy *p, *tp;
283 struct envlist *e, *te;
284 struct alist *a, *ta;
285 int v, i;
287 v = conf.verbose;
289 free(conf.chroot);
290 free(conf.user);
291 memset(&conf, 0, sizeof(conf));
293 conf.verbose = v;
295 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
296 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
297 TAILQ_REMOVE(&h->locations, l, locations);
299 free((char*)l->match);
300 free((char*)l->lang);
301 free((char*)l->default_mime);
302 free((char*)l->index);
303 free((char*)l->block_fmt);
304 free((char*)l->dir);
306 if (l->dirfd != -1)
307 close(l->dirfd);
309 free(l);
312 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
313 TAILQ_REMOVE(&h->env, e, envs);
315 free(e->name);
316 free(e->value);
317 free(e);
320 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
321 TAILQ_REMOVE(&h->params, e, envs);
323 free(e->name);
324 free(e->value);
325 free(e);
328 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
329 TAILQ_REMOVE(&h->aliases, a, aliases);
331 free(a->alias);
332 free(a);
335 TAILQ_FOREACH_SAFE(p, &h->proxies, proxies, tp) {
336 TAILQ_REMOVE(&h->proxies, p, proxies);
338 free(p->match_proto);
339 free(p->match_host);
340 free(p->host);
341 tls_unload_file(p->cert, p->certlen);
342 tls_unload_file(p->key, p->keylen);
343 free(p);
346 free((char*)h->domain);
347 free((char*)h->cert);
348 free((char*)h->key);
349 free((char*)h->ocsp);
350 free((char*)h->cgi);
351 free((char*)h->entrypoint);
353 TAILQ_REMOVE(&hosts, h, vhosts);
354 free(h);
357 for (i = 0; i < FCGI_MAX; ++i) {
358 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
359 break;
360 free(fcgi[i].path);
361 free(fcgi[i].port);
362 free(fcgi[i].prog);
364 fcgi[i].path = NULL;
365 fcgi[i].port = NULL;
366 fcgi[i].prog = NULL;
369 tls_free(ctx);
370 tls_config_free(tlsconf);
373 static int
374 wait_signal(void)
376 sigset_t mask;
377 int signo;
379 sigemptyset(&mask);
380 sigaddset(&mask, SIGHUP);
381 sigaddset(&mask, SIGINT);
382 sigaddset(&mask, SIGTERM);
383 sigwait(&mask, &signo);
385 return signo == SIGHUP;
388 void
389 drop_priv(void)
391 struct passwd *pw = NULL;
393 if (conf.chroot != NULL && conf.user == NULL)
394 fatal("can't chroot without an user to switch to after.");
396 if (conf.user != NULL) {
397 if ((pw = getpwnam(conf.user)) == NULL)
398 fatal("can't find user %s", conf.user);
401 if (conf.chroot != NULL) {
402 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
403 fatal("%s: %s", conf.chroot, strerror(errno));
406 if (pw != NULL) {
407 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
408 fatal("setresuid(%d): %s", pw->pw_uid,
409 strerror(errno));
412 if (getuid() == 0)
413 log_warn(NULL, "not a good idea to run a network daemon as root");
416 static void
417 usage(void)
419 fprintf(stderr,
420 "Version: " GMID_STRING "\n"
421 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
422 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
423 getprogname(),
424 getprogname());
427 static void
428 logger_init(void)
430 int p[2];
432 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
433 err(1, "socketpair");
435 switch (fork()) {
436 case -1:
437 err(1, "fork");
438 case 0:
439 signal(SIGHUP, SIG_IGN);
440 close(p[0]);
441 setproctitle("logger");
442 imsg_init(&logibuf, p[1]);
443 drop_priv();
444 _exit(logger_main(p[1], &logibuf));
445 default:
446 close(p[1]);
447 imsg_init(&logibuf, p[0]);
448 return;
452 static int
453 serve(int argc, char **argv, struct imsgbuf *ibuf)
455 char path[PATH_MAX];
456 int i, p[2];
457 struct vhost *h;
458 struct location *l;
460 if (config_path == NULL) {
461 if (hostname == NULL)
462 hostname = "localhost";
463 if (certs_dir == NULL)
464 certs_dir = data_dir();
465 load_local_cert(hostname, certs_dir);
467 h = TAILQ_FIRST(&hosts);
468 h->domain = "*";
470 l = TAILQ_FIRST(&h->locations);
471 l->auto_index = 1;
472 l->match = "*";
474 switch (argc) {
475 case 0:
476 l->dir = getcwd(path, sizeof(path));
477 break;
478 case 1:
479 l->dir = absolutify_path(argv[0]);
480 break;
481 default:
482 usage();
483 return 1;
486 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
489 /* setup tls before dropping privileges: we don't want user
490 * to put private certs inside the chroot. */
491 setup_tls();
493 for (i = 0; i < conf.prefork; ++i) {
494 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
495 PF_UNSPEC, p) == -1)
496 fatal("socketpair: %s", strerror(errno));
498 switch (fork()) {
499 case -1:
500 fatal("fork: %s", strerror(errno));
501 case 0: /* child */
502 close(p[0]);
503 imsg_init(&exibuf, p[1]);
504 setproctitle("server");
505 _exit(listener_main(&exibuf));
506 default:
507 close(p[1]);
508 imsg_init(&servibuf[i], p[0]);
512 setproctitle("executor");
513 drop_priv();
514 _exit(executor_main(ibuf));
517 static int
518 write_pidfile(const char *pidfile)
520 struct flock lock;
521 int fd;
523 if (pidfile == NULL)
524 return -1;
526 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
527 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
529 lock.l_start = 0;
530 lock.l_len = 0;
531 lock.l_type = F_WRLCK;
532 lock.l_whence = SEEK_SET;
534 if (fcntl(fd, F_SETLK, &lock) == -1)
535 fatal("can't lock %s, gmid is already running?", pidfile);
537 if (ftruncate(fd, 0) == -1)
538 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
540 dprintf(fd, "%d\n", getpid());
542 return fd;
545 static void
546 setup_configless(int argc, char **argv, const char *cgi)
548 struct vhost *host;
549 struct location *loc;
551 host = xcalloc(1, sizeof(*host));
552 host->cgi = cgi;
553 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
555 loc = xcalloc(1, sizeof(*loc));
556 loc->fcgi = -1;
557 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
559 serve(argc, argv, NULL);
561 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
562 imsg_flush(&logibuf);
565 static int
566 parse_portno(const char *p)
568 const char *errstr;
569 int n;
571 n = strtonum(p, 0, UINT16_MAX, &errstr);
572 if (errstr != NULL)
573 yyerror("port number is %s: %s", errstr, p);
574 return n;
577 int
578 main(int argc, char **argv)
580 struct imsgbuf exibuf;
581 int ch, conftest = 0, configless = 0;
582 int pidfd, old_ipv6, old_port;
584 logger_init();
585 init_config();
587 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
588 switch (ch) {
589 case '6':
590 conf.ipv6 = 1;
591 configless = 1;
592 break;
594 case 'c':
595 config_path = absolutify_path(optarg);
596 break;
598 case 'D':
599 if (cmdline_symset(optarg) == -1)
600 fatal("could not parse macro definition: %s",
601 optarg);
602 break;
604 case 'd':
605 certs_dir = optarg;
606 configless = 1;
607 break;
609 case 'f':
610 conf.foreground = 1;
611 break;
613 case 'H':
614 hostname = optarg;
615 configless = 1;
616 break;
618 case 'h':
619 usage();
620 return 0;
622 case 'n':
623 conftest++;
624 break;
626 case 'P':
627 pidfile = optarg;
628 break;
630 case 'p':
631 conf.port = parse_portno(optarg);
632 configless = 1;
633 break;
635 case 'V':
636 puts("Version: " GMID_STRING);
637 return 0;
639 case 'v':
640 conf.verbose++;
641 break;
643 case 'x':
644 /* drop the starting / (if any) */
645 if (*optarg == '/')
646 optarg++;
647 cgi = optarg;
648 configless = 1;
649 break;
651 default:
652 usage();
653 return 1;
656 argc -= optind;
657 argv += optind;
659 if (config_path == NULL) {
660 configless = 1;
661 conf.foreground = 1;
662 conf.prefork = 1;
663 conf.verbose++;
666 if (config_path != NULL && (argc > 0 || configless))
667 fatal("can't specify options in config mode.");
669 if (conftest) {
670 if (config_path == NULL)
671 fatal("missing configuration");
672 parse_conf(config_path);
673 fprintf(stderr, "config OK\n");
674 if (conftest > 1)
675 print_conf();
676 return 0;
679 if (!conf.foreground && !configless) {
680 /* log to syslog */
681 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
682 imsg_flush(&logibuf);
684 if (daemon(1, 1) == -1)
685 fatal("daemon: %s", strerror(errno));
688 if (config_path != NULL)
689 parse_conf(config_path);
691 sock4 = make_socket(conf.port, AF_INET);
692 sock6 = -1;
693 if (conf.ipv6)
694 sock6 = make_socket(conf.port, AF_INET6);
696 signal(SIGPIPE, SIG_IGN);
697 signal(SIGCHLD, SIG_IGN);
699 if (configless) {
700 setup_configless(argc, argv, cgi);
701 return 0;
704 pidfd = write_pidfile(pidfile);
706 /*
707 * Linux seems to call the event handlers even when we're
708 * doing a sigwait. These dummy handlers are here to avoid
709 * being terminated on SIGHUP, SIGINT or SIGTERM.
710 */
711 signal(SIGHUP, dummy_handler);
712 signal(SIGINT, dummy_handler);
713 signal(SIGTERM, dummy_handler);
715 /* wait a sighup and reload the daemon */
716 for (;;) {
717 int p[2];
719 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
720 PF_UNSPEC, p) == -1)
721 fatal("socketpair: %s", strerror(errno));
723 switch (fork()) {
724 case -1:
725 fatal("fork: %s", strerror(errno));
726 case 0:
727 close(p[0]);
728 imsg_init(&exibuf, p[1]);
729 _exit(serve(argc, argv, &exibuf));
732 close(p[1]);
733 imsg_init(&exibuf, p[0]);
735 if (!wait_signal())
736 break;
738 log_info(NULL, "reloading configuration %s", config_path);
740 /* close the executor (it'll close the servers too) */
741 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
742 imsg_flush(&exibuf);
743 close(p[0]);
745 old_ipv6 = conf.ipv6;
746 old_port = conf.port;
748 free_config();
749 init_config();
750 parse_conf(config_path);
752 if (old_port != conf.port) {
753 close(sock4);
754 close(sock6);
755 sock4 = -1;
756 sock6 = -1;
759 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
760 close(sock6);
761 sock6 = -1;
764 if (sock4 == -1)
765 sock4 = make_socket(conf.port, AF_INET);
766 if (sock6 == -1 && conf.ipv6)
767 sock6 = make_socket(conf.port, AF_INET6);
770 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
771 imsg_flush(&exibuf);
773 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
774 imsg_flush(&logibuf);
776 if (pidfd != -1)
777 close(pidfd);
779 return 0;