bindings.c 26.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/*  Copyright (C) 2015 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>

    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/>.
15 16
 */

17
#include <assert.h>
18
#include <uv.h>
19
#include <contrib/cleanup.h>
20
#include <libknot/descriptor.h>
21

22
#include "lib/cache.h"
23
#include "lib/cdb.h"
24
#include "daemon/bindings.h"
25
#include "daemon/worker.h"
26

27 28 29
/** @internal Annotate for static checkers. */
KR_NORETURN int lua_error (lua_State *L);

30 31 32 33 34 35 36
/** @internal Prefix error with file:line */
static int format_error(lua_State* L, const char *err)
{
	lua_Debug d;
	lua_getstack(L, 1, &d);
	/* error message prefix */
	lua_getinfo(L, "Sln", &d);
37 38 39 40 41 42 43 44 45
	if (strncmp(d.short_src, "[", 1) != 0) {
		lua_pushstring(L, d.short_src);
		lua_pushstring(L, ":");
		lua_pushnumber(L, d.currentline);
		lua_pushstring(L, ": error: ");
		lua_concat(L, 4);
	} else {
		lua_pushstring(L, "error: ");
	}
46 47
	/* error message */
	lua_pushstring(L, err);
48
	lua_concat(L,  2);
49 50 51
	return 1;
}

52 53 54 55 56 57 58
static inline struct worker_ctx *wrk_luaget(lua_State *L) {
	lua_getglobal(L, "__worker");
	struct worker_ctx *worker = lua_touserdata(L, -1);
	lua_pop(L, 1);
	return worker;
}

59 60 61 62
/** List loaded modules */
static int mod_list(lua_State *L)
{
	struct engine *engine = engine_luaget(L);
63
	lua_newtable(L);
64
	for (unsigned i = 0; i < engine->modules.len; ++i) {
65
		struct kr_module *module = engine->modules.at[i];
66
		lua_pushstring(L, module->name);
67
		lua_rawseti(L, -2, i + 1);
68
	}
69
	return 1;
70 71 72 73 74 75 76 77
}

/** Load module. */
static int mod_load(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
	if (n != 1 || !lua_isstring(L, 1)) {
78
		format_error(L, "expected 'load(string name)'");
79 80
		lua_error(L);
	}
81 82 83 84 85 86 87 88
	/* Parse precedence declaration */
	auto_free char *declaration = strdup(lua_tostring(L, 1));
	if (!declaration) {
		return kr_error(ENOMEM);
	}
	const char *name = strtok(declaration, " ");
	const char *precedence = strtok(NULL, " ");
	const char *ref = strtok(NULL, " ");
89 90
	/* Load engine module */
	struct engine *engine = engine_luaget(L);
91
	int ret = engine_register(engine, name, precedence, ref);
92
	if (ret != 0) {
93 94 95 96 97
		if (ret == kr_error(EIDRM)) {
			format_error(L, "referenced module not found");
		} else {
			format_error(L, kr_strerror(ret));
		}
98 99
		lua_error(L);
	}
100 101 102

	lua_pushboolean(L, 1);
	return 1;
103 104 105 106 107
}

/** Unload module. */
static int mod_unload(lua_State *L)
{
108 109 110
	/* Check parameters */
	int n = lua_gettop(L);
	if (n != 1 || !lua_isstring(L, 1)) {
Marek Vavruša's avatar
Marek Vavruša committed
111
		format_error(L, "expected 'unload(string name)'");
112 113 114 115 116 117
		lua_error(L);
	}
	/* Unload engine module */
	struct engine *engine = engine_luaget(L);
	int ret = engine_unregister(engine, lua_tostring(L, 1));
	if (ret != 0) {
118
		format_error(L, kr_strerror(ret));
119 120
		lua_error(L);
	}
121 122 123

	lua_pushboolean(L, 1);
	return 1;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
}

int lib_modules(lua_State *L)
{
	static const luaL_Reg lib[] = {
		{ "list",   mod_list },
		{ "load",   mod_load },
		{ "unload", mod_unload },
		{ NULL, NULL }
	};

	register_lib(L, "modules", lib);
	return 1;
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
/** Append 'addr = {port = int, udp = bool, tcp = bool}' */
static int net_list_add(const char *key, void *val, void *ext)
{
	lua_State *L = (lua_State *)ext;
	endpoint_array_t *ep_array = val;
	lua_newtable(L);
	for (size_t i = ep_array->len; i--;) {
		struct endpoint *ep = ep_array->at[i];
		lua_pushinteger(L, ep->port);
		lua_setfield(L, -2, "port");
		lua_pushboolean(L, ep->flags & NET_UDP);
		lua_setfield(L, -2, "udp");
		lua_pushboolean(L, ep->flags & NET_TCP);
		lua_setfield(L, -2, "tcp");
	}
	lua_setfield(L, -2, key);
	return kr_ok();
}

158 159 160
/** List active endpoints. */
static int net_list(lua_State *L)
{
161 162 163 164
	struct engine *engine = engine_luaget(L);
	lua_newtable(L);
	map_walk(&engine->net.endpoints, net_list_add, L);
	return 1;
165 166
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
/** Listen on interface address list. */
static int net_listen_iface(lua_State *L, int port)
{
	/* Expand 'addr' key if exists */
	lua_getfield(L, 1, "addr");
	if (lua_isnil(L, -1)) {
		lua_pop(L, 1);
		lua_pushvalue(L, 1);
	}

	/* Bind to address list */
	struct engine *engine = engine_luaget(L);
	size_t count = lua_rawlen(L, -1);
	for (size_t i = 0; i < count; ++i) {
		lua_rawgeti(L, -1, i + 1);
		int ret = network_listen(&engine->net, lua_tostring(L, -1),
		                         port, NET_TCP|NET_UDP);
		if (ret != 0) {
185
			kr_log_info("[system] bind to '%s#%d' %s\n", lua_tostring(L, -1), port, kr_strerror(ret));
186 187 188 189 190 191 192 193
		}
		lua_pop(L, 1);
	}

	lua_pushboolean(L, true);
	return 1;
}

194 195 196
/** Listen on endpoint. */
static int net_listen(lua_State *L)
{
197 198
	/* Check parameters */
	int n = lua_gettop(L);
199 200 201 202 203 204 205 206 207
	int port = KR_DNS_PORT;
	if (n > 1 && lua_isnumber(L, 2)) {
		port = lua_tointeger(L, 2);
	}

	/* Process interface or (address, port) pair. */
	if (lua_istable(L, 1)) {
		return net_listen_iface(L, port);
	} else if (n < 1 || !lua_isstring(L, 1)) {
Marek Vavruša's avatar
Marek Vavruša committed
208
		format_error(L, "expected 'listen(string addr, number port = 53)'");
209 210 211 212 213
		lua_error(L);
	}

	/* Open resolution context cache */
	struct engine *engine = engine_luaget(L);
214 215
	int ret = network_listen(&engine->net, lua_tostring(L, 1), port, NET_TCP|NET_UDP);
	if (ret != 0) {
216
		format_error(L, kr_strerror(ret));
217 218 219 220
		lua_error(L);
	}

	lua_pushboolean(L, true);
221
	return 1;
222 223 224 225
}

/** Close endpoint. */
static int net_close(lua_State *L)
226
{
227 228 229
	/* Check parameters */
	int n = lua_gettop(L);
	if (n < 2) {
Marek Vavruša's avatar
Marek Vavruša committed
230
		format_error(L, "expected 'close(string addr, number port)'");
231 232 233 234 235 236 237 238
		lua_error(L);
	}

	/* Open resolution context cache */
	struct engine *engine = engine_luaget(L);
	int ret = network_close(&engine->net, lua_tostring(L, 1), lua_tointeger(L, 2));
	lua_pushboolean(L, ret == 0);
	return 1;
239 240
}

241
/** List available interfaces. */
242 243 244 245
static int net_interfaces(lua_State *L)
{
	/* Retrieve interface list */
	int count = 0;
246
	char buf[INET6_ADDRSTRLEN]; /* https://tools.ietf.org/html/rfc4291 */
247 248 249
	uv_interface_address_t *info = NULL;
	uv_interface_addresses(&info, &count);
	lua_newtable(L);
250
	for (int i = 0; i < count; ++i) {
251
		uv_interface_address_t iface = info[i];
252 253 254 255 256
		lua_getfield(L, -1, iface.name);
		if (lua_isnil(L, -1)) {
			lua_pop(L, 1);
			lua_newtable(L);
		}
257 258

		/* Address */
259 260 261 262 263 264
		lua_getfield(L, -1, "addr");
		if (lua_isnil(L, -1)) {
			lua_pop(L, 1);
			lua_newtable(L);
		}
		if (iface.address.address4.sin_family == AF_INET) {
265
			uv_ip4_name(&iface.address.address4, buf, sizeof(buf));
266
		} else if (iface.address.address4.sin_family == AF_INET6) {
267
			uv_ip6_name(&iface.address.address6, buf, sizeof(buf));
268 269
		} else {
			buf[0] = '\0';
270 271
		}
		lua_pushstring(L, buf);
Marek Vavruša's avatar
Marek Vavruša committed
272
		lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
273 274 275 276 277 278
		lua_setfield(L, -2, "addr");

		/* Hardware address. */
		char *p = buf;
		memset(buf, 0, sizeof(buf));
		for (unsigned k = 0; k < sizeof(iface.phys_addr); ++k) {
279 280
			sprintf(p, "%.2x:", iface.phys_addr[k] & 0xff);
			p += 3;
281
		}
282
		*(p - 1) = '\0';
283
		lua_pushstring(L, buf);
284
		lua_setfield(L, -2, "mac");
285 286

		/* Push table */
287
		lua_setfield(L, -2, iface.name);
288 289 290 291 292 293
	}
	uv_free_interface_addresses(info, count);

	return 1;
}

294 295 296 297 298 299 300 301 302 303
/** Set UDP maximum payload size. */
static int net_bufsize(lua_State *L)
{
	struct engine *engine = engine_luaget(L);
	knot_rrset_t *opt_rr = engine->resolver.opt_rr;
	if (!lua_isnumber(L, 1)) {
		lua_pushnumber(L, knot_edns_get_payload(opt_rr));
		return 1;
	}
	int bufsize = lua_tointeger(L, 1);
304 305
	if (bufsize < 512 || bufsize > UINT16_MAX) {
		format_error(L, "bufsize must be within <512, 65535>");
306 307 308 309 310 311
		lua_error(L);
	}
	knot_edns_set_payload(opt_rr, (uint16_t) bufsize);
	return 0;
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
/** Set TCP pipelining size. */
static int net_pipeline(lua_State *L)
{
	struct worker_ctx *worker = wrk_luaget(L);
	if (!worker) {
		return 0;
	}
	if (!lua_isnumber(L, 1)) {
		lua_pushnumber(L, worker->tcp_pipeline_max);
		return 1;
	}
	int len = lua_tointeger(L, 1);
	if (len < 0 || len > 4096) {
		format_error(L, "tcp_pipeline must be within <0, 4096>");
		lua_error(L);
	}
	worker->tcp_pipeline_max = len;
	lua_pushnumber(L, len);
	return 1;
}

333 334 335
int lib_net(lua_State *L)
{
	static const luaL_Reg lib[] = {
336 337 338 339 340 341
		{ "list",         net_list },
		{ "listen",       net_listen },
		{ "close",        net_close },
		{ "interfaces",   net_interfaces },
		{ "bufsize",      net_bufsize },
		{ "tcp_pipeline", net_pipeline },
342 343 344 345 346 347
		{ NULL, NULL }
	};
	register_lib(L, "net", lib);
	return 1;
}

348 349 350 351 352 353
/** Return available cached backends. */
static int cache_backends(lua_State *L)
{
	struct engine *engine = engine_luaget(L);

	lua_newtable(L);
354 355 356 357
	for (unsigned i = 0; i < engine->backends.len; ++i) {
		const struct kr_cdb_api *api = engine->backends.at[i];
		lua_pushboolean(L, api == engine->resolver.cache.api);
		lua_setfield(L, -2, api->name);
358 359 360 361
	}
	return 1;
}

362 363 364 365
/** Return number of cached records. */
static int cache_count(lua_State *L)
{
	struct engine *engine = engine_luaget(L);
366
	const struct kr_cdb_api *api = engine->resolver.cache.api;
367

368
	/* First key is a version counter, omit it. */
369 370 371 372 373 374
	struct kr_cache *cache = &engine->resolver.cache;
	if (kr_cache_is_open(cache)) {
		lua_pushinteger(L, api->count(cache->db) - 1);
		return 1;
	}
	return 0;
375 376
}

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
/** Return cache statistics. */
static int cache_stats(lua_State *L)
{
	struct engine *engine = engine_luaget(L);
	struct kr_cache *cache = &engine->resolver.cache;
	lua_newtable(L);
	lua_pushnumber(L, cache->stats.hit);
	lua_setfield(L, -2, "hit");
	lua_pushnumber(L, cache->stats.miss);
	lua_setfield(L, -2, "miss");
	lua_pushnumber(L, cache->stats.insert);
	lua_setfield(L, -2, "insert");
	lua_pushnumber(L, cache->stats.delete);
	lua_setfield(L, -2, "delete");
	return 1;
}

394
static const struct kr_cdb_api *cache_select(struct engine *engine, const char **conf)
395 396
{
	/* Return default backend */
397 398
	if (*conf == NULL || !strstr(*conf, "://")) {
		return engine->backends.at[0];
399 400 401
	}

	/* Find storage backend from config prefix */
402 403 404 405 406
	for (unsigned i = 0; i < engine->backends.len; ++i) {
		const struct kr_cdb_api *api = engine->backends.at[i];
		if (strncmp(*conf, api->name, strlen(api->name)) == 0) {
			*conf += strlen(api->name) + strlen("://");
			return api;
407 408 409 410 411 412
		}
	}

	return NULL;
}

413 414 415 416 417
/** Open cache */
static int cache_open(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
418
	if (n < 1 || !lua_isnumber(L, 1)) {
Marek Vavruša's avatar
Marek Vavruša committed
419
		format_error(L, "expected 'open(number max_size, string config = \"\")'");
420 421 422
		lua_error(L);
	}

423
	/* Select cache storage backend */
424
	struct engine *engine = engine_luaget(L);
425
	unsigned cache_size = lua_tonumber(L, 1);
426
	const char *conf = n > 1 ? lua_tostring(L, 2) : NULL;
427
	const char *uri = conf;
428 429
	const struct kr_cdb_api *api = cache_select(engine, &conf);
	if (!api) {
430 431 432 433 434
		format_error(L, "unsupported cache backend");
		lua_error(L);
	}

	/* Close if already open */
435
	kr_cache_close(&engine->resolver.cache);
436

437
	/* Reopen cache */
438 439 440 441 442
	struct kr_cdb_opts opts = {
		(conf && strlen(conf)) ? conf : ".",
		cache_size
	};
	int ret = kr_cache_open(&engine->resolver.cache, api, &opts, engine->pool);
443
	if (ret != 0) {
444
		format_error(L, "can't open cache");
445 446 447
		lua_error(L);
	}

448 449
	/* Store current configuration */
	lua_getglobal(L, "cache");
450
	lua_pushstring(L, "current_size");
451 452
	lua_pushnumber(L, cache_size);
	lua_rawset(L, -3);
453
	lua_pushstring(L, "current_storage");
454 455
	lua_pushstring(L, uri);
	lua_rawset(L, -3);
456
	lua_pop(L, 1);
457

458 459 460 461 462 463 464
	lua_pushboolean(L, 1);
	return 1;
}

static int cache_close(lua_State *L)
{
	struct engine *engine = engine_luaget(L);
465 466 467 468 469 470
	struct kr_cache *cache = &engine->resolver.cache;
	if (!kr_cache_is_open(cache)) {
		return 0;
	}

	kr_cache_close(cache);
471 472 473 474 475
	lua_getglobal(L, "cache");
	lua_pushstring(L, "current_size");
	lua_pushnumber(L, 0);
	lua_rawset(L, -3);
	lua_pop(L, 1);
476 477
	lua_pushboolean(L, 1);
	return 1;
478 479
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
/** @internal Prefix walk. */
static int cache_prefixed(struct kr_cache *cache, const char *args, knot_db_val_t *results, int maxresults)
{
	/* Decode parameters */
	uint8_t namespace = 'R';
	char *extra = (char *)strchr(args, ' ');
	if (extra != NULL) {
		extra[0] = '\0';
		namespace = extra[1];
	}

	/* Convert to domain name */
	uint8_t buf[KNOT_DNAME_MAXLEN];
	if (!knot_dname_from_str(buf, args, sizeof(buf))) {
		return kr_error(EINVAL);
	}

	/* Start prefix search */
	return kr_cache_match(cache, namespace, buf, results, maxresults);
}

/** @internal Delete iterated key. */
static int cache_remove_prefix(struct kr_cache *cache, const char *args)
{
	/* Check if we can remove */
	if (!cache || !cache->api || !cache->api->remove) {
		return kr_error(ENOSYS);
	}
	static knot_db_val_t result_set[1000];
	int ret = cache_prefixed(cache, args, result_set, 1000);
	if (ret < 0) {
		return ret;
	}
	/* Duplicate result set as we're going to remove it
	 * which will invalidate result set. */
	for (int i = 0; i < ret; ++i) {
		void *dst = malloc(result_set[i].len);
		if (!dst) {
			return kr_error(ENOMEM);
		}
		memcpy(dst, result_set[i].data, result_set[i].len);
		result_set[i].data = dst;
	}
	cache->api->remove(cache->db, result_set, ret);
	/* Free keys */
	for (int i = 0; i < ret; ++i) {
		free(result_set[i].data);
	}
	return ret;
}

/** Prune expired/invalid records. */
static int cache_prune(lua_State *L)
{
534 535 536 537 538 539
	struct engine *engine = engine_luaget(L);
	struct kr_cache *cache = &engine->resolver.cache;
	if (!kr_cache_is_open(cache)) {
		return 0;
	}

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
	/* Check parameters */
	int prune_max = UINT16_MAX;
	int n = lua_gettop(L);
	if (n >= 1 && lua_isnumber(L, 1)) {
		prune_max = lua_tointeger(L, 1);
	}

	/* Check if API supports pruning. */
	int ret = kr_error(ENOSYS);
	if (cache->api->prune) {
		ret = cache->api->prune(cache->db, prune_max);
	}
	/* Commit and format result. */
	if (ret < 0) {
		format_error(L, kr_strerror(ret));
		lua_error(L);
	}
	lua_pushinteger(L, ret);
	return 1;
}

/** Clear all records. */
static int cache_clear(lua_State *L)
{
564 565 566 567 568 569
	struct engine *engine = engine_luaget(L);
	struct kr_cache *cache = &engine->resolver.cache;
	if (!kr_cache_is_open(cache)) {
		return 0;
	}

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 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
	/* Check parameters */
	const char *args = NULL;
	int n = lua_gettop(L);
	if (n >= 1 && lua_isstring(L, 1)) {
		args = lua_tostring(L, 1);
	}

	/* Clear a sub-tree in cache. */
	if (args && strlen(args) > 0) {
		int ret = cache_remove_prefix(cache, args);
		if (ret < 0) {
			format_error(L, kr_strerror(ret));
			lua_error(L);
		}
		lua_pushinteger(L, ret);
		return 1;
	}

	/* Clear cache. */
	int ret = kr_cache_clear(cache);
	if (ret < 0) {
		format_error(L, kr_strerror(ret));
		lua_error(L);
	}

	/* Clear reputation tables */
	lru_deinit(engine->resolver.cache_rtt);
	lru_deinit(engine->resolver.cache_rep);
	lru_init(engine->resolver.cache_rtt, LRU_RTT_SIZE);
	lru_init(engine->resolver.cache_rep, LRU_REP_SIZE);
	lua_pushboolean(L, true);
	return 1;
}

/** @internal Dump cache key into table on Lua stack. */
static void cache_dump_key(lua_State *L, knot_db_val_t *key)
{
	char buf[KNOT_DNAME_MAXLEN];
	/* Extract type */
	uint16_t type = 0;
	const char *endp = (const char *)key->data + key->len - sizeof(uint16_t);
	memcpy(&type, endp, sizeof(uint16_t));
	endp -= 1;
	/* Extract domain name */
	char *dst = buf;
	const char *scan = endp - 1;
	while (scan > (const char *)key->data) {
		if (*scan == '\0') {
			const size_t lblen = endp - scan - 1;
			memcpy(dst, scan + 1, lblen);
			dst += lblen;
			*dst++ = '.';
			endp = scan;
		}
		--scan;
	}
	memcpy(dst, scan + 1, endp - scan);
	/* If name typemap doesn't exist yet, create it */
	lua_getfield(L, -1, buf);
	if (lua_isnil(L, -1)) {
		lua_pop(L, 1);
		lua_newtable(L);
	}
	/* Append to typemap */
	char type_buf[16] = { '\0' };
	knot_rrtype_to_string(type, type_buf, sizeof(type_buf));
	lua_pushboolean(L, true);
	lua_setfield(L, -2, type_buf);
	/* Set name typemap */
	lua_setfield(L, -2, buf);
}

/** Query cached records. */
static int cache_get(lua_State *L)
{
645 646 647 648 649 650
	struct engine *engine = engine_luaget(L);
	struct kr_cache *cache = &engine->resolver.cache;
	if (!kr_cache_is_open(cache)) {
		return 0;
	}

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
	/* Check parameters */
	int n = lua_gettop(L);
	if (n < 1 || !lua_isstring(L, 1)) {
		format_error(L, "expected 'cache.get(string key)'");
		lua_error(L);
	}

	/* Clear a sub-tree in cache. */
	const char *args = lua_tostring(L, 1);
	/* Retrieve set of keys */
	static knot_db_val_t result_set[100];
	int ret = cache_prefixed(cache, args, result_set, 100);
	if (ret < 0) {
		format_error(L, kr_strerror(ret));
		lua_error(L);
	}
	/* Format output */
	lua_newtable(L);
	for (int i = 0; i < ret; ++i) {
		cache_dump_key(L, &result_set[i]);
	}
	return 1;
}

675 676 677
int lib_cache(lua_State *L)
{
	static const luaL_Reg lib[] = {
678
		{ "backends", cache_backends },
679
		{ "count",  cache_count },
680
		{ "stats",  cache_stats },
681 682
		{ "open",   cache_open },
		{ "close",  cache_close },
683 684 685
		{ "prune",  cache_prune },
		{ "clear",  cache_clear },
		{ "get",    cache_get },
686 687 688 689
		{ NULL, NULL }
	};

	register_lib(L, "cache", lib);
Marek Vavruša's avatar
Marek Vavruša committed
690
	return 1;
691
}
692 693 694 695 696 697 698 699 700 701

static void event_free(uv_timer_t *timer)
{
	struct worker_ctx *worker = timer->loop->data;
	lua_State *L = worker->engine->L;
	int ref = (intptr_t) timer->data;
	luaL_unref(L, LUA_REGISTRYINDEX, ref);
	free(timer);
}

702 703 704 705 706 707 708 709 710 711 712
static int execute_callback(lua_State *L, int argc)
{
	int ret = engine_pcall(L, argc);
	if (ret != 0) {
		fprintf(stderr, "error: %s\n", lua_tostring(L, -1));
	}
	/* Clear the stack, there may be event a/o enything returned */
	lua_settop(L, 0);
	return ret;
}

713 714 715 716 717 718 719 720 721
static void event_callback(uv_timer_t *timer)
{
	struct worker_ctx *worker = timer->loop->data;
	lua_State *L = worker->engine->L;

	/* Retrieve callback and execute */
	lua_rawgeti(L, LUA_REGISTRYINDEX, (intptr_t) timer->data);
	lua_rawgeti(L, -1, 1);
	lua_pushinteger(L, (intptr_t) timer->data);
722
	int ret = execute_callback(L, 1);
723
	/* Free callback if not recurrent or an error */
724
	if (ret != 0 || (uv_timer_get_repeat(timer) == 0 && uv_is_active((uv_handle_t *)timer) == 0)) {
725 726 727
		if (!uv_is_closing((uv_handle_t *)timer)) {
			uv_close((uv_handle_t *)timer, (uv_close_cb) event_free);
		}
728 729 730
	}
}

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
static void event_fdcallback(uv_poll_t* handle, int status, int events)
{
	struct worker_ctx *worker = handle->loop->data;
	lua_State *L = worker->engine->L;

	/* Retrieve callback and execute */
	lua_rawgeti(L, LUA_REGISTRYINDEX, (intptr_t) handle->data);
	lua_rawgeti(L, -1, 1);
	lua_pushinteger(L, (intptr_t) handle->data);
	lua_pushinteger(L, status);
	lua_pushinteger(L, events);
	int ret = execute_callback(L, 3);
	/* Free callback if not recurrent or an error */
	if (ret != 0) {
		if (!uv_is_closing((uv_handle_t *)handle)) {
			uv_close((uv_handle_t *)handle, (uv_close_cb) event_free);
		}
	}
}

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
static int event_sched(lua_State *L, unsigned timeout, unsigned repeat)
{
	uv_timer_t *timer = malloc(sizeof(*timer));
	if (!timer) {
		format_error(L, "out of memory");
		lua_error(L);
	}

	/* Start timer with the reference */
	uv_loop_t *loop = uv_default_loop();
	uv_timer_init(loop, timer);
	int ret = uv_timer_start(timer, event_callback, timeout, repeat);
	if (ret != 0) {
		free(timer);
		format_error(L, "couldn't start the event");
		lua_error(L);
	}

	/* Save callback and timer in registry */
	lua_newtable(L);
	lua_pushvalue(L, 2);
	lua_rawseti(L, -2, 1);
	lua_pushlightuserdata(L, timer);
	lua_rawseti(L, -2, 2);
	int ref = luaL_ref(L, LUA_REGISTRYINDEX);

	/* Save reference to the timer */
	timer->data = (void *) (intptr_t)ref;
	lua_pushinteger(L, ref);
	return 1;
}

static int event_after(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
	if (n < 2 || !lua_isnumber(L, 1) || !lua_isfunction(L, 2)) {
		format_error(L, "expected 'after(number timeout, function)'");
		lua_error(L);
	}

	return event_sched(L, lua_tonumber(L, 1), 0);
}

static int event_recurrent(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
	if (n < 2 || !lua_isnumber(L, 1) || !lua_isfunction(L, 2)) {
		format_error(L, "expected 'recurrent(number interval, function)'");
		lua_error(L);
	}
	return event_sched(L, 0, lua_tonumber(L, 1));
}

static int event_cancel(lua_State *L)
{
	int n = lua_gettop(L);
	if (n < 1 || !lua_isnumber(L, 1)) {
		format_error(L, "expected 'cancel(number event)'");
		lua_error(L);
	}

	/* Fetch event if it exists */
	lua_rawgeti(L, LUA_REGISTRYINDEX, lua_tointeger(L, 1));
	if (!lua_istable(L, -1)) {
817 818
		lua_pushboolean(L, false);
		return 1;
819 820 821 822 823
	}

	/* Close the timer */
	lua_rawgeti(L, -1, 2);
	uv_handle_t *timer = lua_touserdata(L, -1);
824 825 826
	if (!uv_is_closing(timer)) {
		uv_close(timer, (uv_close_cb) event_free);
	}
827 828
	lua_pushboolean(L, true);
	return 1;
829 830
}

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
static int event_reschedule(lua_State *L)
{
	int n = lua_gettop(L);
	if (n < 2 || !lua_isnumber(L, 1) || !lua_isnumber(L, 2)) {
		format_error(L, "expected 'reschedule(number event, number timeout)'");
		lua_error(L);
	}

	/* Fetch event if it exists */
	lua_rawgeti(L, LUA_REGISTRYINDEX, lua_tointeger(L, 1));
	if (!lua_istable(L, -1)) {
		lua_pushboolean(L, false);
		return 1;
	}

	/* Reschedule the timer */
	lua_rawgeti(L, -1, 2);
	uv_handle_t *timer = lua_touserdata(L, -1);
	if (!uv_is_closing(timer)) {
		if (uv_is_active(timer)) {
			uv_timer_stop((uv_timer_t *)timer);
		}
		int ret = uv_timer_start((uv_timer_t *)timer, event_callback, lua_tointeger(L, 2), 0);
		if (ret != 0) {
			event_cancel(L);
			lua_pushboolean(L, false);
			return 1;
		}
	}
	lua_pushboolean(L, true);
	return 1;
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
static int event_fdwatch(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
	if (n < 2 || !lua_isnumber(L, 1) || !lua_isfunction(L, 2)) {
		format_error(L, "expected 'socket(number fd, function)'");
		lua_error(L);
	}

	uv_poll_t *handle = malloc(sizeof(*handle));
	if (!handle) {
		format_error(L, "out of memory");
		lua_error(L);
	}

	/* Start timer with the reference */
	int sock = lua_tonumber(L, 1);
	uv_loop_t *loop = uv_default_loop();
#if defined(__APPLE__) || defined(__FreeBSD__)
	/* libuv is buggy and fails to create poller for
	 * kqueue sockets as it can't be fcntl'd to non-blocking mode,
	 * so we pass it a copy of standard input and then
	 * switch it with real socket before starting the poller
	 */
	int decoy_fd = dup(STDIN_FILENO);
	int ret = uv_poll_init(loop, handle, decoy_fd);
	if (ret == 0) {
		handle->io_watcher.fd = sock;
	}
	close(decoy_fd);
#else
	int ret = uv_poll_init(loop, handle, sock);
#endif
	if (ret == 0) {
		ret = uv_poll_start(handle, UV_READABLE, event_fdcallback);
	}
	if (ret != 0) {
		free(handle);
		format_error(L, "couldn't start event poller");
		lua_error(L);
	}

	/* Save callback and timer in registry */
	lua_newtable(L);
	lua_pushvalue(L, 2);
	lua_rawseti(L, -2, 1);
	lua_pushlightuserdata(L, handle);
	lua_rawseti(L, -2, 2);
	int ref = luaL_ref(L, LUA_REGISTRYINDEX);

	/* Save reference to the timer */
	handle->data = (void *) (intptr_t)ref;
	lua_pushinteger(L, ref);
	return 1;
}

920 921 922 923 924 925
int lib_event(lua_State *L)
{
	static const luaL_Reg lib[] = {
		{ "after",      event_after },
		{ "recurrent",  event_recurrent },
		{ "cancel",     event_cancel },
926
		{ "socket",     event_fdwatch },
927
		{ "reschedule", event_reschedule },
928 929 930 931 932 933
		{ NULL, NULL }
	};

	register_lib(L, "event", lib);
	return 1;
}
934

935 936 937 938 939 940 941 942 943 944 945
/* @internal Call the Lua callback stored in baton. */
static void resolve_callback(struct worker_ctx *worker, struct kr_request *req, void *baton)
{
	assert(worker);
	assert(req);
	assert(baton);
	lua_State *L = worker->engine->L;
	intptr_t cb_ref = (intptr_t) baton;
	lua_rawgeti(L, LUA_REGISTRYINDEX, cb_ref);
	luaL_unref(L, LUA_REGISTRYINDEX, cb_ref);
	lua_pushlightuserdata(L, req->answer);
946 947
	lua_pushlightuserdata(L, req);
	(void) execute_callback(L, 2);
948 949
}

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
static int wrk_resolve(lua_State *L)
{
	struct worker_ctx *worker = wrk_luaget(L);
	if (!worker) {
		return 0;
	}
	/* Create query packet */
	knot_pkt_t *pkt = knot_pkt_new(NULL, KNOT_EDNS_MAX_UDP_PAYLOAD, NULL);
	if (!pkt) {
		lua_pushstring(L, strerror(ENOMEM));
		lua_error(L);
	}
	uint8_t dname[KNOT_DNAME_MAXLEN];
	knot_dname_from_str(dname, lua_tostring(L, 1), sizeof(dname));
	/* Check class and type */
	uint16_t rrtype = lua_tointeger(L, 2);
	if (!lua_isnumber(L, 2)) {
		lua_pushstring(L, "invalid RR type");
		lua_error(L);
	}
	uint16_t rrclass = lua_tointeger(L, 3);
	if (!lua_isnumber(L, 3)) { /* Default class is IN */
		rrclass = KNOT_CLASS_IN;
	}
	knot_pkt_put_question(pkt, dname, rrclass, rrtype);
	knot_wire_set_rd(pkt->wire);
976
	/* Add OPT RR */
977
	pkt->opt_rr = knot_rrset_copy(worker->engine->resolver.opt_rr, NULL);
978 979
	if (!pkt->opt_rr) {
		return kr_error(ENOMEM);
980
	}	
981
	/* Add completion callback */
982
	int ret = 0;
983
	unsigned options = lua_tointeger(L, 4);
984 985 986 987 988 989 990 991 992
	if (lua_isfunction(L, 5)) {
		/* Store callback in registry */
		lua_pushvalue(L, 5);
		int cb = luaL_ref(L, LUA_REGISTRYINDEX);
		ret = worker_resolve(worker, pkt, options, resolve_callback, (void *) (intptr_t)cb);
	} else {
		ret = worker_resolve(worker, pkt, options, NULL, NULL);
	}
	
993
	knot_rrset_free(&pkt->opt_rr, NULL);
994
	knot_pkt_free(&pkt);
995
	lua_pushboolean(L, ret == 0);
996 997 998
	return 1;
}

999 1000 1001 1002 1003
static inline double getseconds(uv_timeval_t *tv)
{
	return (double)tv->tv_sec + 0.000001*((double)tv->tv_usec);
}

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
/** Return worker statistics. */
static int wrk_stats(lua_State *L)
{
	struct worker_ctx *worker = wrk_luaget(L);
	if (!worker) {
		return 0;
	}
	lua_newtable(L);
	lua_pushnumber(L, worker->stats.concurrent);
	lua_setfield(L, -2, "concurrent");
	lua_pushnumber(L, worker->stats.udp);
	lua_setfield(L, -2, "udp");
	lua_pushnumber(L, worker->stats.tcp);
	lua_setfield(L, -2, "tcp");
1018 1019 1020 1021
	lua_pushnumber(L, worker->stats.ipv6);
	lua_setfield(L, -2, "ipv6");
	lua_pushnumber(L, worker->stats.ipv4);
	lua_setfield(L, -2, "ipv4");
1022 1023 1024 1025 1026 1027
	lua_pushnumber(L, worker->stats.queries);
	lua_setfield(L, -2, "queries");
	lua_pushnumber(L, worker->stats.dropped);
	lua_setfield(L, -2, "dropped");
	lua_pushnumber(L, worker->stats.timeout);
	lua_setfield(L, -2, "timeout");
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	/* Add subset of rusage that represents counters. */
	uv_rusage_t rusage;
	if (uv_getrusage(&rusage) == 0) {
		lua_pushnumber(L, getseconds(&rusage.ru_utime));
		lua_setfield(L, -2, "usertime");
		lua_pushnumber(L, getseconds(&rusage.ru_stime));
		lua_setfield(L, -2, "systime");
		lua_pushnumber(L, rusage.ru_majflt);
		lua_setfield(L, -2, "pagefaults");
		lua_pushnumber(L, rusage.ru_nswap);
		lua_setfield(L, -2, "swaps");
		lua_pushnumber(L, rusage.ru_nvcsw + rusage.ru_nivcsw);
		lua_setfield(L, -2, "csw");
	}
	/* Get RSS */
	size_t rss = 0;
	if (uv_resident_set_memory(&rss) == 0) {
		lua_pushnumber(L, rss);
		lua_setfield(L, -2, "rss");
	}
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
	return 1;
}

int lib_worker(lua_State *L)
{
	static const luaL_Reg lib[] = {
		{ "resolve",  wrk_resolve },
		{ "stats",    wrk_stats },
		{ NULL, NULL }
	};
	register_lib(L, "worker", lib);
	return 1;
}