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 <libgen.h>
24 #include <limits.h>
25 #include <pwd.h>
26 #include <signal.h>
27 #include <string.h>
29 struct fcgi fcgi[FCGI_MAX];
31 struct vhosthead hosts;
33 int sock4, sock6;
35 struct imsgbuf logibuf, exibuf, servibuf[PROC_MAX];
37 const char *config_path, *certs_dir, *hostname, *pidfile, *cgi;
39 struct conf conf;
41 struct tls_config *tlsconf;
42 struct tls *ctx;
44 static void
45 dummy_handler(int signo)
46 {
47 return;
48 }
50 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
51 static void
52 pdirname(const char *path, char *dn)
53 {
54 char p[PATH_MAX+1];
55 char *t;
57 strlcpy(p, path, sizeof(p));
58 t = dirname(p);
59 memmove(dn, t, strlen(t)+1);
60 }
62 static void
63 mkdirs(const char *path, mode_t mode)
64 {
65 char dname[PATH_MAX+1];
67 pdirname(path, dname);
68 if (!strcmp(dname, "/"))
69 return;
70 mkdirs(dname, mode);
71 if (mkdir(path, mode) != 0 && errno != EEXIST)
72 fatal("can't mkdir %s: %s", path, strerror(errno));
73 }
75 /* $XDG_DATA_HOME/gmid */
76 char *
77 data_dir(void)
78 {
79 const char *home, *xdg;
80 char *t;
82 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
83 if ((home = getenv("HOME")) == NULL)
84 errx(1, "XDG_DATA_HOME and HOME both empty");
85 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
86 err(1, "asprintf");
87 } else {
88 if (asprintf(&t, "%s/gmid", xdg) == -1)
89 err(1, "asprintf");
90 }
92 mkdirs(t, 0755);
93 return t;
94 }
96 void
97 load_local_cert(const char *hostname, const char *dir)
98 {
99 char *cert, *key;
100 struct vhost *h;
102 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
103 errx(1, "asprintf");
104 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
105 errx(1, "asprintf");
107 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
108 gen_certificate(hostname, cert, key);
110 h = TAILQ_FIRST(&hosts);
111 h->cert = cert;
112 h->key = key;
113 h->domain = hostname;
116 void
117 load_vhosts(void)
119 struct vhost *h;
120 struct location *l;
122 TAILQ_FOREACH(h, &hosts, vhosts) {
123 TAILQ_FOREACH(l, &h->locations, locations) {
124 if (l->dir == NULL)
125 continue;
126 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
127 fatal("open %s for domain %s", l->dir, h->domain);
132 int
133 make_socket(int port, int family)
135 int sock, v;
136 struct sockaddr_in addr4;
137 struct sockaddr_in6 addr6;
138 struct sockaddr *addr;
139 socklen_t len;
141 switch (family) {
142 case AF_INET:
143 bzero(&addr4, sizeof(addr4));
144 addr4.sin_family = family;
145 addr4.sin_port = htons(port);
146 addr4.sin_addr.s_addr = INADDR_ANY;
147 addr = (struct sockaddr*)&addr4;
148 len = sizeof(addr4);
149 break;
151 case AF_INET6:
152 bzero(&addr6, sizeof(addr6));
153 addr6.sin6_family = AF_INET6;
154 addr6.sin6_port = htons(port);
155 addr6.sin6_addr = in6addr_any;
156 addr = (struct sockaddr*)&addr6;
157 len = sizeof(addr6);
158 break;
160 default:
161 /* unreachable */
162 abort();
165 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
166 fatal("socket: %s", strerror(errno));
168 v = 1;
169 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
170 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
172 v = 1;
173 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
174 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
176 mark_nonblock(sock);
178 if (bind(sock, addr, len) == -1)
179 fatal("bind: %s", strerror(errno));
181 if (listen(sock, 16) == -1)
182 fatal("listen: %s", strerror(errno));
184 return sock;
187 void
188 setup_tls(void)
190 struct vhost *h;
192 if ((tlsconf = tls_config_new()) == NULL)
193 fatal("tls_config_new");
195 /* optionally accept client certs, but don't try to verify them */
196 tls_config_verify_client_optional(tlsconf);
197 tls_config_insecure_noverifycert(tlsconf);
199 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
200 fatal("tls_config_set_protocols");
202 if ((ctx = tls_server()) == NULL)
203 fatal("tls_server failure");
205 h = TAILQ_FIRST(&hosts);
207 /* we need to set something, then we can add how many key we want */
208 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
209 fatal("tls_config_set_keypair_file failed for (%s, %s)",
210 h->cert, h->key);
212 while ((h = TAILQ_NEXT(h, vhosts)) != NULL) {
213 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
214 fatal("failed to load the keypair (%s, %s)",
215 h->cert, h->key);
218 if (tls_configure(ctx, tlsconf) == -1)
219 fatal("tls_configure: %s", tls_error(ctx));
222 static int
223 listener_main(struct imsgbuf *ibuf)
225 drop_priv();
226 load_default_mime(&conf.mime);
227 load_vhosts();
228 loop(ctx, sock4, sock6, ibuf);
229 return 0;
232 void
233 init_config(void)
235 TAILQ_INIT(&hosts);
237 conf.port = 1965;
238 conf.ipv6 = 0;
239 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
241 init_mime(&conf.mime);
243 conf.chroot = NULL;
244 conf.user = NULL;
246 conf.prefork = 3;
249 void
250 free_config(void)
252 struct vhost *h, *th;
253 struct location *l, *tl;
254 struct envlist *e, *te;
255 struct alist *a, *ta;
256 int v, i;
258 v = conf.verbose;
260 free(conf.chroot);
261 free(conf.user);
262 memset(&conf, 0, sizeof(conf));
264 conf.verbose = v;
266 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
267 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
268 TAILQ_REMOVE(&h->locations, l, locations);
270 free((char*)l->match);
271 free((char*)l->lang);
272 free((char*)l->default_mime);
273 free((char*)l->index);
274 free((char*)l->block_fmt);
275 free((char*)l->dir);
277 if (l->dirfd != -1)
278 close(l->dirfd);
280 free(l);
283 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
284 TAILQ_REMOVE(&h->env, e, envs);
286 free(e->name);
287 free(e->value);
288 free(e);
291 TAILQ_FOREACH_SAFE(e, &h->params, envs, te) {
292 TAILQ_REMOVE(&h->params, e, envs);
294 free(e->name);
295 free(e->value);
296 free(e);
299 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
300 TAILQ_REMOVE(&h->aliases, a, aliases);
302 free(a->alias);
303 free(a);
306 free((char*)h->domain);
307 free((char*)h->cert);
308 free((char*)h->key);
309 free((char*)h->cgi);
310 free((char*)h->entrypoint);
312 TAILQ_REMOVE(&hosts, h, vhosts);
313 free(h);
316 for (i = 0; i < FCGI_MAX; ++i) {
317 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
318 break;
319 free(fcgi[i].path);
320 free(fcgi[i].port);
321 free(fcgi[i].prog);
324 tls_free(ctx);
325 tls_config_free(tlsconf);
328 static int
329 wait_signal(void)
331 sigset_t mask;
332 int signo;
334 sigemptyset(&mask);
335 sigaddset(&mask, SIGHUP);
336 sigaddset(&mask, SIGINT);
337 sigaddset(&mask, SIGTERM);
338 sigwait(&mask, &signo);
340 return signo == SIGHUP;
343 void
344 drop_priv(void)
346 struct passwd *pw = NULL;
348 if (conf.chroot != NULL && conf.user == NULL)
349 fatal("can't chroot without an user to switch to after.");
351 if (conf.user != NULL) {
352 if ((pw = getpwnam(conf.user)) == NULL)
353 fatal("can't find user %s", conf.user);
356 if (conf.chroot != NULL) {
357 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
358 fatal("%s: %s", conf.chroot, strerror(errno));
361 if (pw != NULL) {
362 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
363 fatal("setresuid(%d): %s", pw->pw_uid,
364 strerror(errno));
367 if (getuid() == 0)
368 log_warn(NULL, "not a good idea to run a network daemon as root");
371 static void
372 usage(const char *me)
374 fprintf(stderr,
375 "USAGE: %s [-fn] [-c config] [-P pidfile] | [-6h] [-d certs-dir] [-H host]\n"
376 " [-p port] [-x cgi] [dir]\n",
377 me);
380 static void
381 logger_init(void)
383 int p[2];
385 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
386 err(1, "socketpair");
388 switch (fork()) {
389 case -1:
390 err(1, "fork");
391 case 0:
392 signal(SIGHUP, SIG_IGN);
393 close(p[0]);
394 setproctitle("logger");
395 imsg_init(&logibuf, p[1]);
396 drop_priv();
397 _exit(logger_main(p[1], &logibuf));
398 default:
399 close(p[1]);
400 imsg_init(&logibuf, p[0]);
401 return;
405 static int
406 serve(int argc, char **argv, struct imsgbuf *ibuf)
408 char path[PATH_MAX];
409 int i, p[2];
410 struct vhost *h;
411 struct location *l;
413 if (config_path == NULL) {
414 if (hostname == NULL)
415 hostname = "localhost";
416 if (certs_dir == NULL)
417 certs_dir = data_dir();
418 load_local_cert(hostname, certs_dir);
420 h = TAILQ_FIRST(&hosts);
421 h->domain = "*";
423 l = TAILQ_FIRST(&h->locations);
424 l->auto_index = 1;
425 l->match = "*";
427 switch (argc) {
428 case 0:
429 l->dir = getcwd(path, sizeof(path));
430 break;
431 case 1:
432 l->dir = absolutify_path(argv[0]);
433 break;
434 default:
435 usage(getprogname());
436 return 1;
439 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
442 /* setup tls before dropping privileges: we don't want user
443 * to put private certs inside the chroot. */
444 setup_tls();
446 for (i = 0; i < conf.prefork; ++i) {
447 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
448 PF_UNSPEC, p) == -1)
449 fatal("socketpair: %s", strerror(errno));
451 switch (fork()) {
452 case -1:
453 fatal("fork: %s", strerror(errno));
454 case 0: /* child */
455 close(p[0]);
456 imsg_init(&exibuf, p[1]);
457 setproctitle("server");
458 _exit(listener_main(&exibuf));
459 default:
460 close(p[1]);
461 imsg_init(&servibuf[i], p[0]);
465 setproctitle("executor");
466 drop_priv();
467 _exit(executor_main(ibuf));
470 static int
471 write_pidfile(const char *pidfile)
473 struct flock lock;
474 int fd;
476 if (pidfile == NULL)
477 return -1;
479 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
480 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
482 lock.l_start = 0;
483 lock.l_len = 0;
484 lock.l_type = F_WRLCK;
485 lock.l_whence = SEEK_SET;
487 if (fcntl(fd, F_SETLK, &lock) == -1)
488 fatal("can't lock %s, gmid is already running?", pidfile);
490 if (ftruncate(fd, 0) == -1)
491 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
493 dprintf(fd, "%d\n", getpid());
495 return fd;
498 static void
499 setup_configless(int argc, char **argv, const char *cgi)
501 struct vhost *host;
502 struct location *loc;
504 host = xcalloc(1, sizeof(*host));
505 host->cgi = cgi;
506 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
508 loc = xcalloc(1, sizeof(*loc));
509 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
511 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, 2, NULL, 0);
512 imsg_flush(&logibuf);
514 serve(argc, argv, NULL);
516 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
517 imsg_flush(&logibuf);
520 int
521 main(int argc, char **argv)
523 struct imsgbuf exibuf;
524 int ch, conftest = 0, configless = 0;
525 int pidfd, old_ipv6, old_port;
527 init_config();
529 while ((ch = getopt(argc, argv, "6c:d:fH:hnP:p:vx:")) != -1) {
530 switch (ch) {
531 case '6':
532 conf.ipv6 = 1;
533 configless = 1;
534 break;
536 case 'c':
537 config_path = absolutify_path(optarg);
538 break;
540 case 'd':
541 certs_dir = optarg;
542 configless = 1;
543 break;
545 case 'f':
546 conf.foreground = 1;
547 break;
549 case 'H':
550 hostname = optarg;
551 configless = 1;
552 break;
554 case 'h':
555 usage(*argv);
556 return 0;
558 case 'n':
559 conftest = 1;
560 break;
562 case 'P':
563 pidfile = optarg;
564 break;
566 case 'p':
567 conf.port = parse_portno(optarg);
568 configless = 1;
569 break;
571 case 'v':
572 conf.verbose++;
573 break;
575 case 'x':
576 /* drop the starting / (if any) */
577 if (*optarg == '/')
578 optarg++;
579 cgi = optarg;
580 configless = 1;
581 break;
583 default:
584 usage(*argv);
585 return 1;
588 argc -= optind;
589 argv += optind;
591 if (config_path == NULL) {
592 configless = 1;
593 conf.foreground = 1;
594 conf.prefork = 1;
595 conf.verbose++;
598 if (config_path != NULL && (argc > 0 || configless))
599 errx(1, "can't specify options in config mode.");
601 if (conftest) {
602 parse_conf(config_path);
603 puts("config OK");
604 return 0;
607 if (!conf.foreground && !configless) {
608 if (daemon(1, 1) == -1)
609 err(1, "daemon");
612 if (config_path != NULL)
613 parse_conf(config_path);
615 logger_init();
617 sock4 = make_socket(conf.port, AF_INET);
618 sock6 = -1;
619 if (conf.ipv6)
620 sock6 = make_socket(conf.port, AF_INET6);
622 signal(SIGPIPE, SIG_IGN);
623 signal(SIGCHLD, SIG_IGN);
625 if (configless) {
626 setup_configless(argc, argv, cgi);
627 return 0;
630 if (conf.foreground) {
631 imsg_compose(&logibuf, IMSG_LOG_TYPE, 0, 0, 2, NULL, 0);
632 imsg_flush(&logibuf);
635 pidfd = write_pidfile(pidfile);
637 /* Linux seems to call the event handlers even when we're
638 * doing a sigwait. These dummy handlers are here to avoid
639 * being terminated on SIGHUP, SIGINT or SIGTERM. */
640 signal(SIGHUP, dummy_handler);
641 signal(SIGINT, dummy_handler);
642 signal(SIGTERM, dummy_handler);
644 /* wait a sighup and reload the daemon */
645 for (;;) {
646 int p[2];
648 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
649 PF_UNSPEC, p) == -1)
650 fatal("socketpair: %s", strerror(errno));
652 switch (fork()) {
653 case -1:
654 fatal("fork: %s", strerror(errno));
655 case 0:
656 close(p[0]);
657 imsg_init(&exibuf, p[1]);
658 _exit(serve(argc, argv, &exibuf));
661 close(p[1]);
662 imsg_init(&exibuf, p[0]);
664 if (!wait_signal())
665 break;
667 log_info(NULL, "reloading configuration %s", config_path);
669 /* close the executor (it'll close the servers too) */
670 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
671 imsg_flush(&exibuf);
672 close(p[0]);
674 old_ipv6 = conf.ipv6;
675 old_port = conf.port;
677 free_config();
678 init_config();
679 parse_conf(config_path);
681 if (old_port != conf.port) {
682 close(sock4);
683 close(sock6);
684 sock4 = -1;
685 sock6 = -1;
688 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
689 close(sock6);
690 sock6 = -1;
693 if (sock4 == -1)
694 sock4 = make_socket(conf.port, AF_INET);
695 if (sock6 == -1 && conf.ipv6)
696 sock6 = make_socket(conf.port, AF_INET6);
699 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
700 imsg_flush(&exibuf);
702 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
703 imsg_flush(&logibuf);
705 if (pidfd != -1)
706 close(pidfd);
708 return 0;