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, h->ocsp) == -1)
206 fatal("failed to load the keypair (%s, %s, %s)",
207 h->cert, h->key, h->ocsp);
211 void
212 setup_tls(void)
214 struct vhost *h;
216 if ((tlsconf = tls_config_new()) == NULL)
217 fatal("tls_config_new");
219 /* optionally accept client certs, but don't try to verify them */
220 tls_config_verify_client_optional(tlsconf);
221 tls_config_insecure_noverifycert(tlsconf);
223 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
224 fatal("tls_config_set_protocols");
226 if ((ctx = tls_server()) == NULL)
227 fatal("tls_server failure");
229 h = TAILQ_FIRST(&hosts);
231 /* we need to set something, then we can add how many key we want */
232 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
233 fatal("tls_config_set_keypair_file failed for (%s, %s)",
234 h->cert, h->key);
235 if (h->ocsp != NULL &&
236 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
237 fatal("tls_config_set_ocsp_staple_file failed for (%s)",
238 h->ocsp);
240 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
241 add_keypair(h);
243 if (tls_configure(ctx, tlsconf) == -1)
244 fatal("tls_configure: %s", tls_error(ctx));
247 static int
248 listener_main(struct imsgbuf *ibuf)
250 drop_priv();
251 load_default_mime(&conf.mime);
252 load_vhosts();
253 loop(ctx, sock4, sock6, ibuf);
254 return 0;
257 void
258 init_config(void)
260 TAILQ_INIT(&hosts);
262 conf.port = 1965;
263 conf.ipv6 = 0;
264 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
266 init_mime(&conf.mime);
268 conf.chroot = NULL;
269 conf.user = NULL;
271 conf.prefork = 3;
274 void
275 free_config(void)
277 struct vhost *h, *th;
278 struct location *l, *tl;
279 struct envlist *e, *te;
280 struct alist *a, *ta;
281 int v, i;
283 v = conf.verbose;
285 free(conf.chroot);
286 free(conf.user);
287 memset(&conf, 0, sizeof(conf));
289 conf.verbose = v;
291 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
292 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
293 TAILQ_REMOVE(&h->locations, l, locations);
295 free((char*)l->match);
296 free((char*)l->lang);
297 free((char*)l->default_mime);
298 free((char*)l->index);
299 free((char*)l->block_fmt);
300 free((char*)l->dir);
302 if (l->dirfd != -1)
303 close(l->dirfd);
305 free(l);
308 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
309 TAILQ_REMOVE(&h->env, e, envs);
311 free(e->name);
312 free(e->value);
313 free(e);
316 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
317 TAILQ_REMOVE(&h->params, e, envs);
319 free(e->name);
320 free(e->value);
321 free(e);
324 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
325 TAILQ_REMOVE(&h->aliases, a, aliases);
327 free(a->alias);
328 free(a);
331 free((char*)h->domain);
332 free((char*)h->cert);
333 free((char*)h->key);
334 free((char*)h->cgi);
335 free((char*)h->entrypoint);
337 TAILQ_REMOVE(&hosts, h, vhosts);
338 free(h);
341 for (i = 0; i < FCGI_MAX; ++i) {
342 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
343 break;
344 free(fcgi[i].path);
345 free(fcgi[i].port);
346 free(fcgi[i].prog);
348 fcgi[i].path = NULL;
349 fcgi[i].port = NULL;
350 fcgi[i].prog = NULL;
353 tls_free(ctx);
354 tls_config_free(tlsconf);
357 static int
358 wait_signal(void)
360 sigset_t mask;
361 int signo;
363 sigemptyset(&mask);
364 sigaddset(&mask, SIGHUP);
365 sigaddset(&mask, SIGINT);
366 sigaddset(&mask, SIGTERM);
367 sigwait(&mask, &signo);
369 return signo == SIGHUP;
372 void
373 drop_priv(void)
375 struct passwd *pw = NULL;
377 if (conf.chroot != NULL && conf.user == NULL)
378 fatal("can't chroot without an user to switch to after.");
380 if (conf.user != NULL) {
381 if ((pw = getpwnam(conf.user)) == NULL)
382 fatal("can't find user %s", conf.user);
385 if (conf.chroot != NULL) {
386 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
387 fatal("%s: %s", conf.chroot, strerror(errno));
390 if (pw != NULL) {
391 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
392 fatal("setresuid(%d): %s", pw->pw_uid,
393 strerror(errno));
396 if (getuid() == 0)
397 log_warn(NULL, "not a good idea to run a network daemon as root");
400 static void
401 usage(void)
403 fprintf(stderr,
404 "Version: " GMID_STRING "\n"
405 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
406 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
407 getprogname(),
408 getprogname());
411 static void
412 logger_init(void)
414 int p[2];
416 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
417 err(1, "socketpair");
419 switch (fork()) {
420 case -1:
421 err(1, "fork");
422 case 0:
423 signal(SIGHUP, SIG_IGN);
424 close(p[0]);
425 setproctitle("logger");
426 imsg_init(&logibuf, p[1]);
427 drop_priv();
428 _exit(logger_main(p[1], &logibuf));
429 default:
430 close(p[1]);
431 imsg_init(&logibuf, p[0]);
432 return;
436 static int
437 serve(int argc, char **argv, struct imsgbuf *ibuf)
439 char path[PATH_MAX];
440 int i, p[2];
441 struct vhost *h;
442 struct location *l;
444 if (config_path == NULL) {
445 if (hostname == NULL)
446 hostname = "localhost";
447 if (certs_dir == NULL)
448 certs_dir = data_dir();
449 load_local_cert(hostname, certs_dir);
451 h = TAILQ_FIRST(&hosts);
452 h->domain = "*";
454 l = TAILQ_FIRST(&h->locations);
455 l->auto_index = 1;
456 l->match = "*";
458 switch (argc) {
459 case 0:
460 l->dir = getcwd(path, sizeof(path));
461 break;
462 case 1:
463 l->dir = absolutify_path(argv[0]);
464 break;
465 default:
466 usage();
467 return 1;
470 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
473 /* setup tls before dropping privileges: we don't want user
474 * to put private certs inside the chroot. */
475 setup_tls();
477 for (i = 0; i < conf.prefork; ++i) {
478 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
479 PF_UNSPEC, p) == -1)
480 fatal("socketpair: %s", strerror(errno));
482 switch (fork()) {
483 case -1:
484 fatal("fork: %s", strerror(errno));
485 case 0: /* child */
486 close(p[0]);
487 imsg_init(&exibuf, p[1]);
488 setproctitle("server");
489 _exit(listener_main(&exibuf));
490 default:
491 close(p[1]);
492 imsg_init(&servibuf[i], p[0]);
496 setproctitle("executor");
497 drop_priv();
498 _exit(executor_main(ibuf));
501 static int
502 write_pidfile(const char *pidfile)
504 struct flock lock;
505 int fd;
507 if (pidfile == NULL)
508 return -1;
510 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
511 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
513 lock.l_start = 0;
514 lock.l_len = 0;
515 lock.l_type = F_WRLCK;
516 lock.l_whence = SEEK_SET;
518 if (fcntl(fd, F_SETLK, &lock) == -1)
519 fatal("can't lock %s, gmid is already running?", pidfile);
521 if (ftruncate(fd, 0) == -1)
522 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
524 dprintf(fd, "%d\n", getpid());
526 return fd;
529 static void
530 setup_configless(int argc, char **argv, const char *cgi)
532 struct vhost *host;
533 struct location *loc;
535 host = xcalloc(1, sizeof(*host));
536 host->cgi = cgi;
537 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
539 loc = xcalloc(1, sizeof(*loc));
540 loc->fcgi = -1;
541 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
543 serve(argc, argv, NULL);
545 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
546 imsg_flush(&logibuf);
549 static int
550 parse_portno(const char *p)
552 const char *errstr;
553 int n;
555 n = strtonum(p, 0, UINT16_MAX, &errstr);
556 if (errstr != NULL)
557 yyerror("port number is %s: %s", errstr, p);
558 return n;
561 int
562 main(int argc, char **argv)
564 struct imsgbuf exibuf;
565 int ch, conftest = 0, configless = 0;
566 int pidfd, old_ipv6, old_port;
568 logger_init();
569 init_config();
571 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
572 switch (ch) {
573 case '6':
574 conf.ipv6 = 1;
575 configless = 1;
576 break;
578 case 'c':
579 config_path = absolutify_path(optarg);
580 break;
582 case 'D':
583 if (cmdline_symset(optarg) == -1)
584 fatal("could not parse macro definition: %s",
585 optarg);
586 break;
588 case 'd':
589 certs_dir = optarg;
590 configless = 1;
591 break;
593 case 'f':
594 conf.foreground = 1;
595 break;
597 case 'H':
598 hostname = optarg;
599 configless = 1;
600 break;
602 case 'h':
603 usage();
604 return 0;
606 case 'n':
607 conftest++;
608 break;
610 case 'P':
611 pidfile = optarg;
612 break;
614 case 'p':
615 conf.port = parse_portno(optarg);
616 configless = 1;
617 break;
619 case 'V':
620 puts("Version: " GMID_STRING);
621 return 0;
623 case 'v':
624 conf.verbose++;
625 break;
627 case 'x':
628 /* drop the starting / (if any) */
629 if (*optarg == '/')
630 optarg++;
631 cgi = optarg;
632 configless = 1;
633 break;
635 default:
636 usage();
637 return 1;
640 argc -= optind;
641 argv += optind;
643 if (config_path == NULL) {
644 configless = 1;
645 conf.foreground = 1;
646 conf.prefork = 1;
647 conf.verbose++;
650 if (config_path != NULL && (argc > 0 || configless))
651 fatal("can't specify options in config mode.");
653 if (conftest) {
654 if (config_path == NULL)
655 fatal("missing configuration");
656 parse_conf(config_path);
657 fprintf(stderr, "config OK\n");
658 if (conftest > 1)
659 print_conf();
660 return 0;
663 if (!conf.foreground && !configless) {
664 /* log to syslog */
665 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
666 imsg_flush(&logibuf);
668 if (daemon(1, 1) == -1)
669 fatal("daemon: %s", strerror(errno));
672 if (config_path != NULL)
673 parse_conf(config_path);
675 sock4 = make_socket(conf.port, AF_INET);
676 sock6 = -1;
677 if (conf.ipv6)
678 sock6 = make_socket(conf.port, AF_INET6);
680 signal(SIGPIPE, SIG_IGN);
681 signal(SIGCHLD, SIG_IGN);
683 if (configless) {
684 setup_configless(argc, argv, cgi);
685 return 0;
688 pidfd = write_pidfile(pidfile);
690 /*
691 * Linux seems to call the event handlers even when we're
692 * doing a sigwait. These dummy handlers are here to avoid
693 * being terminated on SIGHUP, SIGINT or SIGTERM.
694 */
695 signal(SIGHUP, dummy_handler);
696 signal(SIGINT, dummy_handler);
697 signal(SIGTERM, dummy_handler);
699 /* wait a sighup and reload the daemon */
700 for (;;) {
701 int p[2];
703 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
704 PF_UNSPEC, p) == -1)
705 fatal("socketpair: %s", strerror(errno));
707 switch (fork()) {
708 case -1:
709 fatal("fork: %s", strerror(errno));
710 case 0:
711 close(p[0]);
712 imsg_init(&exibuf, p[1]);
713 _exit(serve(argc, argv, &exibuf));
716 close(p[1]);
717 imsg_init(&exibuf, p[0]);
719 if (!wait_signal())
720 break;
722 log_info(NULL, "reloading configuration %s", config_path);
724 /* close the executor (it'll close the servers too) */
725 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
726 imsg_flush(&exibuf);
727 close(p[0]);
729 old_ipv6 = conf.ipv6;
730 old_port = conf.port;
732 free_config();
733 init_config();
734 parse_conf(config_path);
736 if (old_port != conf.port) {
737 close(sock4);
738 close(sock6);
739 sock4 = -1;
740 sock6 = -1;
743 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
744 close(sock6);
745 sock6 = -1;
748 if (sock4 == -1)
749 sock4 = make_socket(conf.port, AF_INET);
750 if (sock6 == -1 && conf.ipv6)
751 sock6 = make_socket(conf.port, AF_INET6);
754 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
755 imsg_flush(&exibuf);
757 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
758 imsg_flush(&logibuf);
760 if (pidfd != -1)
761 close(pidfd);
763 return 0;