main.c 22.5 KB
Newer Older
1
/*  Copyright (C) 2014-2017 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
Marek Vavruša's avatar
Marek Vavruša committed
2 3 4 5 6 7 8 9 10 11 12 13

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
14
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
Marek Vavruša's avatar
Marek Vavruša committed
15 16
 */

17
#include <arpa/inet.h>
18 19 20
#include <assert.h>
#include <getopt.h>
#include <libgen.h>
21
#include <signal.h>
Marek Vavruša's avatar
Marek Vavruša committed
22 23
#include <stdlib.h>
#include <string.h>
24 25
#include <unistd.h>

26
#include <uv.h>
27 28 29
#ifdef HAS_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
30
#include <libknot/error.h>
Marek Vavruša's avatar
Marek Vavruša committed
31

32 33 34
#include <contrib/cleanup.h>
#include <contrib/ucw/mempool.h>
#include <contrib/ccan/asprintf/asprintf.h>
35
#include "lib/defines.h"
36
#include "lib/resolve.h"
37
#include "lib/dnssec.h"
38 39
#include "daemon/network.h"
#include "daemon/worker.h"
40
#include "daemon/engine.h"
41
#include "daemon/bindings.h"
42
#include "daemon/tls.h"
43
#include "lib/dnssec/ta.h"
44

45 46 47 48 49
/* We can fork early on Linux 3.9+ and do SO_REUSEPORT for better performance. */
#if defined(UV_VERSION_HEX) && defined(SO_REUSEPORT) && defined(__linux__)
 #define CAN_FORK_EARLY 1
#endif

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
/* @internal Array of ip address shorthand. */
typedef array_t(char*) addr_array_t;

struct args {
	int forks;
	addr_array_t addr_set;
	addr_array_t tls_set;
	fd_array_t fd_set;
	fd_array_t tls_fd_set;
	char *keyfile;
	int keyfile_unmanaged;
	const char *moduledir;
	const char *config;
	int control_fd;
	const char *rundir;
	bool interactive;
	bool quiet;
	bool tty_binary_output;
};
69

70 71 72 73 74 75 76 77 78 79
/* lua_pcall helper function */
static inline char *lua_strerror(int lua_err) {
	switch (lua_err) {
	case LUA_ERRRUN: return "a runtime error";
	case LUA_ERRMEM: return "memory allocation error.";
	case LUA_ERRERR: return "error while running the error handler function.";
	default: return "a unknown error";
	}
}

80 81 82
/**
 * TTY control: process input and free() the buffer.
 *
83 84
 * For parameters see http://docs.libuv.org/en/v1.x/stream.html#c.uv_read_cb
 *
85 86
 * - This is just basic read-eval-print; libedit is supported through kresc;
 * - stream->data contains program arguments (struct args);
87
 */
88
static void tty_process_input(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
89
{
90 91
	char *cmd = buf ? buf->base : NULL; /* To be free()d on return. */

92
	/* Set output streams */
93
	FILE *out = stdout;
94
	uv_os_fd_t stream_fd = 0;
95
	struct args *args = stream->data;
96 97
	if (uv_fileno((uv_handle_t *)stream, &stream_fd)) {
		uv_close((uv_handle_t *)stream, (uv_close_cb) free);
98
		free(cmd);
99 100
		return;
	}
101
	if (stream_fd != STDIN_FILENO) {
102
		if (nread < 0) { /* Close if disconnected */
103
			uv_close((uv_handle_t *)stream, (uv_close_cb) free);
104 105
		}
		if (nread <= 0) {
106
			free(cmd);
107 108
			return;
		}
109 110
		uv_os_fd_t dup_fd = dup(stream_fd);
		if (dup_fd >= 0) {
111
			out = fdopen(dup_fd, "w");
112
		}
113
	}
114

115
	/* Execute */
116 117
	if (stream && cmd && nread > 0) {
		/* Ensure cmd is 0-terminated */
118 119
		if (cmd[nread - 1] == '\n') {
			cmd[nread - 1] = '\0';
120
		} else {
121 122 123 124 125 126
			if (nread >= buf->len) { /* only equality should be possible */
				char *newbuf = realloc(cmd, nread + 1);
				if (!newbuf)
					goto finish;
				cmd = newbuf;
			}
127
			cmd[nread] = '\0';
128
		}
129

130
		/* Pseudo-command for switching to "binary output"; */
131
		if (strcmp(cmd, "__binary") == 0) {
132
			args->tty_binary_output = true;
133 134 135 136
			goto finish;
		}

		struct engine *engine = ((struct worker_ctx *)stream->loop->data)->engine;
137
		lua_State *L = engine->L;
138
		int ret = engine_cmd(L, cmd, false);
139
		const char *message = "";
140
		if (lua_gettop(L) > 0) {
141
			message = lua_tostring(L, -1);
142
		}
143 144

		/* Simpler output in binary mode */
145
		if (args->tty_binary_output) {
146 147 148
			size_t len_s = strlen(message);
			if (len_s > UINT32_MAX)
				goto finish;
149 150 151
			uint32_t len_n = htonl(len_s);
			fwrite(&len_n, sizeof(len_n), 1, out);
			fwrite(message, len_s, 1, out);
152
			lua_settop(L, 0);
153 154 155
			goto finish;
		}

156
		/* Log to remote socket if connected */
157
		const char *delim = args->quiet ? "" : "> ";
158 159
		if (stream_fd != STDIN_FILENO) {
			fprintf(stdout, "%s\n", cmd); /* Duplicate command to logs */
160 161
			if (message)
				fprintf(out, "%s", message); /* Duplicate output to sender */
162
			if (message || !args->quiet)
163 164
				fprintf(out, "\n");
			fprintf(out, "%s", delim);
165
		}
166 167 168 169
		/* Log to standard streams */
		FILE *fp_out = ret ? stderr : stdout;
		if (message)
			fprintf(fp_out, "%s", message);
170
		if (message || !args->quiet)
171 172
			fprintf(fp_out, "\n");
		fprintf(fp_out, "%s", delim);
173
		lua_settop(L, 0);
174
	}
175
finish:
176
	fflush(out);
177
	free(cmd);
178 179
	/* Close if redirected */
	if (stream_fd != STDIN_FILENO) {
180
		fclose(out);
181
	}
182 183 184
}

static void tty_alloc(uv_handle_t *handle, size_t suggested, uv_buf_t *buf) {
Marek Vavruša's avatar
Marek Vavruša committed
185 186
	buf->len = suggested;
	buf->base = malloc(suggested);
187
}
188

189 190 191
static void tty_accept(uv_stream_t *master, int status)
{
	uv_tcp_t *client = malloc(sizeof(*client));
192
	struct args *args = master->data;
193 194 195
	if (client) {
		 uv_tcp_init(master->loop, client);
		 if (uv_accept(master, (uv_stream_t *)client) != 0) {
196 197
			free(client);
			return;
198
		 }
199
		 client->data = args;
200
		 uv_read_start((uv_stream_t *)client, tty_alloc, tty_process_input);
201
		 /* Write command line */
202
		 if (!args->quiet) {
203 204 205
		 	uv_buf_t buf = { "> ", 2 };
		 	uv_try_write((uv_stream_t *)client, &buf, 1);
		 }
206 207 208
	}
}

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
/* @internal AF_LOCAL reads may still be interrupted, loop it. */
static bool ipc_readall(int fd, char *dst, size_t len)
{
	while (len > 0) {
		int rb = read(fd, dst, len);
		if (rb > 0) {
			dst += rb;
			len -= rb;
		} else if (errno != EAGAIN && errno != EINTR) {
			return false;
		}
	}
	return true;
}

224
static void ipc_activity(uv_poll_t *handle, int status, int events)
225 226 227 228 229 230 231 232 233 234 235
{
	struct engine *engine = handle->data;
	if (status != 0) {
		kr_log_error("[system] ipc: %s\n", uv_strerror(status));
		return;
	}
	/* Get file descriptor from handle */
	uv_os_fd_t fd = 0;
	(void) uv_fileno((uv_handle_t *)(handle), &fd);
	/* Read expression from IPC pipe */
	uint32_t len = 0;
236 237 238 239 240 241
	auto_free char *rbuf = NULL;
	if (!ipc_readall(fd, (char *)&len, sizeof(len))) {
		goto failure;
	}
	if (len < UINT32_MAX) {
		rbuf = malloc(len + 1);
242
	} else {
243 244 245
		errno = EINVAL;
	}
	if (!rbuf) {
246
		goto failure;
247 248 249 250 251 252 253 254 255 256 257
	}
	if (!ipc_readall(fd, rbuf, len)) {
		goto failure;
	}
	rbuf[len] = '\0';
	/* Run expression */
	const char *message = "";
	int ret = engine_ipc(engine, rbuf);
	if (ret > 0) {
		message = lua_tostring(engine->L, -1);
	}
258 259
	/* Clear the Lua stack */
	lua_settop(engine->L, 0);
260 261 262 263
	/* Send response back */
	len = strlen(message);
	if (write(fd, &len, sizeof(len)) != sizeof(len) ||
		write(fd, message, len) != len) {
264
		goto failure;
265
	}
266
	return; /* success! */
267
failure:
268 269 270 271 272 273
	/* Note that if the piped command got read or written partially,
	 * we would get out of sync and only receive rubbish now.
	 * Therefore we prefer to stop IPC, but we try to continue with all else.
	 */
	kr_log_error("[system] stopping ipc because of: %s\n", strerror(errno));
	uv_poll_stop(handle);
274
	uv_close((uv_handle_t *)handle, (uv_close_cb)free);
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
}

static bool ipc_watch(uv_loop_t *loop, struct engine *engine, int fd)
{
	uv_poll_t *poller = malloc(sizeof(*poller));
	if (!poller) {
		return false;
	}
	int ret = uv_poll_init(loop, poller, fd);
	if (ret != 0) {
		free(poller);
		return false;
	}
	poller->data = engine;
	ret = uv_poll_start(poller, UV_READABLE, ipc_activity);
	if (ret != 0) {
		free(poller);
		return false;
	}
	/* libuv sets O_NONBLOCK whether we want it or not */
	(void) fcntl(fd, F_SETFD, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
	return true;
}

299
static void signal_handler(uv_signal_t *handle, int signum)
300 301 302 303 304
{
	uv_stop(uv_default_loop());
	uv_signal_stop(handle);
}

305 306 307 308 309 310 311 312 313
/** SIGBUS -> attempt to remove the overflowing cache file and abort. */
static void sigbus_handler(int sig, siginfo_t *siginfo, void *ptr)
{
	/* We can't safely assume that printf-like functions work, but write() is OK.
	 * See POSIX for the safe functions, e.g. 2017 version just above this link:
	 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_04
	 */
	#define WRITE_ERR(err_charray) \
		(void)write(STDERR_FILENO, err_charray, sizeof(err_charray))
314 315 316
	/* Unfortunately, void-cast on the write isn't enough to avoid the warning. */
	#pragma GCC diagnostic push
	#pragma GCC diagnostic ignored "-Wunused-result"
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	const char msg_typical[] =
		"\nSIGBUS received; this is most likely due to filling up the filesystem where cache resides.\n",
		msg_unknown[] = "\nSIGBUS received, cause unknown.\n",
		msg_deleted[] = "Cache file deleted.\n",
		msg_del_fail[] = "Cache file deletion failed.\n",
		msg_final[] = "kresd can not recover reliably by itself, exiting.\n";
	if (siginfo->si_code != BUS_ADRERR) {
		WRITE_ERR(msg_unknown);
		goto end;
	}
	WRITE_ERR(msg_typical);
	if (!kr_cache_emergency_file_to_remove) goto end;
	if (unlink(kr_cache_emergency_file_to_remove)) {
		WRITE_ERR(msg_del_fail);
	} else {
		WRITE_ERR(msg_deleted);
	}
end:
	WRITE_ERR(msg_final);
	_exit(128 - sig); /*< regular return from OS-raised SIGBUS can't work anyway */
	#undef WRITE_ERR
338
	#pragma GCC diagnostic pop
339 340
}

341
/** Split away port from the address. */
342 343
static const char *set_addr(char *addr, int *port)
{
344 345 346 347
	char *p = strchr(addr, '@');
	if (!p) {
		p = strchr(addr, '#');
	}
348
	if (p) {
349
		*port = strtol(p + 1, NULL, 10);
350 351 352 353 354 355 356 357 358 359
		*p = '\0';
	}

	return addr;
}

/*
 * Server operation.
 */

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
static int fork_workers(fd_array_t *ipc_set, int forks)
{
	/* Fork subprocesses if requested */
	while (--forks > 0) {
		int sv[2] = {-1, -1};
		if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sv) < 0) {
			perror("[system] socketpair");
			return kr_error(errno);
		}
		int pid = fork();
		if (pid < 0) {
			perror("[system] fork");
			return kr_error(errno);
		}

		/* Forked process */
		if (pid == 0) {
			array_clear(*ipc_set);
			array_push(*ipc_set, sv[0]);
			close(sv[1]);
			return forks;
		/* Parent process */
		} else {
			array_push(*ipc_set, sv[1]);
			/* Do not share parent-end with other forks. */
			(void) fcntl(sv[1], F_SETFD, FD_CLOEXEC);
			close(sv[0]);
		}
	}
	return 0;
}

Marek Vavruša's avatar
Marek Vavruša committed
392
static void help(int argc, char *argv[])
Marek Vavruša's avatar
Marek Vavruša committed
393
{
394
	printf("Usage: %s [parameters] [rundir]\n", argv[0]);
Marek Vavruša's avatar
Marek Vavruša committed
395
	printf("\nParameters:\n"
396 397 398 399 400
	       " -a, --addr=[addr]      Server address (default: localhost@53).\n"
	       " -t, --tls=[addr]       Server address for TLS (default: off).\n"
	       " -S, --fd=[fd]          Listen on given fd (handed out by supervisor).\n"
	       " -T, --tlsfd=[fd]       Listen using TLS on given fd (handed out by supervisor).\n"
	       " -c, --config=[path]    Config file path (relative to [rundir]) (default: config).\n"
401 402
	       " -k, --keyfile=[path]   File with root domain trust anchors (DS or DNSKEY), automatically updated.\n"
	       " -K, --keyfile-ro=[path] File with read-only root domain trust anchors, for use with an external updater.\n"
403 404
	       " -m, --moduledir=[path] Override the default module path (" MODULEDIR ").\n"
	       " -f, --forks=N          Start N forks sharing the configuration.\n"
405
	       " -q, --quiet            No command prompt in interactive mode.\n"
406
	       " -v, --verbose          Run in verbose mode."
407 408
#ifdef NOVERBOSELOG
	           " (Recompile without -DNOVERBOSELOG to activate.)"
409 410
#endif
	           "\n"
411 412
	       " -V, --version        Print version of the server.\n"
	       " -h, --help           Print help and usage.\n"
413
	       "Options:\n"
414
	       " [rundir]             Path to the working directory (default: .)\n");
Marek Vavruša's avatar
Marek Vavruša committed
415 416
}

417
static int run_worker(uv_loop_t *loop, struct engine *engine, fd_array_t *ipc_set, bool leader, struct args *args)
418 419 420 421 422
{
	/* Control sockets or TTY */
	auto_free char *sock_file = NULL;
	uv_pipe_t pipe;
	uv_pipe_init(loop, &pipe, 0);
423 424 425
	pipe.data = args;
	if (args->interactive) {
		if (!args->quiet)
426
			printf("[system] interactive mode\n> ");
427 428
		fflush(stdout);
		uv_pipe_open(&pipe, 0);
429
		uv_read_start((uv_stream_t*) &pipe, tty_alloc, tty_process_input);
430
	} else {
431
		int pipe_ret = -1;
432 433
		if (args->control_fd != -1) {
			pipe_ret = uv_pipe_open(&pipe, args->control_fd);
434 435 436 437 438 439
		} else {
			(void) mkdir("tty", S_IRWXU|S_IRWXG);
			sock_file = afmt("tty/%ld", getpid());
			if (sock_file) {
				pipe_ret = uv_pipe_bind(&pipe, sock_file);
			}
440
		}
441 442
		if (!pipe_ret)
			uv_listen((uv_stream_t *) &pipe, 16, tty_accept);
443
	}
444 445 446 447 448 449 450 451 452 453
	/* Watch IPC pipes (or just assign them if leading the pgroup). */
	if (!leader) {
		for (size_t i = 0; i < ipc_set->len; ++i) {
			if (!ipc_watch(loop, engine, ipc_set->at[i])) {
				kr_log_error("[system] failed to create poller: %s\n", strerror(errno));
				close(ipc_set->at[i]);
			}
		}
	}
	memcpy(&engine->ipc_set, ipc_set, sizeof(*ipc_set));
454

455 456 457 458
	/* Notify supervisor. */
#ifdef HAS_SYSTEMD
	sd_notify(0, "READY=1");
#endif
459
	/* Run event loop */
460
	uv_run(loop, UV_RUN_DEFAULT);
461 462 463
	if (sock_file) {
		unlink(sock_file);
	}
464
	return kr_ok();
Marek Vavruša's avatar
Marek Vavruša committed
465 466
}

467
#ifdef HAS_SYSTEMD
468
static void free_sd_socket_names(char **socket_names, int count)
469 470 471 472 473 474
{
	for (int i = 0; i < count; i++) {
		free(socket_names[i]);
	}
	free(socket_names);
}
475
#endif
476

477
static int set_keyfile(struct engine *engine, char *keyfile, bool unmanaged)
Marek Vavruša's avatar
Marek Vavruša committed
478
{
479
	assert(keyfile != NULL);
480
	auto_free char *cmd = afmt("trust_anchors.config('%s',%s)",
481
				   keyfile, unmanaged ? "true" : "nil");
482
	if (!cmd) {
483
		kr_log_error("[system] not enough memory\n");
484 485 486 487 488
		return kr_error(ENOMEM);
	}
	int lua_ret = engine_cmd(engine->L, cmd, false);
	if (lua_ret != 0) {
		if (lua_gettop(engine->L) > 0) {
489
			kr_log_error("%s\n", lua_tostring(engine->L, -1));
490 491
		} else {
			kr_log_error("[ ta ] keyfile '%s': failed to load (%s)\n",
492
					keyfile, lua_strerror(lua_ret));
493
		}
494
		return lua_ret;
495 496 497
	}

	lua_settop(engine->L, 0);
498
	return kr_ok();
499 500
}

501 502

static void args_init(struct args *args)
Marek Vavruša's avatar
Marek Vavruša committed
503
{
504
	memset(args, 0, sizeof(struct args));
505
	args->forks = 1;
506 507 508 509 510 511 512 513 514
	array_init(args->addr_set);
	array_init(args->tls_set);
	array_init(args->fd_set);
	array_init(args->tls_fd_set);
	args->moduledir = MODULEDIR;
	args->control_fd = -1;
	args->interactive = true;
	args->quiet = false;
}
Marek Vavruša's avatar
Marek Vavruša committed
515

516 517 518 519 520 521 522 523
static long strtol_10(const char *s)
{
	if (!s) abort();
	/* ^^ This shouldn't ever happen.  When getopt_long() returns an option
	 * character that has a mandatory parameter, optarg can't be NULL. */
	return strtol(s, NULL, 10);
}

524 525 526 527
/** Process arguments into struct args.
 * @return >=0 if main() should be exited immediately.
 */
static int parse_args(int argc, char **argv, struct args *args)
528
{
Marek Vavruša's avatar
Marek Vavruša committed
529
	/* Long options. */
530
	int c = 0, li = 0;
Marek Vavruša's avatar
Marek Vavruša committed
531
	struct option opts[] = {
532 533 534 535 536 537 538 539 540 541 542 543 544
		{"addr",       required_argument, 0, 'a'},
		{"tls",        required_argument, 0, 't'},
		{"fd",         required_argument, 0, 'S'},
		{"tlsfd",      required_argument, 0, 'T'},
		{"config",     required_argument, 0, 'c'},
		{"keyfile",    required_argument, 0, 'k'},
		{"keyfile-ro", required_argument, 0, 'K'},
		{"forks",      required_argument, 0, 'f'},
		{"moduledir",  required_argument, 0, 'm'},
		{"verbose",          no_argument, 0, 'v'},
		{"quiet",            no_argument, 0, 'q'},
		{"version",          no_argument, 0, 'V'},
		{"help",             no_argument, 0, 'h'},
Marek Vavruša's avatar
Marek Vavruša committed
545 546
		{0, 0, 0, 0}
	};
547
	while ((c = getopt_long(argc, argv, "a:t:S:T:c:f:m:K:k:vqVh", opts, &li)) != -1) {
Marek Vavruša's avatar
Marek Vavruša committed
548 549 550
		switch (c)
		{
		case 'a':
551
			array_push(args->addr_set, optarg);
Marek Vavruša's avatar
Marek Vavruša committed
552
			break;
553
		case 't':
554
			array_push(args->tls_set, optarg);
555
			break;
556
		case 'S':
557
			array_push(args->fd_set, strtol_10(optarg));
558
			break;
559
		case 'T':
560
			array_push(args->tls_fd_set, strtol_10(optarg));
561
			break;
562
		case 'c':
563
			args->config = optarg;
564
			break;
Marek Vavruša's avatar
Marek Vavruša committed
565
		case 'f':
566
			args->interactive = false;
567
			args->forks = strtol_10(optarg);
568
			if (args->forks <= 0) {
569 570
				kr_log_error("[system] error '-f' requires a positive"
						" number, not '%s'\n", optarg);
Marek Vavruša's avatar
Marek Vavruša committed
571 572 573
				return EXIT_FAILURE;
			}
			break;
574
		case 'K':
575
			args->keyfile_unmanaged = 1;
576
		case 'k':
577
			if (args->keyfile != NULL) {
578 579 580
				kr_log_error("[system] error only one of '--keyfile' and '--keyfile-ro' allowed\n");
				return EXIT_FAILURE;
			}
581
			args->keyfile = optarg;
582
			break;
583
		case 'm':
584
			args->moduledir = optarg;
585
			break;
586
		case 'v':
587 588 589
			kr_verbose_set(true);
#ifdef NOVERBOSELOG
			kr_log_info("--verbose flag has no effect due to compilation with -DNOVERBOSELOG.\n");
590
#endif
591
			break;
592
		case 'q':
593
			args->quiet = true;
594
			break;
595
		case 'V':
596
			kr_log_info("%s, version %s\n", "Knot Resolver", PACKAGE_VERSION);
Marek Vavruša's avatar
Marek Vavruša committed
597 598 599
			return EXIT_SUCCESS;
		case 'h':
		case '?':
Marek Vavruša's avatar
Marek Vavruša committed
600
			help(argc, argv);
Marek Vavruša's avatar
Marek Vavruša committed
601 602
			return EXIT_SUCCESS;
		default:
Marek Vavruša's avatar
Marek Vavruša committed
603
			help(argc, argv);
Marek Vavruša's avatar
Marek Vavruša committed
604 605
			return EXIT_FAILURE;
		}
606
	}
607 608 609
	if (optind < argc) {
		args->rundir = argv[optind];
	}
610
	return -1;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
}

static int bind_fds(struct network *net, fd_array_t *fd_set, bool tls) {
	int ret = 0;
	for (size_t i = 0; i < fd_set->len; ++i) {
		ret = network_listen_fd(net, fd_set->at[i], tls);
		if (ret != 0) {
			kr_log_error("[system] %slisten on fd=%d %s\n",
				 tls ? "TLS " : "", fd_set->at[i], kr_strerror(ret));
			break;
		}
	}
	return ret;
}

static int bind_sockets(struct network *net, addr_array_t *addr_set, bool tls) {	
	uint32_t flags = tls ? NET_TCP|NET_TLS : NET_UDP|NET_TCP;
	int ret = 0;
	for (size_t i = 0; i < addr_set->len; ++i) {
		int port = tls ? KR_DNS_TLS_PORT : KR_DNS_PORT;
		const char *addr = set_addr(addr_set->at[i], &port);
		ret = network_listen(net, addr, (uint16_t)port, flags);
		if (ret != 0) {
			kr_log_error("[system] bind to '%s@%d' %s%s\n", 
				addr, port, tls ? "(TLS) " : "", kr_strerror(ret));
			break;
		}
	}
	return ret;
}

int main(int argc, char **argv)
{
	int ret = 0;
	struct args args;
	args_init(&args);
647
	if ((ret = parse_args(argc, argv, &args)) >= 0) {
648
		return ret;
Marek Vavruša's avatar
Marek Vavruša committed
649 650
	}

651 652
#ifdef HAS_SYSTEMD
	/* Accept passed sockets from systemd supervisor. */
653 654
	char **socket_names = NULL;
	int sd_nsocks = sd_listen_fds_with_names(0, &socket_names);
655 656
	for (int i = 0; i < sd_nsocks; ++i) {
		int fd = SD_LISTEN_FDS_START + i;
657
		/* when run under systemd supervision, do not use interactive mode */
658 659
		args.interactive = false;
		if (args.forks != 1) {
660
			kr_log_error("[system] when run under systemd-style supervision, "
661
				     "use single-process only (bad: --forks=%d).\n", args.forks);
662 663 664 665
			free_sd_socket_names(socket_names, sd_nsocks);
			return EXIT_FAILURE;
		}
		if (!strcasecmp("control",socket_names[i])) {
666
			args.control_fd = fd;
667
		} else if (!strcasecmp("tls",socket_names[i])) {
668
			array_push(args.tls_fd_set, fd);
669
		} else {
670
			array_push(args.fd_set, fd);
671
		}
672
	}
673
	free_sd_socket_names(socket_names, sd_nsocks);
674 675
#endif

676
	/* Switch to rundir. */
677
	if (args.rundir != NULL) {
678
		/* FIXME: access isn't a good way if we start as root and drop privileges later */
679 680
		if (access(args.rundir, W_OK) != 0) {
			kr_log_error("[system] rundir '%s': %s\n", args.rundir, strerror(errno));
681 682
			return EXIT_FAILURE;
		}
683
		ret = chdir(args.rundir);
684
		if (ret != 0) {
685
			kr_log_error("[system] rundir '%s': %s\n", args.rundir, strerror(errno));
686 687
			return EXIT_FAILURE;
		}
688
	}
689

690 691
	if (args.config && strcmp(args.config, "-") != 0 && access(args.config, R_OK) != 0) {
		kr_log_error("[system] config '%s': %s\n", args.config, strerror(errno));
692 693
		return EXIT_FAILURE;
	}
694 695
	if (!args.config && access("config", R_OK) == 0) {
		args.config = "config";
696 697
	}

698 699 700 701 702
#ifndef CAN_FORK_EARLY
	/* Forking is currently broken with libuv. We need libuv to bind to
	 * sockets etc. before forking, but at the same time can't touch it before
	 * forking otherwise it crashes, so it's a chicken and egg problem.
	 * Disabling until https://github.com/libuv/libuv/pull/846 is done. */
703
	 if (args.forks > 1 && args.fd_set.len == 0 && args.tls_fd_set.len == 0) {
704 705 706 707
	 	kr_log_error("[system] forking >1 workers supported only on Linux 3.9+ or with supervisor\n");
	 	return EXIT_FAILURE;
	 }
#endif
708

709
	/* Connect forks with local socket */
710 711
	fd_array_t ipc_set;
	array_init(ipc_set);
712
	/* Fork subprocesses if requested */
713
	int fork_id = fork_workers(&ipc_set, args.forks);
714 715
	if (fork_id < 0) {
		return EXIT_FAILURE;
716 717
	}

718 719
	kr_crypto_init();

720
	/* Create a server engine. */
721
	knot_mm_t pool = {
722
		.ctx = mp_new (4096),
723
		.alloc = (knot_mm_alloc_t) mp_alloc
724
	};
725 726 727
	struct engine engine;
	ret = engine_init(&engine, &pool);
	if (ret != 0) {
728
		kr_log_error("[system] failed to initialize engine: %s\n", kr_strerror(ret));
729 730
		return EXIT_FAILURE;
	}
731
	/* Create worker */
732
	struct worker_ctx *worker = worker_create(&engine, &pool, fork_id, args.forks);
733
	if (!worker) {
734
		kr_log_error("[system] not enough memory\n");
735 736
		return EXIT_FAILURE;
	}
737

738 739 740
	uv_loop_t *loop = uv_default_loop();
	worker->loop = loop;
	loop->data = worker;
741

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
	/* Catch some signals. */
	uv_signal_t sigint, sigterm;
	if (true) ret = uv_signal_init(loop, &sigint);
	if (!ret) ret = uv_signal_init(loop, &sigterm);
	if (!ret) ret = uv_signal_start(&sigint, signal_handler, SIGINT);
	if (!ret) ret = uv_signal_start(&sigterm, signal_handler, SIGTERM);
	/* Block SIGPIPE; see https://github.com/libuv/libuv/issues/45 */
	if (!ret && signal(SIGPIPE, SIG_IGN) == SIG_ERR) ret = errno;
	if (!ret) {
		/* Catching SIGBUS via uv_signal_* can't work; see:
		 * https://github.com/libuv/libuv/pull/1987 */
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_sigaction = sigbus_handler;
		sa.sa_flags = SA_SIGINFO;
		if (sigaction(SIGBUS, &sa, NULL)) {
			ret = errno;
		}
	}
	if (ret) {
		kr_log_error("[system] failed to set up signal handlers: %s\n",
				strerror(abs(errno)));
		ret = EXIT_FAILURE;
765 766 767
		goto cleanup;
	}

768 769 770 771 772 773 774 775 776 777
	/* Bind to passed fds and sockets*/
	if (bind_fds(&engine.net, &args.fd_set, false) != 0 ||
	    bind_fds(&engine.net, &args.tls_fd_set, true) != 0 ||
	    bind_sockets(&engine.net, &args.addr_set, false) != 0 ||
	    bind_sockets(&engine.net, &args.tls_set, true) != 0
	) {
		ret = EXIT_FAILURE;
		goto cleanup;
	}

778
	/* Start the scripting engine */
779
	engine_set_moduledir(&engine, args.moduledir);
780

781
	if (engine_load_sandbox(&engine) != 0) {
782 783 784
		ret = EXIT_FAILURE;
		goto cleanup;
	}
785 786
	if (args.config != NULL && strcmp(args.config, "-") != 0) {
		if(engine_loadconf(&engine, args.config) != 0) {
787 788 789
			ret = EXIT_FAILURE;
			goto cleanup;
		}
790
		lua_settop(engine.L, 0);
791
	}
792
	if (args.keyfile != NULL && set_keyfile(&engine, args.keyfile, args.keyfile_unmanaged) != 0) {
793 794 795
		ret = EXIT_FAILURE;
		goto cleanup;
	}
796 797
	if (args.config == NULL || strcmp(args.config, "-") !=0) {
		if(engine_load_defaults(&engine) != 0) {
798
			ret = EXIT_FAILURE;
799
			goto cleanup;
800
		}
801 802
	}
	if (engine_start(&engine) != 0) {
803 804
		ret = EXIT_FAILURE;
		goto cleanup;
805
	}
806 807

	/* Run the event loop */
808
	ret = run_worker(loop, &engine, &ipc_set, fork_id == 0, &args);
809 810 811 812 813 814 815
	if (ret != 0) {
		perror("[system] worker failed");
		ret = EXIT_FAILURE;
		goto cleanup;
	}

cleanup:/* Cleanup. */
816
	engine_deinit(&engine);
817
	worker_reclaim(worker);
818 819 820
	if (loop != NULL) {
		uv_loop_close(loop);	
	}
821
	mp_delete(pool.ctx);
822 823
	array_clear(args.addr_set);
	array_clear(args.tls_set);
824
	kr_crypto_cleanup();
825 826
	return ret;
}