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 <grp.h>
27 #include <pwd.h>
28 #include <signal.h>
29 #include <string.h>
31 static const char *opts = "D:df:hnP:Vv";
33 static const struct option longopts[] = {
34 {"help", no_argument, NULL, 'h'},
35 {"version", no_argument, NULL, 'V'},
36 {NULL, 0, NULL, 0},
37 };
39 struct fcgi fcgi[FCGI_MAX];
41 struct vhosthead hosts;
43 int sock4, sock6;
45 struct imsgbuf logibuf, servibuf[PROC_MAX];
47 const char *config_path = "/etc/gmid.conf";
48 const char *pidfile;
50 struct conf conf;
52 struct tls_config *tlsconf;
53 struct tls *ctx;
55 static void
56 dummy_handler(int signo)
57 {
58 return;
59 }
61 void
62 load_vhosts(void)
63 {
64 struct vhost *h;
65 struct location *l;
67 TAILQ_FOREACH(h, &hosts, vhosts) {
68 TAILQ_FOREACH(l, &h->locations, locations) {
69 if (*l->dir == '\0')
70 continue;
71 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
72 fatal("open %s for domain %s: %s", l->dir, h->domain,
73 strerror(errno));
74 }
75 }
76 }
78 int
79 make_socket(int port, int family)
80 {
81 int sock, v;
82 struct sockaddr_in addr4;
83 struct sockaddr_in6 addr6;
84 struct sockaddr *addr;
85 socklen_t len;
87 switch (family) {
88 case AF_INET:
89 memset(&addr4, 0, sizeof(addr4));
90 addr4.sin_family = family;
91 addr4.sin_port = htons(port);
92 addr4.sin_addr.s_addr = INADDR_ANY;
93 addr = (struct sockaddr*)&addr4;
94 len = sizeof(addr4);
95 break;
97 case AF_INET6:
98 memset(&addr6, 0, sizeof(addr6));
99 addr6.sin6_family = AF_INET6;
100 addr6.sin6_port = htons(port);
101 addr6.sin6_addr = in6addr_any;
102 addr = (struct sockaddr*)&addr6;
103 len = sizeof(addr6);
104 break;
106 default:
107 /* unreachable */
108 abort();
111 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
112 fatal("socket: %s", strerror(errno));
114 v = 1;
115 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
116 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
118 v = 1;
119 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
120 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
122 mark_nonblock(sock);
124 if (bind(sock, addr, len) == -1)
125 fatal("bind: %s", strerror(errno));
127 if (listen(sock, 16) == -1)
128 fatal("listen: %s", strerror(errno));
130 return sock;
133 static void
134 add_keypair(struct vhost *h)
136 if (*h->ocsp == '\0') {
137 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
138 fatal("failed to load the keypair (%s, %s)",
139 h->cert, h->key);
140 } else {
141 if (tls_config_add_keypair_ocsp_file(tlsconf, h->cert, h->key,
142 h->ocsp) == -1)
143 fatal("failed to load the keypair (%s, %s, %s)",
144 h->cert, h->key, h->ocsp);
148 void
149 setup_tls(void)
151 struct vhost *h;
153 if ((tlsconf = tls_config_new()) == NULL)
154 fatal("tls_config_new");
156 /* optionally accept client certs, but don't try to verify them */
157 tls_config_verify_client_optional(tlsconf);
158 tls_config_insecure_noverifycert(tlsconf);
160 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
161 fatal("tls_config_set_protocols");
163 if ((ctx = tls_server()) == NULL)
164 fatal("tls_server failure");
166 h = TAILQ_FIRST(&hosts);
168 /* we need to set something, then we can add how many key we want */
169 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
170 fatal("tls_config_set_keypair_file failed for (%s, %s)",
171 h->cert, h->key);
173 /* same for OCSP */
174 if (*h->ocsp != '\0' &&
175 tls_config_set_ocsp_staple_file(tlsconf, h->ocsp) == -1)
176 fatal("tls_config_set_ocsp_staple_file failed for (%s)",
177 h->ocsp);
179 while ((h = TAILQ_NEXT(h, vhosts)) != NULL)
180 add_keypair(h);
182 if (tls_configure(ctx, tlsconf) == -1)
183 fatal("tls_configure: %s", tls_error(ctx));
186 static int
187 listener_main(struct imsgbuf *ibuf)
189 drop_priv();
190 if (load_default_mime(&conf.mime) == -1)
191 fatal("load_default_mime: %s", strerror(errno));
192 sort_mime(&conf.mime);
193 load_vhosts();
194 loop(ctx, sock4, sock6, ibuf);
195 return 0;
198 void
199 init_config(void)
201 TAILQ_INIT(&hosts);
203 conf.port = 1965;
204 conf.ipv6 = 0;
205 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
207 init_mime(&conf.mime);
209 conf.prefork = 3;
212 void
213 free_config(void)
215 struct vhost *h, *th;
216 struct location *l, *tl;
217 struct proxy *p, *tp;
218 struct envlist *e, *te;
219 struct alist *a, *ta;
220 int v;
222 v = conf.verbose;
224 free_mime(&conf.mime);
225 memset(&conf, 0, sizeof(conf));
227 conf.verbose = v;
229 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
230 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
231 TAILQ_REMOVE(&h->locations, l, locations);
233 if (l->dirfd != -1)
234 close(l->dirfd);
236 free(l);
239 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
240 TAILQ_REMOVE(&h->params, e, envs);
241 free(e);
244 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
245 TAILQ_REMOVE(&h->aliases, a, aliases);
246 free(a);
249 TAILQ_FOREACH_SAFE(p, &h->proxies, proxies, tp) {
250 TAILQ_REMOVE(&h->proxies, p, proxies);
251 tls_unload_file(p->cert, p->certlen);
252 tls_unload_file(p->key, p->keylen);
253 free(p);
256 TAILQ_REMOVE(&hosts, h, vhosts);
257 free(h);
260 memset(fcgi, 0, sizeof(fcgi));
262 tls_free(ctx);
263 tls_config_free(tlsconf);
266 static int
267 wait_signal(void)
269 sigset_t mask;
270 int signo;
272 sigemptyset(&mask);
273 sigaddset(&mask, SIGHUP);
274 sigaddset(&mask, SIGINT);
275 sigaddset(&mask, SIGTERM);
276 sigwait(&mask, &signo);
278 return signo == SIGHUP;
281 void
282 drop_priv(void)
284 struct passwd *pw = NULL;
286 if (*conf.chroot != '\0' && *conf.user == '\0')
287 fatal("can't chroot without an user to switch to after.");
289 if (*conf.user != '\0') {
290 if ((pw = getpwnam(conf.user)) == NULL)
291 fatal("can't find user %s", conf.user);
294 if (*conf.chroot != '\0') {
295 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
296 fatal("%s: %s", conf.chroot, strerror(errno));
299 if (pw != NULL) {
300 if (setgroups(1, &pw->pw_gid) == -1 ||
301 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1 ||
302 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
303 fatal("cannot drop privileges");
306 if (getuid() == 0)
307 log_warn(NULL, "not a good idea to run a network daemon as root");
310 static void
311 usage(void)
313 fprintf(stderr,
314 "Version: " GMID_STRING "\n"
315 "Usage: %s [-dhnVv] [-D macro=value] [-f config] [-P pidfile]\n",
316 getprogname());
319 static void
320 logger_init(void)
322 int p[2];
324 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
325 err(1, "socketpair");
327 switch (fork()) {
328 case -1:
329 err(1, "fork");
330 case 0:
331 signal(SIGHUP, SIG_IGN);
332 close(p[0]);
333 setproctitle("logger");
334 imsg_init(&logibuf, p[1]);
335 drop_priv();
336 _exit(logger_main(p[1], &logibuf));
337 default:
338 close(p[1]);
339 imsg_init(&logibuf, p[0]);
340 return;
344 static void
345 serve(void)
347 int i, p[2];
349 /* setup tls before dropping privileges: we don't want user
350 * to put private certs inside the chroot. */
351 setup_tls();
353 for (i = 0; i < conf.prefork; ++i) {
354 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
355 PF_UNSPEC, p) == -1)
356 fatal("socketpair: %s", strerror(errno));
358 switch (fork()) {
359 case -1:
360 fatal("fork: %s", strerror(errno));
361 case 0: /* child */
362 close(p[0]);
363 imsg_init(&servibuf[i], p[1]);
364 setproctitle("server");
365 _exit(listener_main(&servibuf[i]));
366 default:
367 close(p[1]);
368 imsg_init(&servibuf[i], p[0]);
373 static int
374 write_pidfile(const char *pidfile)
376 struct flock lock;
377 int fd;
379 if (pidfile == NULL)
380 return -1;
382 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
383 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
385 lock.l_start = 0;
386 lock.l_len = 0;
387 lock.l_type = F_WRLCK;
388 lock.l_whence = SEEK_SET;
390 if (fcntl(fd, F_SETLK, &lock) == -1)
391 fatal("can't lock %s, gmid is already running?", pidfile);
393 if (ftruncate(fd, 0) == -1)
394 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
396 dprintf(fd, "%d\n", getpid());
398 return fd;
401 int
402 main(int argc, char **argv)
404 int i, ch, conftest = 0;
405 int pidfd, old_ipv6, old_port;
407 logger_init();
408 init_config();
410 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
411 switch (ch) {
412 case 'D':
413 if (cmdline_symset(optarg) == -1)
414 fatal("could not parse macro definition: %s",
415 optarg);
416 break;
417 case 'd':
418 conf.foreground = 1;
419 break;
420 case 'f':
421 config_path = absolutify_path(optarg);
422 break;
423 case 'h':
424 usage();
425 return 0;
426 case 'n':
427 conftest++;
428 break;
429 case 'P':
430 pidfile = optarg;
431 break;
432 case 'V':
433 puts("Version: " GMID_STRING);
434 return 0;
435 case 'v':
436 conf.verbose++;
437 break;
438 default:
439 usage();
440 return 1;
443 argc -= optind;
444 argv += optind;
446 if (argc != 0)
447 usage();
449 parse_conf(config_path);
451 if (conftest) {
452 fprintf(stderr, "config OK\n");
453 if (conftest > 1)
454 print_conf();
455 return 0;
458 if (!conf.foreground) {
459 /* log to syslog */
460 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, -1, NULL, 0);
461 imsg_flush(&logibuf);
463 if (daemon(1, 1) == -1)
464 fatal("daemon: %s", strerror(errno));
467 sock4 = make_socket(conf.port, AF_INET);
468 sock6 = -1;
469 if (conf.ipv6)
470 sock6 = make_socket(conf.port, AF_INET6);
472 signal(SIGPIPE, SIG_IGN);
474 pidfd = write_pidfile(pidfile);
476 /*
477 * Linux seems to call the event handlers even when we're
478 * doing a sigwait. These dummy handlers are here to avoid
479 * being terminated on SIGHUP, SIGINT or SIGTERM.
480 */
481 signal(SIGHUP, dummy_handler);
482 signal(SIGINT, dummy_handler);
483 signal(SIGTERM, dummy_handler);
485 /* wait a sighup and reload the daemon */
486 for (;;) {
487 serve();
489 if (!wait_signal())
490 break;
492 log_info(NULL, "reloading configuration %s", config_path);
494 /* close the servers */
495 for (i = 0; i < conf.prefork; ++i) {
496 imsg_compose(&servibuf[i], IMSG_QUIT, 0, 0, -1, NULL, 0);
497 imsg_flush(&servibuf[i]);
498 close(servibuf[i].fd);
501 old_ipv6 = conf.ipv6;
502 old_port = conf.port;
504 free_config();
505 init_config();
506 parse_conf(config_path);
508 if (old_port != conf.port) {
509 close(sock4);
510 close(sock6);
511 sock4 = -1;
512 sock6 = -1;
515 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
516 close(sock6);
517 sock6 = -1;
520 if (sock4 == -1)
521 sock4 = make_socket(conf.port, AF_INET);
522 if (sock6 == -1 && conf.ipv6)
523 sock6 = make_socket(conf.port, AF_INET6);
526 for (i = 0; i < conf.prefork; ++i) {
527 imsg_compose(&servibuf[i], IMSG_QUIT, 0, 0, -1, NULL, 0);
528 imsg_flush(&servibuf[i]);
529 close(servibuf[i].fd);
532 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
533 imsg_flush(&logibuf);
534 close(logibuf.fd);
536 if (pidfd != -1)
537 close(pidfd);
539 return 0;