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", l->dir, h->domain);
141 int
142 make_socket(int port, int family)
144 int sock, v;
145 struct sockaddr_in addr4;
146 struct sockaddr_in6 addr6;
147 struct sockaddr *addr;
148 socklen_t len;
150 switch (family) {
151 case AF_INET:
152 memset(&addr4, 0, 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;
157 len = sizeof(addr4);
158 break;
160 case AF_INET6:
161 memset(&addr6, 0, 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;
166 len = sizeof(addr6);
167 break;
169 default:
170 /* unreachable */
171 abort();
174 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
175 fatal("socket: %s", strerror(errno));
177 v = 1;
178 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
179 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
181 v = 1;
182 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
183 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
185 mark_nonblock(sock);
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));
193 return sock;
196 void
197 setup_tls(void)
199 struct vhost *h;
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)",
219 h->cert, h->key);
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)",
224 h->cert, h->key);
227 if (tls_configure(ctx, tlsconf) == -1)
228 fatal("tls_configure: %s", tls_error(ctx));
231 static int
232 listener_main(struct imsgbuf *ibuf)
234 drop_priv();
235 load_default_mime(&conf.mime);
236 load_vhosts();
237 loop(ctx, sock4, sock6, ibuf);
238 return 0;
241 void
242 init_config(void)
244 TAILQ_INIT(&hosts);
246 conf.port = 1965;
247 conf.ipv6 = 0;
248 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
250 init_mime(&conf.mime);
252 conf.chroot = NULL;
253 conf.user = NULL;
255 conf.prefork = 3;
258 void
259 free_config(void)
261 struct vhost *h, *th;
262 struct location *l, *tl;
263 struct envlist *e, *te;
264 struct alist *a, *ta;
265 int v, i;
267 v = conf.verbose;
269 free(conf.chroot);
270 free(conf.user);
271 memset(&conf, 0, sizeof(conf));
273 conf.verbose = v;
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);
284 free((char*)l->dir);
286 if (l->dirfd != -1)
287 close(l->dirfd);
289 free(l);
292 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
293 TAILQ_REMOVE(&h->env, e, envs);
295 free(e->name);
296 free(e->value);
297 free(e);
300 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
301 TAILQ_REMOVE(&h->params, e, envs);
303 free(e->name);
304 free(e->value);
305 free(e);
308 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
309 TAILQ_REMOVE(&h->aliases, a, aliases);
311 free(a->alias);
312 free(a);
315 free((char*)h->domain);
316 free((char*)h->cert);
317 free((char*)h->key);
318 free((char*)h->cgi);
319 free((char*)h->entrypoint);
321 TAILQ_REMOVE(&hosts, h, vhosts);
322 free(h);
325 for (i = 0; i < FCGI_MAX; ++i) {
326 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
327 break;
328 free(fcgi[i].path);
329 free(fcgi[i].port);
330 free(fcgi[i].prog);
332 fcgi[i].path = NULL;
333 fcgi[i].port = NULL;
334 fcgi[i].prog = NULL;
337 tls_free(ctx);
338 tls_config_free(tlsconf);
341 static int
342 wait_signal(void)
344 sigset_t mask;
345 int signo;
347 sigemptyset(&mask);
348 sigaddset(&mask, SIGHUP);
349 sigaddset(&mask, SIGINT);
350 sigaddset(&mask, SIGTERM);
351 sigwait(&mask, &signo);
353 return signo == SIGHUP;
356 void
357 drop_priv(void)
359 struct passwd *pw = NULL;
361 if (conf.chroot != NULL && conf.user == NULL)
362 fatal("can't chroot without an user to switch to after.");
364 if (conf.user != NULL) {
365 if ((pw = getpwnam(conf.user)) == NULL)
366 fatal("can't find user %s", conf.user);
369 if (conf.chroot != NULL) {
370 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
371 fatal("%s: %s", conf.chroot, strerror(errno));
374 if (pw != NULL) {
375 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
376 fatal("setresuid(%d): %s", pw->pw_uid,
377 strerror(errno));
380 if (getuid() == 0)
381 log_warn(NULL, "not a good idea to run a network daemon as root");
384 static void
385 usage(void)
387 fprintf(stderr,
388 "Version: " GMID_STRING "\n"
389 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
390 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
391 getprogname(),
392 getprogname());
395 static void
396 logger_init(void)
398 int p[2];
400 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
401 err(1, "socketpair");
403 switch (fork()) {
404 case -1:
405 err(1, "fork");
406 case 0:
407 signal(SIGHUP, SIG_IGN);
408 close(p[0]);
409 setproctitle("logger");
410 imsg_init(&logibuf, p[1]);
411 drop_priv();
412 _exit(logger_main(p[1], &logibuf));
413 default:
414 close(p[1]);
415 imsg_init(&logibuf, p[0]);
416 return;
420 static int
421 serve(int argc, char **argv, struct imsgbuf *ibuf)
423 char path[PATH_MAX];
424 int i, p[2];
425 struct vhost *h;
426 struct location *l;
428 if (config_path == NULL) {
429 if (hostname == NULL)
430 hostname = "localhost";
431 if (certs_dir == NULL)
432 certs_dir = data_dir();
433 load_local_cert(hostname, certs_dir);
435 h = TAILQ_FIRST(&hosts);
436 h->domain = "*";
438 l = TAILQ_FIRST(&h->locations);
439 l->auto_index = 1;
440 l->match = "*";
442 switch (argc) {
443 case 0:
444 l->dir = getcwd(path, sizeof(path));
445 break;
446 case 1:
447 l->dir = absolutify_path(argv[0]);
448 break;
449 default:
450 usage();
451 return 1;
454 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
457 /* setup tls before dropping privileges: we don't want user
458 * to put private certs inside the chroot. */
459 setup_tls();
461 for (i = 0; i < conf.prefork; ++i) {
462 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
463 PF_UNSPEC, p) == -1)
464 fatal("socketpair: %s", strerror(errno));
466 switch (fork()) {
467 case -1:
468 fatal("fork: %s", strerror(errno));
469 case 0: /* child */
470 close(p[0]);
471 imsg_init(&exibuf, p[1]);
472 setproctitle("server");
473 _exit(listener_main(&exibuf));
474 default:
475 close(p[1]);
476 imsg_init(&servibuf[i], p[0]);
480 setproctitle("executor");
481 drop_priv();
482 _exit(executor_main(ibuf));
485 static int
486 write_pidfile(const char *pidfile)
488 struct flock lock;
489 int fd;
491 if (pidfile == NULL)
492 return -1;
494 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
495 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
497 lock.l_start = 0;
498 lock.l_len = 0;
499 lock.l_type = F_WRLCK;
500 lock.l_whence = SEEK_SET;
502 if (fcntl(fd, F_SETLK, &lock) == -1)
503 fatal("can't lock %s, gmid is already running?", pidfile);
505 if (ftruncate(fd, 0) == -1)
506 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
508 dprintf(fd, "%d\n", getpid());
510 return fd;
513 static void
514 setup_configless(int argc, char **argv, const char *cgi)
516 struct vhost *host;
517 struct location *loc;
519 host = xcalloc(1, sizeof(*host));
520 host->cgi = cgi;
521 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
523 loc = xcalloc(1, sizeof(*loc));
524 loc->fcgi = -1;
525 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
527 serve(argc, argv, NULL);
529 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
530 imsg_flush(&logibuf);
533 static int
534 parse_portno(const char *p)
536 const char *errstr;
537 int n;
539 n = strtonum(p, 0, UINT16_MAX, &errstr);
540 if (errstr != NULL)
541 yyerror("port number is %s: %s", errstr, p);
542 return n;
545 int
546 main(int argc, char **argv)
548 struct imsgbuf exibuf;
549 int ch, conftest = 0, configless = 0;
550 int pidfd, old_ipv6, old_port;
552 logger_init();
553 init_config();
555 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
556 switch (ch) {
557 case '6':
558 conf.ipv6 = 1;
559 configless = 1;
560 break;
562 case 'c':
563 config_path = absolutify_path(optarg);
564 break;
566 case 'D':
567 if (cmdline_symset(optarg) == -1)
568 fatal("could not parse macro definition: %s",
569 optarg);
570 break;
572 case 'd':
573 certs_dir = optarg;
574 configless = 1;
575 break;
577 case 'f':
578 conf.foreground = 1;
579 break;
581 case 'H':
582 hostname = optarg;
583 configless = 1;
584 break;
586 case 'h':
587 usage();
588 return 0;
590 case 'n':
591 conftest = 1;
592 break;
594 case 'P':
595 pidfile = optarg;
596 break;
598 case 'p':
599 conf.port = parse_portno(optarg);
600 configless = 1;
601 break;
603 case 'V':
604 puts("Version: " GMID_STRING);
605 return 0;
607 case 'v':
608 conf.verbose++;
609 break;
611 case 'x':
612 /* drop the starting / (if any) */
613 if (*optarg == '/')
614 optarg++;
615 cgi = optarg;
616 configless = 1;
617 break;
619 default:
620 usage();
621 return 1;
624 argc -= optind;
625 argv += optind;
627 if (config_path == NULL) {
628 configless = 1;
629 conf.foreground = 1;
630 conf.prefork = 1;
631 conf.verbose++;
634 if (config_path != NULL && (argc > 0 || configless))
635 fatal("can't specify options in config mode.");
637 if (conftest) {
638 if (config_path == NULL)
639 fatal("missing configuration");
640 parse_conf(config_path);
641 puts("config OK");
642 return 0;
645 if (!conf.foreground && !configless) {
646 /* log to syslog */
647 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
648 imsg_flush(&logibuf);
650 if (daemon(1, 1) == -1)
651 fatal("daemon: %s", strerror(errno));
654 if (config_path != NULL)
655 parse_conf(config_path);
657 sock4 = make_socket(conf.port, AF_INET);
658 sock6 = -1;
659 if (conf.ipv6)
660 sock6 = make_socket(conf.port, AF_INET6);
662 signal(SIGPIPE, SIG_IGN);
663 signal(SIGCHLD, SIG_IGN);
665 if (configless) {
666 setup_configless(argc, argv, cgi);
667 return 0;
670 pidfd = write_pidfile(pidfile);
672 /*
673 * Linux seems to call the event handlers even when we're
674 * doing a sigwait. These dummy handlers are here to avoid
675 * being terminated on SIGHUP, SIGINT or SIGTERM.
676 */
677 signal(SIGHUP, dummy_handler);
678 signal(SIGINT, dummy_handler);
679 signal(SIGTERM, dummy_handler);
681 /* wait a sighup and reload the daemon */
682 for (;;) {
683 int p[2];
685 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
686 PF_UNSPEC, p) == -1)
687 fatal("socketpair: %s", strerror(errno));
689 switch (fork()) {
690 case -1:
691 fatal("fork: %s", strerror(errno));
692 case 0:
693 close(p[0]);
694 imsg_init(&exibuf, p[1]);
695 _exit(serve(argc, argv, &exibuf));
698 close(p[1]);
699 imsg_init(&exibuf, p[0]);
701 if (!wait_signal())
702 break;
704 log_info(NULL, "reloading configuration %s", config_path);
706 /* close the executor (it'll close the servers too) */
707 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
708 imsg_flush(&exibuf);
709 close(p[0]);
711 old_ipv6 = conf.ipv6;
712 old_port = conf.port;
714 free_config();
715 init_config();
716 parse_conf(config_path);
718 if (old_port != conf.port) {
719 close(sock4);
720 close(sock6);
721 sock4 = -1;
722 sock6 = -1;
725 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
726 close(sock6);
727 sock6 = -1;
730 if (sock4 == -1)
731 sock4 = make_socket(conf.port, AF_INET);
732 if (sock6 == -1 && conf.ipv6)
733 sock6 = make_socket(conf.port, AF_INET6);
736 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
737 imsg_flush(&exibuf);
739 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
740 imsg_flush(&logibuf);
742 if (pidfd != -1)
743 close(pidfd);
745 return 0;