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 void
198 setup_tls(void)
200 struct vhost *h;
202 if ((tlsconf = tls_config_new()) == NULL)
203 fatal("tls_config_new");
205 /* optionally accept client certs, but don't try to verify them */
206 tls_config_verify_client_optional(tlsconf);
207 tls_config_insecure_noverifycert(tlsconf);
209 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
210 fatal("tls_config_set_protocols");
212 if ((ctx = tls_server()) == NULL)
213 fatal("tls_server failure");
215 h = TAILQ_FIRST(&hosts);
217 /* we need to set something, then we can add how many key we want */
218 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
219 fatal("tls_config_set_keypair_file failed for (%s, %s)",
220 h->cert, h->key);
222 while ((h = TAILQ_NEXT(h, vhosts)) != NULL) {
223 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
224 fatal("failed to load the keypair (%s, %s)",
225 h->cert, h->key);
228 if (tls_configure(ctx, tlsconf) == -1)
229 fatal("tls_configure: %s", tls_error(ctx));
232 static int
233 listener_main(struct imsgbuf *ibuf)
235 drop_priv();
236 load_default_mime(&conf.mime);
237 load_vhosts();
238 loop(ctx, sock4, sock6, ibuf);
239 return 0;
242 void
243 init_config(void)
245 TAILQ_INIT(&hosts);
247 conf.port = 1965;
248 conf.ipv6 = 0;
249 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
251 init_mime(&conf.mime);
253 conf.chroot = NULL;
254 conf.user = NULL;
256 conf.prefork = 3;
259 void
260 free_config(void)
262 struct vhost *h, *th;
263 struct location *l, *tl;
264 struct envlist *e, *te;
265 struct alist *a, *ta;
266 int v, i;
268 v = conf.verbose;
270 free(conf.chroot);
271 free(conf.user);
272 memset(&conf, 0, sizeof(conf));
274 conf.verbose = v;
276 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
277 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
278 TAILQ_REMOVE(&h->locations, l, locations);
280 free((char*)l->match);
281 free((char*)l->lang);
282 free((char*)l->default_mime);
283 free((char*)l->index);
284 free((char*)l->block_fmt);
285 free((char*)l->dir);
287 if (l->dirfd != -1)
288 close(l->dirfd);
290 free(l);
293 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
294 TAILQ_REMOVE(&h->env, e, envs);
296 free(e->name);
297 free(e->value);
298 free(e);
301 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
302 TAILQ_REMOVE(&h->params, e, envs);
304 free(e->name);
305 free(e->value);
306 free(e);
309 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
310 TAILQ_REMOVE(&h->aliases, a, aliases);
312 free(a->alias);
313 free(a);
316 free((char*)h->domain);
317 free((char*)h->cert);
318 free((char*)h->key);
319 free((char*)h->cgi);
320 free((char*)h->entrypoint);
322 TAILQ_REMOVE(&hosts, h, vhosts);
323 free(h);
326 for (i = 0; i < FCGI_MAX; ++i) {
327 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
328 break;
329 free(fcgi[i].path);
330 free(fcgi[i].port);
331 free(fcgi[i].prog);
333 fcgi[i].path = NULL;
334 fcgi[i].port = NULL;
335 fcgi[i].prog = NULL;
338 tls_free(ctx);
339 tls_config_free(tlsconf);
342 static int
343 wait_signal(void)
345 sigset_t mask;
346 int signo;
348 sigemptyset(&mask);
349 sigaddset(&mask, SIGHUP);
350 sigaddset(&mask, SIGINT);
351 sigaddset(&mask, SIGTERM);
352 sigwait(&mask, &signo);
354 return signo == SIGHUP;
357 void
358 drop_priv(void)
360 struct passwd *pw = NULL;
362 if (conf.chroot != NULL && conf.user == NULL)
363 fatal("can't chroot without an user to switch to after.");
365 if (conf.user != NULL) {
366 if ((pw = getpwnam(conf.user)) == NULL)
367 fatal("can't find user %s", conf.user);
370 if (conf.chroot != NULL) {
371 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
372 fatal("%s: %s", conf.chroot, strerror(errno));
375 if (pw != NULL) {
376 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
377 fatal("setresuid(%d): %s", pw->pw_uid,
378 strerror(errno));
381 if (getuid() == 0)
382 log_warn(NULL, "not a good idea to run a network daemon as root");
385 static void
386 usage(void)
388 fprintf(stderr,
389 "Version: " GMID_STRING "\n"
390 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n"
391 " %s [-6hVv] [-d certs-dir] [-H hostname] [-p port] [-x cgi] [dir]\n",
392 getprogname(),
393 getprogname());
396 static void
397 logger_init(void)
399 int p[2];
401 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
402 err(1, "socketpair");
404 switch (fork()) {
405 case -1:
406 err(1, "fork");
407 case 0:
408 signal(SIGHUP, SIG_IGN);
409 close(p[0]);
410 setproctitle("logger");
411 imsg_init(&logibuf, p[1]);
412 drop_priv();
413 _exit(logger_main(p[1], &logibuf));
414 default:
415 close(p[1]);
416 imsg_init(&logibuf, p[0]);
417 return;
421 static int
422 serve(int argc, char **argv, struct imsgbuf *ibuf)
424 char path[PATH_MAX];
425 int i, p[2];
426 struct vhost *h;
427 struct location *l;
429 if (config_path == NULL) {
430 if (hostname == NULL)
431 hostname = "localhost";
432 if (certs_dir == NULL)
433 certs_dir = data_dir();
434 load_local_cert(hostname, certs_dir);
436 h = TAILQ_FIRST(&hosts);
437 h->domain = "*";
439 l = TAILQ_FIRST(&h->locations);
440 l->auto_index = 1;
441 l->match = "*";
443 switch (argc) {
444 case 0:
445 l->dir = getcwd(path, sizeof(path));
446 break;
447 case 1:
448 l->dir = absolutify_path(argv[0]);
449 break;
450 default:
451 usage();
452 return 1;
455 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
458 /* setup tls before dropping privileges: we don't want user
459 * to put private certs inside the chroot. */
460 setup_tls();
462 for (i = 0; i < conf.prefork; ++i) {
463 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
464 PF_UNSPEC, p) == -1)
465 fatal("socketpair: %s", strerror(errno));
467 switch (fork()) {
468 case -1:
469 fatal("fork: %s", strerror(errno));
470 case 0: /* child */
471 close(p[0]);
472 imsg_init(&exibuf, p[1]);
473 setproctitle("server");
474 _exit(listener_main(&exibuf));
475 default:
476 close(p[1]);
477 imsg_init(&servibuf[i], p[0]);
481 setproctitle("executor");
482 drop_priv();
483 _exit(executor_main(ibuf));
486 static int
487 write_pidfile(const char *pidfile)
489 struct flock lock;
490 int fd;
492 if (pidfile == NULL)
493 return -1;
495 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
496 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
498 lock.l_start = 0;
499 lock.l_len = 0;
500 lock.l_type = F_WRLCK;
501 lock.l_whence = SEEK_SET;
503 if (fcntl(fd, F_SETLK, &lock) == -1)
504 fatal("can't lock %s, gmid is already running?", pidfile);
506 if (ftruncate(fd, 0) == -1)
507 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
509 dprintf(fd, "%d\n", getpid());
511 return fd;
514 static void
515 setup_configless(int argc, char **argv, const char *cgi)
517 struct vhost *host;
518 struct location *loc;
520 host = xcalloc(1, sizeof(*host));
521 host->cgi = cgi;
522 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
524 loc = xcalloc(1, sizeof(*loc));
525 loc->fcgi = -1;
526 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
528 serve(argc, argv, NULL);
530 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
531 imsg_flush(&logibuf);
534 static int
535 parse_portno(const char *p)
537 const char *errstr;
538 int n;
540 n = strtonum(p, 0, UINT16_MAX, &errstr);
541 if (errstr != NULL)
542 yyerror("port number is %s: %s", errstr, p);
543 return n;
546 int
547 main(int argc, char **argv)
549 struct imsgbuf exibuf;
550 int ch, conftest = 0, configless = 0;
551 int pidfd, old_ipv6, old_port;
553 logger_init();
554 init_config();
556 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
557 switch (ch) {
558 case '6':
559 conf.ipv6 = 1;
560 configless = 1;
561 break;
563 case 'c':
564 config_path = absolutify_path(optarg);
565 break;
567 case 'D':
568 if (cmdline_symset(optarg) == -1)
569 fatal("could not parse macro definition: %s",
570 optarg);
571 break;
573 case 'd':
574 certs_dir = optarg;
575 configless = 1;
576 break;
578 case 'f':
579 conf.foreground = 1;
580 break;
582 case 'H':
583 hostname = optarg;
584 configless = 1;
585 break;
587 case 'h':
588 usage();
589 return 0;
591 case 'n':
592 conftest = 1;
593 break;
595 case 'P':
596 pidfile = optarg;
597 break;
599 case 'p':
600 conf.port = parse_portno(optarg);
601 configless = 1;
602 break;
604 case 'V':
605 puts("Version: " GMID_STRING);
606 return 0;
608 case 'v':
609 conf.verbose++;
610 break;
612 case 'x':
613 /* drop the starting / (if any) */
614 if (*optarg == '/')
615 optarg++;
616 cgi = optarg;
617 configless = 1;
618 break;
620 default:
621 usage();
622 return 1;
625 argc -= optind;
626 argv += optind;
628 if (config_path == NULL) {
629 configless = 1;
630 conf.foreground = 1;
631 conf.prefork = 1;
632 conf.verbose++;
635 if (config_path != NULL && (argc > 0 || configless))
636 fatal("can't specify options in config mode.");
638 if (conftest) {
639 if (config_path == NULL)
640 fatal("missing configuration");
641 parse_conf(config_path);
642 puts("config OK");
643 return 0;
646 if (!conf.foreground && !configless) {
647 /* log to syslog */
648 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
649 imsg_flush(&logibuf);
651 if (daemon(1, 1) == -1)
652 fatal("daemon: %s", strerror(errno));
655 if (config_path != NULL)
656 parse_conf(config_path);
658 sock4 = make_socket(conf.port, AF_INET);
659 sock6 = -1;
660 if (conf.ipv6)
661 sock6 = make_socket(conf.port, AF_INET6);
663 signal(SIGPIPE, SIG_IGN);
664 signal(SIGCHLD, SIG_IGN);
666 if (configless) {
667 setup_configless(argc, argv, cgi);
668 return 0;
671 pidfd = write_pidfile(pidfile);
673 /*
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.
677 */
678 signal(SIGHUP, dummy_handler);
679 signal(SIGINT, dummy_handler);
680 signal(SIGTERM, dummy_handler);
682 /* wait a sighup and reload the daemon */
683 for (;;) {
684 int p[2];
686 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
687 PF_UNSPEC, p) == -1)
688 fatal("socketpair: %s", strerror(errno));
690 switch (fork()) {
691 case -1:
692 fatal("fork: %s", strerror(errno));
693 case 0:
694 close(p[0]);
695 imsg_init(&exibuf, p[1]);
696 _exit(serve(argc, argv, &exibuf));
699 close(p[1]);
700 imsg_init(&exibuf, p[0]);
702 if (!wait_signal())
703 break;
705 log_info(NULL, "reloading configuration %s", config_path);
707 /* close the executor (it'll close the servers too) */
708 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
709 imsg_flush(&exibuf);
710 close(p[0]);
712 old_ipv6 = conf.ipv6;
713 old_port = conf.port;
715 free_config();
716 init_config();
717 parse_conf(config_path);
719 if (old_port != conf.port) {
720 close(sock4);
721 close(sock6);
722 sock4 = -1;
723 sock6 = -1;
726 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
727 close(sock6);
728 sock6 = -1;
731 if (sock4 == -1)
732 sock4 = make_socket(conf.port, AF_INET);
733 if (sock6 == -1 && conf.ipv6)
734 sock6 = make_socket(conf.port, AF_INET6);
737 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
738 imsg_flush(&exibuf);
740 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
741 imsg_flush(&logibuf);
743 if (pidfd != -1)
744 close(pidfd);
746 return 0;