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 vhosthead hosts;
31 int sock4, sock6;
33 struct imsgbuf logibuf, exibuf, servibuf[PROC_MAX];
35 const char *config_path, *certs_dir, *hostname;
37 struct conf conf;
39 struct tls_config *tlsconf;
40 struct tls *ctx;
42 static void
43 dummy_handler(int signo)
44 {
45 return;
46 }
48 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
49 static void
50 pdirname(const char *path, char *dn)
51 {
52 char p[PATH_MAX+1];
53 char *t;
55 strlcpy(p, path, sizeof(p));
56 t = dirname(p);
57 memmove(dn, t, strlen(t)+1);
58 }
60 static void
61 mkdirs(const char *path, mode_t mode)
62 {
63 char dname[PATH_MAX+1];
65 pdirname(path, dname);
66 if (!strcmp(dname, "/"))
67 return;
68 mkdirs(dname, mode);
69 if (mkdir(path, mode) != 0 && errno != EEXIST)
70 fatal("can't mkdir %s: %s", path, strerror(errno));
71 }
73 /* $XDG_DATA_HOME/gmid */
74 char *
75 data_dir(void)
76 {
77 const char *home, *xdg;
78 char *t;
80 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
81 if ((home = getenv("HOME")) == NULL)
82 errx(1, "XDG_DATA_HOME and HOME both empty");
83 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
84 err(1, "asprintf");
85 } else {
86 if (asprintf(&t, "%s/gmid", xdg) == -1)
87 err(1, "asprintf");
88 }
90 mkdirs(t, 0755);
91 return t;
92 }
94 void
95 load_local_cert(const char *hostname, const char *dir)
96 {
97 char *cert, *key;
98 struct vhost *h;
100 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
101 errx(1, "asprintf");
102 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
103 errx(1, "asprintf");
105 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
106 gen_certificate(hostname, cert, key);
108 h = TAILQ_FIRST(&hosts);
109 h->cert = cert;
110 h->key = key;
111 h->domain = hostname;
114 void
115 load_vhosts(void)
117 struct vhost *h;
118 struct location *l;
120 TAILQ_FOREACH(h, &hosts, vhosts) {
121 TAILQ_FOREACH(l, &h->locations, locations) {
122 if (l->dir == NULL)
123 continue;
124 if ((l->dirfd = open(l->dir, O_RDONLY | O_DIRECTORY)) == -1)
125 fatal("open %s for domain %s", l->dir, h->domain);
130 int
131 make_socket(int port, int family)
133 int sock, v;
134 struct sockaddr_in addr4;
135 struct sockaddr_in6 addr6;
136 struct sockaddr *addr;
137 socklen_t len;
139 switch (family) {
140 case AF_INET:
141 bzero(&addr4, sizeof(addr4));
142 addr4.sin_family = family;
143 addr4.sin_port = htons(port);
144 addr4.sin_addr.s_addr = INADDR_ANY;
145 addr = (struct sockaddr*)&addr4;
146 len = sizeof(addr4);
147 break;
149 case AF_INET6:
150 bzero(&addr6, sizeof(addr6));
151 addr6.sin6_family = AF_INET6;
152 addr6.sin6_port = htons(port);
153 addr6.sin6_addr = in6addr_any;
154 addr = (struct sockaddr*)&addr6;
155 len = sizeof(addr6);
156 break;
158 default:
159 /* unreachable */
160 abort();
163 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
164 fatal("socket: %s", strerror(errno));
166 v = 1;
167 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
168 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
170 v = 1;
171 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
172 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
174 mark_nonblock(sock);
176 if (bind(sock, addr, len) == -1)
177 fatal("bind: %s", strerror(errno));
179 if (listen(sock, 16) == -1)
180 fatal("listen: %s", strerror(errno));
182 return sock;
185 void
186 setup_tls(void)
188 struct vhost *h;
190 if ((tlsconf = tls_config_new()) == NULL)
191 fatal("tls_config_new");
193 /* optionally accept client certs, but don't try to verify them */
194 tls_config_verify_client_optional(tlsconf);
195 tls_config_insecure_noverifycert(tlsconf);
197 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
198 fatal("tls_config_set_protocols");
200 if ((ctx = tls_server()) == NULL)
201 fatal("tls_server failure");
203 h = TAILQ_FIRST(&hosts);
205 /* we need to set something, then we can add how many key we want */
206 if (tls_config_set_keypair_file(tlsconf, h->cert, h->key))
207 fatal("tls_config_set_keypair_file failed for (%s, %s)",
208 h->cert, h->key);
210 while ((h = TAILQ_NEXT(h, vhosts)) != NULL) {
211 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
212 fatal("failed to load the keypair (%s, %s)",
213 h->cert, h->key);
216 if (tls_configure(ctx, tlsconf) == -1)
217 fatal("tls_configure: %s", tls_error(ctx));
220 static int
221 listener_main(struct imsgbuf *ibuf)
223 drop_priv();
224 load_default_mime(&conf.mime);
225 load_vhosts();
226 loop(ctx, sock4, sock6, ibuf);
227 return 0;
230 void
231 init_config(void)
233 TAILQ_INIT(&hosts);
235 conf.port = 1965;
236 conf.ipv6 = 0;
237 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
239 init_mime(&conf.mime);
241 conf.chroot = NULL;
242 conf.user = NULL;
244 conf.prefork = 3;
247 void
248 free_config(void)
250 struct vhost *h, *th;
251 struct location *l, *tl;
252 struct envlist *e, *te;
253 struct alist *a, *ta;
254 int v;
256 v = conf.verbose;
258 free(conf.chroot);
259 free(conf.user);
260 memset(&conf, 0, sizeof(conf));
262 conf.verbose = v;
264 TAILQ_FOREACH_SAFE(h, &hosts, vhosts, th) {
265 TAILQ_FOREACH_SAFE(l, &h->locations, locations, tl) {
266 TAILQ_REMOVE(&h->locations, l, locations);
268 free((char*)l->match);
269 free((char*)l->lang);
270 free((char*)l->default_mime);
271 free((char*)l->index);
272 free((char*)l->block_fmt);
273 free((char*)l->dir);
275 if (l->dirfd != -1)
276 close(l->dirfd);
278 free(l);
281 TAILQ_FOREACH_SAFE(e, &h->env, envs, te) {
282 free(e->name);
283 free(e->value);
284 free(e);
287 TAILQ_FOREACH_SAFE(a, &h->aliases, aliases, ta) {
288 free(a->alias);
289 free(a);
292 free((char*)h->domain);
293 free((char*)h->cert);
294 free((char*)h->key);
295 free((char*)h->cgi);
296 free((char*)h->entrypoint);
298 TAILQ_REMOVE(&hosts, h, vhosts);
299 free(h);
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 != NULL && conf.user == NULL)
327 fatal("can't chroot without an user to switch to after.");
329 if (conf.user != NULL) {
330 if ((pw = getpwnam(conf.user)) == NULL)
331 fatal("can't find user %s", conf.user);
334 if (conf.chroot != NULL) {
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(const char *me)
352 fprintf(stderr,
353 "USAGE: %s [-fn] [-c config] [-P pidfile] | [-6h] [-d certs-dir] [-H host]\n"
354 " [-p port] [-x cgi] [dir]\n",
355 me);
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 int
384 serve(int argc, char **argv, struct imsgbuf *ibuf)
386 char path[PATH_MAX];
387 int i, p[2];
388 struct vhost *h;
389 struct location *l;
391 if (config_path == NULL) {
392 if (hostname == NULL)
393 hostname = "localhost";
394 if (certs_dir == NULL)
395 certs_dir = data_dir();
396 load_local_cert(hostname, certs_dir);
398 h = TAILQ_FIRST(&hosts);
399 h->domain = "*";
401 l = TAILQ_FIRST(&h->locations);
402 l->auto_index = 1;
403 l->match = "*";
405 switch (argc) {
406 case 0:
407 l->dir = getcwd(path, sizeof(path));
408 break;
409 case 1:
410 l->dir = absolutify_path(argv[0]);
411 break;
412 default:
413 usage(getprogname());
414 return 1;
417 log_notice(NULL, "serving %s on port %d", l->dir, conf.port);
420 /* setup tls before dropping privileges: we don't want user
421 * to put private certs inside the chroot. */
422 setup_tls();
424 for (i = 0; i < conf.prefork; ++i) {
425 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
426 PF_UNSPEC, p) == -1)
427 fatal("socketpair: %s", strerror(errno));
429 switch (fork()) {
430 case -1:
431 fatal("fork: %s", strerror(errno));
432 case 0: /* child */
433 close(p[0]);
434 imsg_init(&exibuf, p[1]);
435 setproctitle("server");
436 _exit(listener_main(&exibuf));
437 default:
438 close(p[1]);
439 imsg_init(&servibuf[i], p[0]);
443 setproctitle("executor");
444 drop_priv();
445 _exit(executor_main(ibuf));
448 static int
449 write_pidfile(const char *pidfile)
451 struct flock lock;
452 int fd;
454 if (pidfile == NULL)
455 return -1;
457 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
458 fatal("can't open pidfile %s: %s", pidfile, strerror(errno));
460 lock.l_start = 0;
461 lock.l_len = 0;
462 lock.l_type = F_WRLCK;
463 lock.l_whence = SEEK_SET;
465 if (fcntl(fd, F_SETLK, &lock) == -1)
466 fatal("can't lock %s, gmid is already running?", pidfile);
468 if (ftruncate(fd, 0) == -1)
469 fatal("ftruncate: %s: %s", pidfile, strerror(errno));
471 dprintf(fd, "%d\n", getpid());
473 return fd;
476 static void
477 setup_configless(int argc, char **argv, const char *cgi)
479 struct vhost *host;
480 struct location *loc;
482 host = xcalloc(1, sizeof(*host));
483 host->cgi = cgi;
484 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
486 loc = xcalloc(1, sizeof(*loc));
487 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
489 serve(argc, argv, NULL);
490 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
491 imsg_flush(&logibuf);
494 int
495 main(int argc, char **argv)
497 struct imsgbuf exibuf;
498 int ch, conftest = 0, configless = 0;
499 int pidfd, old_ipv6, old_port;
500 const char *pidfile = NULL, *cgi = NULL;
502 init_config();
504 while ((ch = getopt(argc, argv, "6c:d:fH:hnP:p:vx:")) != -1) {
505 switch (ch) {
506 case '6':
507 conf.ipv6 = 1;
508 configless = 1;
509 break;
511 case 'c':
512 config_path = absolutify_path(optarg);
513 break;
515 case 'd':
516 certs_dir = optarg;
517 configless = 1;
518 break;
520 case 'f':
521 conf.foreground = 1;
522 break;
524 case 'H':
525 hostname = optarg;
526 configless = 1;
527 break;
529 case 'h':
530 usage(*argv);
531 return 0;
533 case 'n':
534 conftest = 1;
535 break;
537 case 'P':
538 pidfile = optarg;
539 break;
541 case 'p':
542 conf.port = parse_portno(optarg);
543 configless = 1;
544 break;
546 case 'v':
547 conf.verbose++;
548 break;
550 case 'x':
551 /* drop the starting / (if any) */
552 if (*optarg == '/')
553 optarg++;
554 cgi = optarg;
555 configless = 1;
556 break;
558 default:
559 usage(*argv);
560 return 1;
563 argc -= optind;
564 argv += optind;
566 if (config_path == NULL) {
567 configless = 1;
568 conf.foreground = 1;
569 conf.prefork = 1;
570 conf.verbose++;
573 if (config_path != NULL && (argc > 0 || configless))
574 errx(1, "can't specify options in config mode.");
576 if (conftest) {
577 parse_conf(config_path);
578 puts("config OK");
579 return 0;
582 if (!conf.foreground && !configless) {
583 if (daemon(1, 1) == -1)
584 err(1, "daemon");
587 if (config_path != NULL)
588 parse_conf(config_path);
590 logger_init();
592 sock4 = make_socket(conf.port, AF_INET);
593 sock6 = -1;
594 if (conf.ipv6)
595 sock6 = make_socket(conf.port, AF_INET6);
597 signal(SIGPIPE, SIG_IGN);
598 signal(SIGCHLD, SIG_IGN);
600 if (configless) {
601 setup_configless(argc, argv, cgi);
602 return 0;
605 pidfd = write_pidfile(pidfile);
607 /* Linux seems to call the event handlers even when we're
608 * doing a sigwait. These dummy handlers are here to avoid
609 * being terminated on SIGHUP, SIGINT or SIGTERM. */
610 signal(SIGHUP, dummy_handler);
611 signal(SIGINT, dummy_handler);
612 signal(SIGTERM, dummy_handler);
614 /* wait a sighup and reload the daemon */
615 for (;;) {
616 int p[2];
618 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
619 PF_UNSPEC, p) == -1)
620 fatal("socketpair: %s", strerror(errno));
622 switch (fork()) {
623 case -1:
624 fatal("fork: %s", strerror(errno));
625 case 0:
626 close(p[0]);
627 imsg_init(&exibuf, p[1]);
628 _exit(serve(argc, argv, &exibuf));
631 close(p[1]);
632 imsg_init(&exibuf, p[0]);
634 if (!wait_signal())
635 break;
637 log_info(NULL, "reloading configuration %s", config_path);
639 /* close the executor (it'll close the servers too) */
640 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
641 imsg_flush(&exibuf);
642 close(p[0]);
644 old_ipv6 = conf.ipv6;
645 old_port = conf.port;
647 free_config();
648 init_config();
649 parse_conf(config_path);
651 if (old_port != conf.port) {
652 close(sock4);
653 close(sock6);
654 sock4 = -1;
655 sock6 = -1;
658 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
659 close(sock6);
660 sock6 = -1;
663 if (sock4 == -1)
664 sock4 = make_socket(conf.port, AF_INET);
665 if (sock6 == -1 && conf.ipv6)
666 sock6 = make_socket(conf.port, AF_INET6);
669 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
670 imsg_flush(&exibuf);
672 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
673 imsg_flush(&logibuf);
675 if (pidfd != -1)
676 close(pidfd);
678 return 0;