summaryrefslogtreecommitdiffstats
path: root/daemon/bindings/modules.c
blob: acae270ce7a95af0c0b2492b2a6e9824aad0708e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*  Copyright (C) CZ.NIC, z.s.p.o. <knot-resolver@labs.nic.cz>
 *  SPDX-License-Identifier: GPL-3.0-or-later
 */

#include "daemon/bindings/impl.h"


/** List loaded modules */
static int mod_list(lua_State *L)
{
	const module_array_t * const modules = &the_worker->engine->modules;
	lua_newtable(L);
	for (unsigned i = 0; i < modules->len; ++i) {
		struct kr_module *module = modules->at[i];
		lua_pushstring(L, module->name);
		lua_rawseti(L, -2, i + 1);
	}
	return 1;
}

/** Load module. */
static int mod_load(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
	if (n != 1 || !lua_isstring(L, 1))
		lua_error_p(L, "expected 'load(string name)'");
	/* Parse precedence declaration */
	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, " ");
	/* Load engine module */
	int ret = engine_register(the_worker->engine, name, precedence, ref);
	free(declaration);
	if (ret != 0) {
		if (ret == kr_error(EIDRM)) {
			lua_error_p(L, "referenced module not found");
		} else {
			lua_error_maybe(L, ret);
		}
	}

	lua_pushboolean(L, 1);
	return 1;
}

/** Unload module. */
static int mod_unload(lua_State *L)
{
	/* Check parameters */
	int n = lua_gettop(L);
	if (n != 1 || !lua_isstring(L, 1))
		lua_error_p(L, "expected 'unload(string name)'");
	/* Unload engine module */
	int ret = engine_unregister(the_worker->engine, lua_tostring(L, 1));
	lua_error_maybe(L, ret);

	lua_pushboolean(L, 1);
	return 1;
}

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

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