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 <limits.h>
24 #include <pwd.h>
25 #include <signal.h>
26 #include <string.h>
28 struct vhost hosts[HOSTSLEN];
30 int sock4, sock6;
32 struct imsgbuf logibuf, exibuf, servibuf[PROC_MAX];
34 const char *config_path, *certs_dir, *hostname;
36 struct conf conf;
38 struct tls_config *tlsconf;
39 struct tls *ctx;
41 static void
42 dummy_handler(int signo)
43 {
44 return;
45 }
47 /* XXX: create recursively */
48 void
49 mkdirs(const char *path)
50 {
51 if (mkdir(path, 0755) == -1 && errno != EEXIST)
52 fatal("can't mkdir %s: %s", path, strerror(errno));
53 }
55 /* $XDG_DATA_HOME/gmid */
56 char *
57 data_dir(void)
58 {
59 const char *home, *xdg;
60 char *t;
62 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
63 if ((home = getenv("HOME")) == NULL)
64 errx(1, "XDG_DATA_HOME and HOME both empty");
65 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
66 err(1, "asprintf");
67 mkdirs(t);
68 return t;
69 }
71 if (asprintf(&t, "%s/gmid", xdg) == -1)
72 err(1, "asprintf");
73 mkdirs(t);
74 return t;
75 }
77 void
78 load_local_cert(const char *hostname, const char *dir)
79 {
80 char *cert, *key;
82 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
83 errx(1, "asprintf");
84 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
85 errx(1, "asprintf");
87 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
88 gen_certificate(hostname, cert, key);
90 hosts[0].cert = cert;
91 hosts[0].key = key;
92 hosts[0].domain = hostname;
93 }
95 void
96 load_vhosts(void)
97 {
98 struct vhost *h;
100 for (h = hosts; h->domain != NULL; ++h) {
101 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
102 fatal("open %s for domain %s", h->dir, h->domain);
106 int
107 make_socket(int port, int family)
109 int sock, v;
110 struct sockaddr_in addr4;
111 struct sockaddr_in6 addr6;
112 struct sockaddr *addr;
113 socklen_t len;
115 switch (family) {
116 case AF_INET:
117 bzero(&addr4, sizeof(addr4));
118 addr4.sin_family = family;
119 addr4.sin_port = htons(port);
120 addr4.sin_addr.s_addr = INADDR_ANY;
121 addr = (struct sockaddr*)&addr4;
122 len = sizeof(addr4);
123 break;
125 case AF_INET6:
126 bzero(&addr6, sizeof(addr6));
127 addr6.sin6_family = AF_INET6;
128 addr6.sin6_port = htons(port);
129 addr6.sin6_addr = in6addr_any;
130 addr = (struct sockaddr*)&addr6;
131 len = sizeof(addr6);
132 break;
134 default:
135 /* unreachable */
136 abort();
139 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
140 fatal("socket: %s", strerror(errno));
142 v = 1;
143 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
144 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
146 v = 1;
147 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
148 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
150 mark_nonblock(sock);
152 if (bind(sock, addr, len) == -1)
153 fatal("bind: %s", strerror(errno));
155 if (listen(sock, 16) == -1)
156 fatal("listen: %s", strerror(errno));
158 return sock;
161 void
162 setup_tls(void)
164 struct vhost *h;
166 if ((tlsconf = tls_config_new()) == NULL)
167 fatal("tls_config_new");
169 /* optionally accept client certs, but don't try to verify them */
170 tls_config_verify_client_optional(tlsconf);
171 tls_config_insecure_noverifycert(tlsconf);
173 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
174 fatal("tls_config_set_protocols");
176 if ((ctx = tls_server()) == NULL)
177 fatal("tls_server failure");
179 /* we need to set something, then we can add how many key we want */
180 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
181 fatal("tls_config_set_keypair_file failed for (%s, %s)",
182 hosts->cert, hosts->key);
184 for (h = &hosts[1]; h->domain != NULL; ++h) {
185 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
186 fatal("failed to load the keypair (%s, %s)",
187 h->cert, h->key);
190 if (tls_configure(ctx, tlsconf) == -1)
191 fatal("tls_configure: %s", tls_error(ctx));
194 static int
195 listener_main(struct imsgbuf *ibuf)
197 drop_priv();
198 load_default_mime(&conf.mime);
199 load_vhosts();
200 loop(ctx, sock4, sock6, ibuf);
201 return 0;
204 void
205 init_config(void)
207 size_t i;
209 bzero(hosts, sizeof(hosts));
210 for (i = 0; i < HOSTSLEN; ++i)
211 hosts[i].dirfd = -1;
213 conf.port = 1965;
214 conf.ipv6 = 0;
215 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
217 init_mime(&conf.mime);
219 conf.chroot = NULL;
220 conf.user = NULL;
222 /* we'll change this to 0 when running without config. */
223 conf.prefork = 3;
226 void
227 free_config(void)
229 struct vhost *h;
230 struct location *l;
232 free(conf.chroot);
233 free(conf.user);
234 memset(&conf, 0, sizeof(conf));
236 for (h = hosts; h->domain != NULL; ++h) {
237 free((char*)h->domain);
238 free((char*)h->cert);
239 free((char*)h->key);
240 free((char*)h->dir);
241 free((char*)h->cgi);
242 free((char*)h->entrypoint);
244 for (l = h->locations; l->match != NULL; ++l) {
245 free((char*)l->match);
246 free((char*)l->lang);
247 free((char*)l->default_mime);
248 free((char*)l->index);
249 free((char*)l->block_fmt);
252 memset(hosts, 0, sizeof(hosts));
254 tls_free(ctx);
255 tls_config_free(tlsconf);
258 static int
259 wait_signal(void)
261 sigset_t mask;
262 int signo;
264 sigemptyset(&mask);
265 sigaddset(&mask, SIGHUP);
266 sigaddset(&mask, SIGINT);
267 sigaddset(&mask, SIGTERM);
268 sigwait(&mask, &signo);
270 return signo == SIGHUP;
273 void
274 drop_priv(void)
276 struct passwd *pw = NULL;
278 if (conf.chroot != NULL && conf.user == NULL)
279 fatal("can't chroot without an user to switch to after.");
281 if (conf.user != NULL) {
282 if ((pw = getpwnam(conf.user)) == NULL)
283 fatal("can't find user %s", conf.user);
286 if (conf.chroot != NULL) {
287 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
288 fatal("%s: %s", conf.chroot, strerror(errno));
291 if (pw != NULL) {
292 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
293 fatal("setresuid(%d): %s", pw->pw_uid,
294 strerror(errno));
297 if (getuid() == 0)
298 log_warn(NULL, "not a good idea to run a network daemon as root");
301 static void
302 usage(const char *me)
304 fprintf(stderr,
305 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]\n"
306 " [-p port] [-x cgi] [dir]\n",
307 me);
310 static void
311 logger_init(void)
313 int p[2];
315 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
316 err(1, "socketpair");
318 switch (fork()) {
319 case -1:
320 err(1, "fork");
321 case 0:
322 signal(SIGHUP, SIG_IGN);
323 close(p[0]);
324 setproctitle("logger");
325 imsg_init(&logibuf, p[1]);
326 drop_priv();
327 _exit(logger_main(p[1], &logibuf));
328 default:
329 close(p[1]);
330 imsg_init(&logibuf, p[0]);
331 return;
335 static int
336 serve(int argc, char **argv, struct imsgbuf *ibuf)
338 char path[PATH_MAX];
339 int i, p[2];
341 if (config_path == NULL) {
342 if (hostname == NULL)
343 hostname = "localhost";
344 if (certs_dir == NULL)
345 certs_dir = data_dir();
346 load_local_cert(hostname, certs_dir);
348 hosts[0].domain = "*";
349 hosts[0].locations[0].auto_index = 1;
350 hosts[0].locations[0].match = "*";
352 switch (argc) {
353 case 0:
354 hosts[0].dir = getcwd(path, sizeof(path));
355 break;
356 case 1:
357 hosts[0].dir = absolutify_path(argv[0]);
358 break;
359 default:
360 usage(getprogname());
361 return 1;
364 log_notice(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
367 /* setup tls before dropping privileges: we don't want user
368 * to put private certs inside the chroot. */
369 setup_tls();
371 for (i = 0; i < conf.prefork; ++i) {
372 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
373 PF_UNSPEC, p) == -1)
374 fatal("socketpair: %s", strerror(errno));
376 switch (fork()) {
377 case -1:
378 fatal("fork: %s", strerror(errno));
379 case 0: /* child */
380 close(p[0]);
381 imsg_init(&exibuf, p[1]);
382 setproctitle("server");
383 _exit(listener_main(&exibuf));
384 default:
385 close(p[1]);
386 imsg_init(&servibuf[i], p[0]);
390 setproctitle("executor");
391 drop_priv();
392 _exit(executor_main(ibuf));
395 int
396 main(int argc, char **argv)
398 struct imsgbuf exibuf;
399 int ch, conftest = 0, configless = 0;
400 int old_ipv6, old_port;
402 init_config();
404 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
405 switch (ch) {
406 case '6':
407 conf.ipv6 = 1;
408 configless = 1;
409 break;
411 case 'c':
412 config_path = absolutify_path(optarg);
413 break;
415 case 'd':
416 certs_dir = optarg;
417 configless = 1;
418 break;
420 case 'f':
421 conf.foreground = 1;
422 break;
424 case 'H':
425 hostname = optarg;
426 configless = 1;
427 break;
429 case 'h':
430 usage(*argv);
431 return 0;
433 case 'n':
434 conftest = 1;
435 break;
437 case 'p':
438 conf.port = parse_portno(optarg);
439 configless = 1;
440 break;
442 case 'v':
443 conf.verbose++;
444 break;
446 case 'x':
447 /* drop the starting / (if any) */
448 if (*optarg == '/')
449 optarg++;
450 hosts[0].cgi = optarg;
451 configless = 1;
452 break;
454 default:
455 usage(*argv);
456 return 1;
459 argc -= optind;
460 argv += optind;
462 if (config_path == NULL) {
463 configless = 1;
464 conf.foreground = 1;
465 conf.prefork = 1;
466 conf.verbose++;
469 if (config_path != NULL && (argc > 0 || configless))
470 err(1, "can't specify options in config mode.");
472 if (conftest) {
473 parse_conf(config_path);
474 puts("config OK");
475 return 0;
478 signal(SIGPIPE, SIG_IGN);
479 signal(SIGCHLD, SIG_IGN);
481 if (!conf.foreground && !configless) {
482 if (daemon(1, 1) == -1)
483 err(1, "daemon");
486 if (config_path != NULL)
487 parse_conf(config_path);
489 logger_init();
491 sock4 = make_socket(conf.port, AF_INET);
492 sock6 = -1;
493 if (conf.ipv6)
494 sock6 = make_socket(conf.port, AF_INET6);
496 if (configless) {
497 serve(argc, argv, NULL);
498 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
499 imsg_flush(&logibuf);
500 return 0;
504 /* Linux seems to call the event handlers even when we're
505 * doing a sigwait. These dummy handlers is here to avoid
506 * being terminated on SIGHUP, SIGTERM or SIGINFO. */
507 signal(SIGHUP, dummy_handler);
508 signal(SIGINT, dummy_handler);
509 signal(SIGTERM, dummy_handler);
511 /* wait a sighup and reload the daemon */
512 for (;;) {
513 int p[2];
515 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
516 PF_UNSPEC, p) == -1)
517 fatal("socketpair: %s", strerror(errno));
519 switch (fork()) {
520 case -1:
521 fatal("fork: %s", strerror(errno));
522 case 0:
523 close(p[0]);
524 imsg_init(&exibuf, p[1]);
525 _exit(serve(argc, argv, &exibuf));
528 close(p[1]);
529 imsg_init(&exibuf, p[0]);
531 if (!wait_signal())
532 break;
534 log_info(NULL, "reloading configuration %s", config_path);
536 /* close the executor (it'll close the servers too) */
537 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
538 imsg_flush(&exibuf);
539 close(p[0]);
541 old_ipv6 = conf.ipv6;
542 old_port = conf.port;
544 free_config();
545 init_config();
546 parse_conf(config_path);
548 if (old_port != conf.port) {
549 close(sock4);
550 close(sock6);
551 sock4 = -1;
552 sock6 = -1;
555 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
556 close(sock6);
557 sock6 = -1;
560 if (sock4 == -1)
561 sock4 = make_socket(conf.port, AF_INET);
562 if (sock6 == -1 && conf.ipv6)
563 sock6 = make_socket(conf.port, AF_INET6);
566 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
567 imsg_flush(&exibuf);
569 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
570 imsg_flush(&logibuf);
572 return 0;