aboutsummaryrefslogtreecommitdiff
path: root/builtin/game/auth.lua
blob: e7d502bb3f1c1f01525283884f59ed2928dc1f4a (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
-- Minetest: builtin/auth.lua

--
-- Builtin authentication handler
--

-- Make the auth object private, deny access to mods
local core_auth = core.auth
core.auth = nil

core.builtin_auth_handler = {
	get_auth = function(name)
		assert(type(name) == "string")
		local auth_entry = core_auth.read(name)
		-- If no such auth found, return nil
		if not auth_entry then
			return nil
		end
		-- Figure out what privileges the player should have.
		-- Take a copy of the privilege table
		local privileges = {}
		for priv, _ in pairs(auth_entry.privileges) do
			privileges[priv] = true
		end
		-- If singleplayer, give all privileges except those marked as give_to_singleplayer = false
		if core.is_singleplayer() then
			for priv, def in pairs(core.registered_privileges) do
				if def.give_to_singleplayer then
					privileges[priv] = true
				end
			end
		-- For the admin, give everything
		elseif name == core.settings:get("name") then
			for priv, def in pairs(core.registered_privileges) do
				if def.give_to_admin then
					privileges[priv] = true
				end
			end
		end
		-- All done
		return {
			password = auth_entry.password,
			privileges = privileges,
			last_login = auth_entry.last_login,
		}
	end,
	create_auth = function(name, password)
		assert(type(name) == "string")
		assert(type(password) == "string")
		core.log('info', "Built-in authentication handler adding player '"..name.."'")
		return core_auth.create({
			name = name,
			password = password,
			privileges = core.string_to_privs(core.settings:get("default_privs")),
			last_login = -1,  -- Defer login time calculation until record_login (called by on_joinplayer)
		})
	end,
	delete_auth = function(name)
		assert(type(name) == "string")
		local auth_entry = core_auth.read(name)
		if not auth_entry then
			return false
		end
		core.log('info', "Built-in authentication handler deleting player '"..name.."'")
		return core_auth.delete(name)
	end,
	set_password = function(name, password)
		assert(type(name) == "string")
		assert(type(password) == "string")
		local auth_entry = core_auth.read(name)
		if not auth_entry then
			core.builtin_auth_handler.create_auth(name, password)
		else
			core.log('info', "Built-in authentication handler setting password of player '"..name.."'")
			auth_entry.password = password
			core_auth.save(auth_entry)
		end
		return true
	end,
	set_privileges = function(name, privileges)
		assert(type(name) == "string")
		assert(type(privileges) == "table")
		local auth_entry = core_auth.read(name)
		if not auth_entry then
			auth_entry = core.builtin_auth_handler.create_auth(name,
				core.get_password_hash(name,
					core.settings:get("default_password")))
		end

		auth_entry.privileges = privileges

		core_auth.save(auth_entry)

		-- Run grant callbacks
		for priv, _ in pairs(privileges) do
			if not auth_entry.privileges[priv] then
				core.run_priv_callbacks(name, priv, nil, "grant")
			end
		end

		-- Run revoke callbacks
		for priv, _ in pairs(auth_entry.privileges) do
			if not privileges[priv] then
				core.run_priv_callbacks(name, priv, nil, "revoke")
			end
		end
		core.notify_authentication_modified(name)
	end,
	reload = function()
		core_auth.reload()
		return true
	end,
	record_login = function(name)
		assert(type(name) == "string")
		local auth_entry = core_auth.read(name)
		assert(auth_entry)
		auth_entry.last_login = os.time()
		core_auth.save(auth_entry)
	end,
	iterate = function()
		local names = {}
		local nameslist = core_auth.list_names()
		for k,v in pairs(nameslist) do
			names[v] = true
		end
		return pairs(names)
	end,
}

core.register_on_prejoinplayer(function(name, ip)
	if core.registered_auth_handler ~= nil then
		return -- Don't do anything if custom auth handler registered
	end
	local auth_entry = core_auth.read(name)
	if auth_entry ~= nil then
		return
	end

	local name_lower = name:lower()
	for k in core.builtin_auth_handler.iterate() do
		if k:lower() == name_lower then
			return string.format("\nCannot create new player called '%s'. "..
					"Another account called '%s' is already registered. "..
					"Please check the spelling if it's your account "..
					"or use a different nickname.", name, k)
		end
	end
end)

--
-- Authentication API
--

function core.register_authentication_handler(handler)
	if core.registered_auth_handler then
		error("Add-on authentication handler already registered by "..core.registered_auth_handler_modname)
	end
	core.registered_auth_handler = handler
	core.registered_auth_handler_modname = core.get_current_modname()
	handler.mod_origin = core.registered_auth_handler_modname
end

function core.get_auth_handler()
	return core.registered_auth_handler or core.builtin_auth_handler
end

local function auth_pass(name)
	return function(...)
		local auth_handler = core.get_auth_handler()
		if auth_handler[name] then
			return auth_handler[name](...)
		end
		return false
	end
end

core.set_player_password = auth_pass("set_password")
core.set_player_privs    = auth_pass("set_privileges")
core.remove_player_auth  = auth_pass("delete_auth")
core.auth_reload         = auth_pass("reload")

local record_login = auth_pass("record_login")
core.register_on_joinplayer(function(player)
	record_login(player:get_player_name())
end)
span>string, lua_CFunction> &lib : m_libs) { lua_pushcfunction(L, lib.second); lua_pushstring(L, lib.first.c_str()); lua_call(L, 1, 0); } } void ScriptApiBase::loadMod(const std::string &script_path, const std::string &mod_name) { ModNameStorer mod_name_storer(getStack(), mod_name); loadScript(script_path); } void ScriptApiBase::loadScript(const std::string &script_path) { verbosestream << "Loading and running script from " << script_path << std::endl; lua_State *L = getStack(); int error_handler = PUSH_ERROR_HANDLER(L); bool ok; if (m_secure) { ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str()); } else { ok = !luaL_loadfile(L, script_path.c_str()); } ok = ok && !lua_pcall(L, 0, 0, error_handler); if (!ok) { std::string error_msg = readParam<std::string>(L, -1); lua_pop(L, 2); // Pop error message and error handler throw ModError("Failed to load and run script from " + script_path + ":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } #ifndef SERVER void ScriptApiBase::loadModFromMemory(const std::string &mod_name) { ModNameStorer mod_name_storer(getStack(), mod_name); const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua"); const std::string display_filename = mod_name + ":init.lua"; if(init_filename == NULL) throw ModError("Mod:\"" + mod_name + "\" lacks init.lua"); verbosestream << "Loading and running script " << display_filename << std::endl; lua_State *L = getStack(); int error_handler = PUSH_ERROR_HANDLER(L); bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str()); if (ok) ok = !lua_pcall(L, 0, 0, error_handler); if (!ok) { std::string error_msg = luaL_checkstring(L, -1); lua_pop(L, 2); // Pop error message and error handler throw ModError("Failed to load and run mod \"" + mod_name + "\":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } #endif // Push the list of callbacks (a lua table). // Then push nargs arguments. // Then call this function, which // - runs the callbacks // - replaces the table and arguments with the return value, // computed depending on mode // This function must only be called with scriptlock held (i.e. inside of a // code block with SCRIPTAPI_PRECHECKHEADER declared) void ScriptApiBase::runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn) { #ifdef SCRIPTAPI_LOCK_DEBUG assert(m_lock_recursion_count > 0); #endif lua_State *L = getStack(); FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments"); // Insert error handler PUSH_ERROR_HANDLER(L); int error_handler = lua_gettop(L) - nargs - 1; lua_insert(L, error_handler); // Insert run_callbacks between error handler and table lua_getglobal(L, "core"); lua_getfield(L, -1, "run_callbacks"); lua_remove(L, -2); lua_insert(L, error_handler + 1); // Insert mode after table lua_pushnumber(L, (int)mode); lua_insert(L, error_handler + 3); // Stack now looks like this: // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n> int result = lua_pcall(L, nargs + 2, 1, error_handler); if (result != 0) scriptError(result, fxn); lua_remove(L, error_handler); } void ScriptApiBase::realityCheck() { int top = lua_gettop(m_luastack); if (top >= 30) { dstream << "Stack is over 30:" << std::endl; stackDump(dstream); std::string traceback = script_get_backtrace(m_luastack); throw LuaError("Stack is over 30 (reality check)\n" + traceback); } } void ScriptApiBase::scriptError(int result, const char *fxn) { script_error(getStack(), result, m_last_run_mod.c_str(), fxn); } void ScriptApiBase::stackDump(std::ostream &o) { int top = lua_gettop(m_luastack); for (int i = 1; i <= top; i++) { /* repeat for each level */ int t = lua_type(m_luastack, i); switch (t) { case LUA_TSTRING: /* strings */ o << "\"" << readParam<std::string>(m_luastack, i) << "\""; break; case LUA_TBOOLEAN: /* booleans */ o << (readParam<bool>(m_luastack, i) ? "true" : "false"); break; case LUA_TNUMBER: /* numbers */ { char buf[10]; porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i)); o << buf; break; } default: /* other values */ o << lua_typename(m_luastack, t); break; } o << " "; } o << std::endl; } void ScriptApiBase::setOriginDirect(const char *origin) { m_last_run_mod = origin ? origin : "??"; } void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) { #ifdef SCRIPTAPI_DEBUG lua_State *L = getStack(); m_last_run_mod = lua_istable(L, index) ? getstringfield_default(L, index, "mod_origin", "") : ""; //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str()); #endif } void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl; // Create object on stack ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack int object = lua_gettop(L); // Get core.object_refs table lua_getglobal(L, "core"); lua_getfield(L, -1, "object_refs"); luaL_checktype(L, -1, LUA_TTABLE); int objectstable = lua_gettop(L); // object_refs[id] = object lua_pushnumber(L, cobj->getId()); // Push id lua_pushvalue(L, object); // Copy object to top of stack lua_settable(L, objectstable); } void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl; // Get core.object_refs table lua_getglobal(L, "core"); lua_getfield(L, -1, "object_refs"); luaL_checktype(L, -1, LUA_TTABLE); int objectstable = lua_gettop(L); // Get object_refs[id] lua_pushnumber(L, cobj->getId()); // Push id lua_gettable(L, objectstable); // Set object reference to NULL ObjectRef::set_null(L); lua_pop(L, 1); // pop object // Set object_refs[id] = nil lua_pushnumber(L, cobj->getId()); // Push id lua_pushnil(L); lua_settable(L, objectstable); } // Creates a new anonymous reference if cobj=NULL or id=0 void ScriptApiBase::objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj) { if (cobj == NULL || cobj->getId() == 0) { ObjectRef::create(L, cobj); } else { push_objectRef(L, cobj->getId()); if (cobj->isGone()) warningstream << "ScriptApiBase::objectrefGetOrCreate(): " << "Pushing ObjectRef to removed/deactivated object" << ", this is probably a bug." << std::endl; } } void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason) { if (reason.lua_reference >= 0) { lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference); luaL_unref(L, LUA_REGISTRYINDEX, reason.lua_reference); } else lua_newtable(L); lua_pushstring(L, reason.getTypeAsString().c_str()); lua_setfield(L, -2, "type"); lua_pushstring(L, reason.from_mod ? "mod" : "engine"); lua_setfield(L, -2, "from"); if (reason.object) { objectrefGetOrCreate(L, reason.object); lua_setfield(L, -2, "object"); } } Server* ScriptApiBase::getServer() { return dynamic_cast<Server *>(m_gamedef); } #ifndef SERVER Client* ScriptApiBase::getClient() { return dynamic_cast<Client *>(m_gamedef); } #endif