Blob


1 /*
2 * Copyright (c) 2020, 2021, 2022 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 = "D:df:hnP:Vv";
32 static const 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 = "/etc/gmid.conf";
47 const char *pidfile;
49 struct conf conf;
51 struct tls_config *tlsconf;
52 struct tls *ctx;
54 static void
55 dummy_handler(int signo)
56 {
57 return;
58 }
60 void
61 load_vhosts(void)
62 {
63 struct vhost *h;
64 struct location *l;
66 TAILQ_FOREACH(h, &hosts, vhosts) {
67 TAILQ_FOREACH(l, &h->locations, locations) {
68 if (l->dir == NULL)
69 continue;
70 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
71 fatal("open %s for domain %s: %s", l->dir, h->domain,
72 strerror(errno));
73 }
74 }
75 }
77 int
78 make_socket(int port, int family)
79 {
80 int sock, v;
81 struct sockaddr_in addr4;
82 struct sockaddr_in6 addr6;
83 struct sockaddr *addr;
84 socklen_t len;
86 switch (family) {
87 case AF_INET:
88 memset(&addr4, 0, sizeof(addr4));
89 addr4.sin_family = family;
90 addr4.sin_port = htons(port);
91 addr4.sin_addr.s_addr = INADDR_ANY;
92 addr = (struct sockaddr*)&addr4;
93 len = sizeof(addr4);
94 break;
96 case AF_INET6:
97 memset(&addr6, 0, sizeof(addr6));
98 addr6.sin6_family = AF_INET6;
99 addr6.sin6_port = htons(port);
100 addr6.sin6_addr = in6addr_any;
101 addr = (struct sockaddr*)&addr6;
102 len = sizeof(addr6);
103 break;
105 default:
106 /* unreachable */
107 abort();
110 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
111 fatal("socket: %s", strerror(errno));
113 v = 1;
114 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
115 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
117 v = 1;
118 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
119 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
121 mark_nonblock(sock);
123 if (bind(sock, addr, len) == -1)
124 fatal("bind: %s", strerror(errno));
126 if (listen(sock, 16) == -1)
127 fatal("listen: %s", strerror(errno));
129 return sock;
132 static void
133 add_keypair(struct vhost *h)
135 if (h->ocsp == NULL) {
136 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
137 fatal("failed to load the keypair (%s, %s)",
138 h->cert, h->key);
139 } else {
140 if (tls_config_add_keypair_ocsp_file(tlsconf, h->cert, h->key,
141 h->ocsp) == -1)
142 fatal("failed to load the keypair (%s, %s, %s)",
143 h->cert, h->key, h->ocsp);
147 void
148 setup_tls(void)
150 struct vhost *h;
152 if ((tlsconf = tls_config_new()) == NULL)
153 fatal("tls_config_new");
155 /* optionally accept client certs, but don't try to verify them */
156 tls_config_verify_client_optional(tlsconf);
157 tls_config_insecure_noverifycert(tlsconf);
159 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
160 fatal("tls_config_set_protocols");
162 if ((ctx = tls_server()) == NULL)
163 fatal("tls_server failure");
165 h = TAILQ_FIRST(&hosts);
167 /* we need to set something, then we can add how many key we want */
168 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
169 fatal("tls_config_set_keypair_file failed for (%s, %s)",
170 h->cert, h->key);
172 /* same for OCSP */
173 if (h->ocsp != NULL &&
174 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
175 fatal("tls_config_set_ocsp_staple_file failed for (%s)",
176 h->ocsp);
178 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
179 add_keypair(h);
181 if (tls_configure(ctx, tlsconf) == -1)
182 fatal("tls_configure: %s", tls_error(ctx));
185 static int
186 listener_main(struct imsgbuf *ibuf)
188 drop_priv();
189 if (!conf.mime.skip_defaults && load_default_mime(&conf.mime) == -1)
190 fatal("load_default_mime: %s", strerror(errno));
191 sort_mime(&conf.mime);
192 load_vhosts();
193 loop(ctx, sock4, sock6, ibuf);
194 return 0;
197 void
198 init_config(void)
200 TAILQ_INIT(&hosts);
202 conf.port = 1965;
203 conf.ipv6 = 0;
204 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
206 init_mime(&conf.mime);
208 conf.prefork = 3;
211 void
212 free_config(void)
214 struct vhost *h, *th;
215 struct location *l, *tl;
216 struct proxy *p, *tp;
217 struct envlist *e, *te;
218 struct alist *a, *ta;
219 int v, i;
221 v = conf.verbose;
223 free_mime(&conf.mime);
224 memset(&conf, 0, sizeof(conf));
226 conf.verbose = v;
228 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
229 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
230 TAILQ_REMOVE(&h->locations, l, locations);
232 free((char*)l->match);
233 free((char*)l->lang);
234 free((char*)l->default_mime);
235 free((char*)l->index);
236 free((char*)l->block_fmt);
237 free((char*)l->dir);
239 if (l->dirfd != -1)
240 close(l->dirfd);
242 free(l);
245 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
246 TAILQ_REMOVE(&h->env, e, envs);
248 free(e->name);
249 free(e->value);
250 free(e);
253 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
254 TAILQ_REMOVE(&h->params, e, envs);
256 free(e->name);
257 free(e->value);
258 free(e);
261 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
262 TAILQ_REMOVE(&h->aliases, a, aliases);
264 free(a->alias);
265 free(a);
268 TAILQ_FOREACH_SAFE(p, &h->proxies, proxies, tp) {
269 TAILQ_REMOVE(&h->proxies, p, proxies);
271 free(p->match_proto);
272 free(p->match_host);
273 free(p->host);
274 free(p->sni);
275 tls_unload_file(p->cert, p->certlen);
276 tls_unload_file(p->key, p->keylen);
277 free(p);
280 free((char*)h->domain);
281 free((char*)h->cert);
282 free((char*)h->key);
283 free((char*)h->ocsp);
284 free((char*)h->entrypoint);
286 TAILQ_REMOVE(&hosts, h, vhosts);
287 free(h);
290 for (i = 0; i < FCGI_MAX; ++i) {
291 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
292 break;
293 free(fcgi[i].path);
294 free(fcgi[i].port);
295 free(fcgi[i].prog);
297 fcgi[i].path = NULL;
298 fcgi[i].port = NULL;
299 fcgi[i].prog = NULL;
302 tls_free(ctx);
303 tls_config_free(tlsconf);
306 static int
307 wait_signal(void)
309 sigset_t mask;
310 int signo;
312 sigemptyset(&mask);
313 sigaddset(&mask, SIGHUP);
314 sigaddset(&mask, SIGINT);
315 sigaddset(&mask, SIGTERM);
316 sigwait(&mask, &signo);
318 return signo == SIGHUP;
321 void
322 drop_priv(void)
324 struct passwd *pw = NULL;
326 if (*conf.chroot != '\0' && *conf.user == '\0')
327 fatal("can't chroot without an user to switch to after.");
329 if (*conf.user != '\0') {
330 if ((pw = getpwnam(conf.user)) == NULL)
331 fatal("can't find user %s", conf.user);
334 if (*conf.chroot != '\0') {
335 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
336 fatal("%s: %s", conf.chroot, strerror(errno));
339 if (pw != NULL) {
340 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
341 fatal("setresuid(%d): %s", pw->pw_uid,
342 strerror(errno));
345 if (getuid() == 0)
346 log_warn(NULL, "not a good idea to run a network daemon as root");
349 static void
350 usage(void)
352 fprintf(stderr,
353 "Version: " GMID_STRING "\n"
354 "Usage: %s [-dhnVv] [-D macro=value] [-f config] [-P pidfile]\n",
355 getprogname());
358 static void
359 logger_init(void)
361 int p[2];
363 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
364 err(1, "socketpair");
366 switch (fork()) {
367 case -1:
368 err(1, "fork");
369 case 0:
370 signal(SIGHUP, SIG_IGN);
371 close(p[0]);
372 setproctitle("logger");
373 imsg_init(&logibuf, p[1]);
374 drop_priv();
375 _exit(logger_main(p[1], &logibuf));
376 default:
377 close(p[1]);
378 imsg_init(&logibuf, p[0]);
379 return;
383 static void
384 serve(void)
386 int i, p[2];
388 /* setup tls before dropping privileges: we don't want user
389 * to put private certs inside the chroot. */
390 setup_tls();
392 for (i = 0; i < conf.prefork; ++i) {
393 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
394 PF_UNSPEC, p) == -1)
395 fatal("socketpair: %s", strerror(errno));
397 switch (fork()) {
398 case -1:
399 fatal("fork: %s", strerror(errno));
400 case 0: /* child */
401 close(p[0]);
402 imsg_init(&exibuf, p[1]);
403 setproctitle("server");
404 _exit(listener_main(&exibuf));
405 default:
406 close(p[1]);
407 imsg_init(&servibuf[i], p[0]);
412 static int
413 write_pidfile(const char *pidfile)
415 struct flock lock;
416 int fd;
418 if (pidfile == NULL)
419 return -1;
421 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
422 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
424 lock.l_start = 0;
425 lock.l_len = 0;
426 lock.l_type = F_WRLCK;
427 lock.l_whence = SEEK_SET;
429 if (fcntl(fd, F_SETLK, &lock) == -1)
430 fatal("can't lock %s, gmid is already running?", pidfile);
432 if (ftruncate(fd, 0) == -1)
433 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
435 dprintf(fd, "%d\n", getpid());
437 return fd;
440 int
441 main(int argc, char **argv)
443 int i, ch, conftest = 0;
444 int pidfd, old_ipv6, old_port;
446 logger_init();
447 init_config();
449 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
450 switch (ch) {
451 case 'D':
452 if (cmdline_symset(optarg) == -1)
453 fatal("could not parse macro definition: %s",
454 optarg);
455 break;
457 case 'd':
458 conf.foreground = 1;
459 break;
461 case 'f':
462 config_path = absolutify_path(optarg);
463 break;
465 case 'h':
466 usage();
467 return 0;
469 case 'n':
470 conftest++;
471 break;
473 case 'P':
474 pidfile = optarg;
475 break;
477 case 'V':
478 puts("Version: " GMID_STRING);
479 return 0;
481 case 'v':
482 conf.verbose++;
483 break;
485 default:
486 usage();
487 return 1;
490 argc -= optind;
491 argv += optind;
493 if (argc != 0)
494 usage();
496 parse_conf(config_path);
498 if (conftest) {
499 fprintf(stderr, "config OK\n");
500 if (conftest > 1)
501 print_conf();
502 return 0;
505 if (!conf.foreground) {
506 /* log to syslog */
507 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
508 imsg_flush(&logibuf);
510 if (daemon(1, 1) == -1)
511 fatal("daemon: %s", strerror(errno));
514 sock4 = make_socket(conf.port, AF_INET);
515 sock6 = -1;
516 if (conf.ipv6)
517 sock6 = make_socket(conf.port, AF_INET6);
519 signal(SIGPIPE, SIG_IGN);
521 pidfd = write_pidfile(pidfile);
523 /*
524 * Linux seems to call the event handlers even when we're
525 * doing a sigwait. These dummy handlers are here to avoid
526 * being terminated on SIGHUP, SIGINT or SIGTERM.
527 */
528 signal(SIGHUP, dummy_handler);
529 signal(SIGINT, dummy_handler);
530 signal(SIGTERM, dummy_handler);
532 /* wait a sighup and reload the daemon */
533 for (;;) {
534 serve();
536 if (!wait_signal())
537 break;
539 log_info(NULL, "reloading configuration %s", config_path);
541 /* close the servers */
542 for (i = 0; i < conf.prefork; ++i) {
543 imsg_compose(&servibuf[i], IMSG_QUIT, 0, 0, -1, NULL, 0);
544 imsg_flush(&servibuf[i]);
545 close(servibuf[i].fd);
548 old_ipv6 = conf.ipv6;
549 old_port = conf.port;
551 free_config();
552 init_config();
553 parse_conf(config_path);
555 if (old_port != conf.port) {
556 close(sock4);
557 close(sock6);
558 sock4 = -1;
559 sock6 = -1;
562 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
563 close(sock6);
564 sock6 = -1;
567 if (sock4 == -1)
568 sock4 = make_socket(conf.port, AF_INET);
569 if (sock6 == -1 && conf.ipv6)
570 sock6 = make_socket(conf.port, AF_INET6);
573 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
574 imsg_flush(&exibuf);
576 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
577 imsg_flush(&logibuf);
579 if (pidfd != -1)
580 close(pidfd);
582 return 0;