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 /* XXX: create recursively */
42 void
43 mkdirs(const char *path)
44 {
45 if (mkdir(path, 0755) == -1 && errno != EEXIST)
46 fatal("can't mkdir %s: %s", path, strerror(errno));
47 }
49 /* $XDG_DATA_HOME/gmid */
50 char *
51 data_dir(void)
52 {
53 const char *home, *xdg;
54 char *t;
56 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
57 if ((home = getenv("HOME")) == NULL)
58 errx(1, "XDG_DATA_HOME and HOME both empty");
59 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
60 err(1, "asprintf");
61 mkdirs(t);
62 return t;
63 }
65 if (asprintf(&t, "%s/gmid", xdg) == -1)
66 err(1, "asprintf");
67 mkdirs(t);
68 return t;
69 }
71 void
72 load_local_cert(const char *hostname, const char *dir)
73 {
74 char *cert, *key;
76 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
77 errx(1, "asprintf");
78 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
79 errx(1, "asprintf");
81 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
82 gen_certificate(hostname, cert, key);
84 hosts[0].cert = cert;
85 hosts[0].key = key;
86 hosts[0].domain = hostname;
87 }
89 void
90 load_vhosts(void)
91 {
92 struct vhost *h;
94 for (h = hosts; h->domain != NULL; ++h) {
95 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
96 fatal("open %s for domain %s", h->dir, h->domain);
97 }
98 }
100 int
101 make_socket(int port, int family)
103 int sock, v;
104 struct sockaddr_in addr4;
105 struct sockaddr_in6 addr6;
106 struct sockaddr *addr;
107 socklen_t len;
109 switch (family) {
110 case AF_INET:
111 bzero(&addr4, sizeof(addr4));
112 addr4.sin_family = family;
113 addr4.sin_port = htons(port);
114 addr4.sin_addr.s_addr = INADDR_ANY;
115 addr = (struct sockaddr*)&addr4;
116 len = sizeof(addr4);
117 break;
119 case AF_INET6:
120 bzero(&addr6, sizeof(addr6));
121 addr6.sin6_family = AF_INET6;
122 addr6.sin6_port = htons(port);
123 addr6.sin6_addr = in6addr_any;
124 addr = (struct sockaddr*)&addr6;
125 len = sizeof(addr6);
126 break;
128 default:
129 /* unreachable */
130 abort();
133 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
134 fatal("socket: %s", strerror(errno));
136 v = 1;
137 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
138 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
140 v = 1;
141 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
142 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
144 mark_nonblock(sock);
146 if (bind(sock, addr, len) == -1)
147 fatal("bind: %s", strerror(errno));
149 if (listen(sock, 16) == -1)
150 fatal("listen: %s", strerror(errno));
152 return sock;
155 void
156 setup_tls(void)
158 struct vhost *h;
160 if ((tlsconf = tls_config_new()) == NULL)
161 fatal("tls_config_new");
163 /* optionally accept client certs, but don't try to verify them */
164 tls_config_verify_client_optional(tlsconf);
165 tls_config_insecure_noverifycert(tlsconf);
167 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
168 fatal("tls_config_set_protocols");
170 if ((ctx = tls_server()) == NULL)
171 fatal("tls_server failure");
173 /* we need to set something, then we can add how many key we want */
174 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
175 fatal("tls_config_set_keypair_file failed for (%s, %s)",
176 hosts->cert, hosts->key);
178 for (h = &hosts[1]; h->domain != NULL; ++h) {
179 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
180 fatal("failed to load the keypair (%s, %s)",
181 h->cert, h->key);
184 if (tls_configure(ctx, tlsconf) == -1)
185 fatal("tls_configure: %s", tls_error(ctx));
188 static int
189 listener_main(struct imsgbuf *ibuf)
191 drop_priv();
192 load_default_mime(&conf.mime);
193 load_vhosts();
194 loop(ctx, sock4, sock6, ibuf);
195 return 0;
198 void
199 init_config(void)
201 size_t i;
203 bzero(hosts, sizeof(hosts));
204 for (i = 0; i < HOSTSLEN; ++i)
205 hosts[i].dirfd = -1;
207 conf.port = 1965;
208 conf.ipv6 = 0;
209 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
211 init_mime(&conf.mime);
213 conf.chroot = NULL;
214 conf.user = NULL;
216 /* we'll change this to 0 when running without config. */
217 conf.prefork = 3;
220 void
221 free_config(void)
223 struct vhost *h;
224 struct location *l;
226 free(conf.chroot);
227 free(conf.user);
228 memset(&conf, 0, sizeof(conf));
230 for (h = hosts; h->domain != NULL; ++h) {
231 free((char*)h->domain);
232 free((char*)h->cert);
233 free((char*)h->key);
234 free((char*)h->dir);
235 free((char*)h->cgi);
236 free((char*)h->entrypoint);
238 for (l = h->locations; l->match != NULL; ++l) {
239 free((char*)l->match);
240 free((char*)l->lang);
241 free((char*)l->default_mime);
242 free((char*)l->index);
243 free((char*)l->block_fmt);
246 memset(hosts, 0, sizeof(hosts));
248 tls_free(ctx);
249 tls_config_free(tlsconf);
252 static void
253 wait_sighup(void)
255 sigset_t mask;
256 int signo;
258 sigemptyset(&mask);
259 sigaddset(&mask, SIGHUP);
260 sigwait(&mask, &signo);
263 void
264 drop_priv(void)
266 struct passwd *pw = NULL;
268 if (conf.chroot != NULL && conf.user == NULL)
269 fatal("can't chroot without an user to switch to after.");
271 if (conf.user != NULL) {
272 if ((pw = getpwnam(conf.user)) == NULL)
273 fatal("can't find user %s", conf.user);
276 if (conf.chroot != NULL) {
277 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
278 fatal("%s: %s", conf.chroot, strerror(errno));
281 if (pw != NULL) {
282 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
283 fatal("setresuid(%d): %s", pw->pw_uid,
284 strerror(errno));
287 if (getuid() == 0)
288 log_warn(NULL, "not a good idea to run a network daemon as root");
291 static void
292 usage(const char *me)
294 fprintf(stderr,
295 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]\n"
296 " [-p port] [-x cgi] [dir]\n",
297 me);
300 static void
301 logger_init(void)
303 int p[2];
305 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
306 err(1, "socketpair");
308 switch (fork()) {
309 case -1:
310 err(1, "fork");
311 case 0:
312 signal(SIGHUP, SIG_IGN);
313 close(p[0]);
314 setproctitle("logger");
315 imsg_init(&logibuf, p[1]);
316 drop_priv();
317 _exit(logger_main(p[1], &logibuf));
318 default:
319 close(p[1]);
320 imsg_init(&logibuf, p[0]);
321 return;
325 static int
326 serve(int argc, char **argv, struct imsgbuf *ibuf)
328 char path[PATH_MAX];
329 int i, p[2];
331 if (config_path == NULL) {
332 if (hostname == NULL)
333 hostname = "localhost";
334 if (certs_dir == NULL)
335 certs_dir = data_dir();
336 load_local_cert(hostname, certs_dir);
338 hosts[0].domain = "*";
339 hosts[0].locations[0].auto_index = 1;
340 hosts[0].locations[0].match = "*";
342 switch (argc) {
343 case 0:
344 hosts[0].dir = getcwd(path, sizeof(path));
345 break;
346 case 1:
347 hosts[0].dir = absolutify_path(argv[0]);
348 break;
349 default:
350 usage(getprogname());
351 return 1;
354 log_notice(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
357 /* setup tls before dropping privileges: we don't want user
358 * to put private certs inside the chroot. */
359 setup_tls();
361 for (i = 0; i < conf.prefork; ++i) {
362 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
363 PF_UNSPEC, p) == -1)
364 fatal("socketpair: %s", strerror(errno));
366 switch (fork()) {
367 case -1:
368 fatal("fork: %s", strerror(errno));
369 case 0: /* child */
370 close(p[0]);
371 imsg_init(&exibuf, p[1]);
372 setproctitle("server");
373 _exit(listener_main(&exibuf));
374 default:
375 close(p[1]);
376 imsg_init(&servibuf[i], p[0]);
380 setproctitle("executor");
381 drop_priv();
382 _exit(executor_main(ibuf));
385 int
386 main(int argc, char **argv)
388 int ch, conftest = 0, configless = 0;
389 int old_ipv6, old_port;
391 init_config();
393 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
394 switch (ch) {
395 case '6':
396 conf.ipv6 = 1;
397 configless = 1;
398 break;
400 case 'c':
401 config_path = absolutify_path(optarg);
402 break;
404 case 'd':
405 certs_dir = optarg;
406 configless = 1;
407 break;
409 case 'f':
410 conf.foreground = 1;
411 break;
413 case 'H':
414 hostname = optarg;
415 configless = 1;
416 break;
418 case 'h':
419 usage(*argv);
420 return 0;
422 case 'n':
423 conftest = 1;
424 break;
426 case 'p':
427 conf.port = parse_portno(optarg);
428 configless = 1;
429 break;
431 case 'v':
432 conf.verbose++;
433 break;
435 case 'x':
436 /* drop the starting / (if any) */
437 if (*optarg == '/')
438 optarg++;
439 hosts[0].cgi = optarg;
440 configless = 1;
441 break;
443 default:
444 usage(*argv);
445 return 1;
448 argc -= optind;
449 argv += optind;
451 if (config_path == NULL) {
452 configless = 1;
453 conf.foreground = 1;
454 conf.prefork = 1;
455 conf.verbose++;
458 if (config_path != NULL && (argc > 0 || configless))
459 err(1, "can't specify options in config mode.");
461 if (conftest) {
462 parse_conf(config_path);
463 puts("config OK");
464 return 0;
467 signal(SIGPIPE, SIG_IGN);
468 signal(SIGCHLD, SIG_IGN);
470 if (!conf.foreground && !configless) {
471 if (daemon(1, 1) == -1)
472 err(1, "daemon");
475 if (config_path != NULL)
476 parse_conf(config_path);
478 logger_init();
480 sock4 = make_socket(conf.port, AF_INET);
481 sock6 = -1;
482 if (conf.ipv6)
483 sock6 = make_socket(conf.port, AF_INET6);
485 if (configless) {
486 serve(argc, argv, NULL);
487 imsg_compose(&logibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
488 imsg_flush(&logibuf);
489 return 0;
492 /* wait a sighup and reload the daemon */
493 for (;;) {
494 struct imsgbuf exibuf;
495 int p[2];
497 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
498 PF_UNSPEC, p) == -1)
499 fatal("socketpair: %s", strerror(errno));
501 switch (fork()) {
502 case -1:
503 fatal("fork: %s", strerror(errno));
504 case 0:
505 signal(SIGHUP, SIG_IGN);
506 close(p[0]);
507 imsg_init(&exibuf, p[1]);
508 _exit(serve(argc, argv, &exibuf));
511 close(p[1]);
512 imsg_init(&exibuf, p[0]);
514 wait_sighup();
515 log_info(NULL, "reloading configuration %s", config_path);
517 /* close the executor (it'll close the servers too) */
518 imsg_compose(&exibuf, IMSG_QUIT, 0, 0, -1, NULL, 0);
519 imsg_flush(&exibuf);
520 close(p[0]);
522 old_ipv6 = conf.ipv6;
523 old_port = conf.port;
525 free_config();
526 init_config();
527 parse_conf(config_path);
529 if (old_port != conf.port) {
530 close(sock4);
531 close(sock6);
532 sock4 = -1;
533 sock6 = -1;
536 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
537 close(sock6);
538 sock6 = -1;
541 if (sock4 == -1)
542 sock4 = make_socket(conf.port, AF_INET);
543 if (sock6 == -1 && conf.ipv6)
544 sock6 = make_socket(conf.port, AF_INET6);