aboutsummaryrefslogtreecommitdiff
path: root/builtin/game/auth.lua
blob: 46fe3d342778c50e15dac1d681ac7929a543a45d (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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
-- Minetest: builtin/auth.lua

--
-- Authentication handler
--

function core.string_to_privs(str, delim)
	assert(type(str) == "string")
	delim = delim or ','
	local privs = {}
	for _, priv in pairs(string.split(str, delim)) do
		privs[priv:trim()] = true
	end
	return privs
end

function core.privs_to_string(privs, delim)
	assert(type(privs) == "table")
	delim = delim or ','
	local list = {}
	for priv, bool in pairs(privs) do
		if bool then
			list[#list + 1] = priv
		end
	end
	return table.concat(list, delim)
end

assert(core.string_to_privs("a,b").b == true)
assert(core.privs_to_string({a=true,b=true}) == "a,b")

core.auth_file_path = core.get_worldpath().."/auth.txt"
core.auth_table = {}

local function read_auth_file()
	local newtable = {}
	local file, errmsg = io.open(core.auth_file_path, 'rb')
	if not file then
		core.log("info", core.auth_file_path.." could not be opened for reading ("..errmsg.."); assuming new world")
		return
	end
	for line in file:lines() do
		if line ~= "" then
			local fields = line:split(":", true)
			local name, password, privilege_string, last_login = unpack(fields)
			last_login = tonumber(last_login)
			if not (name and password and privilege_string) then
				error("Invalid line in auth.txt: "..dump(line))
			end
			local privileges = core.string_to_privs(privilege_string)
			newtable[name] = {password=password, privileges=privileges, last_login=last_login}
		end
	end
	io.close(file)
	core.auth_table = newtable
	core.notify_authentication_modified()
end

local function save_auth_file()
	local newtable = {}
	-- Check table for validness before attempting to save
	for name, stuff in pairs(core.auth_table) do
		assert(type(name) == "string")
		assert(name ~= "")
		assert(type(stuff) == "table")
		assert(type(stuff.password) == "string")
		assert(type(stuff.privileges) == "table")
		assert(stuff.last_login == nil or type(stuff.last_login) == "number")
	end
	local file, errmsg = io.open(core.auth_file_path, 'w+b')
	if not file then
		error(core.auth_file_path.." could not be opened for writing: "..errmsg)
	end
	for name, stuff in pairs(core.auth_table) do
		local priv_string = core.privs_to_string(stuff.privileges)
		local parts = {name, stuff.password, priv_string, stuff.last_login or ""}
		file:write(table.concat(parts, ":").."\n")
	end
	io.close(file)
end

read_auth_file()

core.builtin_auth_handler = {
	get_auth = function(name)
		assert(type(name) == "string")
		-- Figure out what password to use for a new player (singleplayer
		-- always has an empty password, otherwise use default, which is
		-- usually empty too)
		local new_password_hash = ""
		-- If not in authentication table, return nil
		if not core.auth_table[name] 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(core.auth_table[name].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.setting_get("name") then
			for priv, def in pairs(core.registered_privileges) do
				privileges[priv] = true
			end
		end
		-- All done
		return {
			password = core.auth_table[name].password,
			privileges = privileges,
			-- Is set to nil if unknown
			last_login = core.auth_table[name].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.."'")
		core.auth_table[name] = {
			password = password,
			privileges = core.string_to_privs(core.setting_get("default_privs")),
			last_login = os.time(),
		}
		save_auth_file()
	end,
	set_password = function(name, password)
		assert(type(name) == "string")
		assert(type(password) == "string")
		if not core.auth_table[name] then
			core.builtin_auth_handler.create_auth(name, password)
		else
			core.log('info', "Built-in authentication handler setting password of player '"..name.."'")
			core.auth_table[name].password = password
			save_auth_file()
		end
		return true
	end,
	set_privileges = function(name, privileges)
		assert(type(name) == "string")
		assert(type(privileges) == "table")
		if not core.auth_table[name] then
			core.builtin_auth_handler.create_auth(name,
				core.get_password_hash(name,
					core.setting_get("default_password")))
		end
		core.auth_table[name].privileges = privileges
		core.notify_authentication_modified(name)
		save_auth_file()
	end,
	reload = function()
		read_auth_file()
		return true
	end,
	record_login = function(name)
		assert(type(name) == "string")
		assert(core.auth_table[name]).last_login = os.time()
		save_auth_file()
	end,
}

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.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)

core.register_on_prejoinplayer(function(name, ip)
	local auth = core.auth_table
	if auth[name] ~= nil then
		return
	end

	local name_lower = name:lower()
	for k in pairs(auth) 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)
1 || version > 3) throw SerializationError("unsupported ItemDefinition version"); type = (enum ItemType)readU8(is); name = deSerializeString(is); description = deSerializeString(is); inventory_image = deSerializeString(is); wield_image = deSerializeString(is); wield_scale = readV3F1000(is); stack_max = readS16(is); usable = readU8(is); liquids_pointable = readU8(is); std::string tool_capabilities_s = deSerializeString(is); if(!tool_capabilities_s.empty()) { std::istringstream tmp_is(tool_capabilities_s, std::ios::binary); tool_capabilities = new ToolCapabilities; tool_capabilities->deSerialize(tmp_is); } groups.clear(); u32 groups_size = readU16(is); for(u32 i=0; i<groups_size; i++){ std::string name = deSerializeString(is); int value = readS16(is); groups[name] = value; } if(version == 1){ // We cant be sure that node_placement_prediction is send in version 1 try{ node_placement_prediction = deSerializeString(is); }catch(SerializationError &e) {}; // Set the old default sound sound_place.name = "default_place_node"; sound_place.gain = 0.5; } else if(version >= 2) { node_placement_prediction = deSerializeString(is); //deserializeSimpleSoundSpec(sound_place, is); sound_place.name = deSerializeString(is); sound_place.gain = readF1000(is); } if(version == 3) { range = readF1000(is); } // If you add anything here, insert it primarily inside the try-catch // block to not need to increase the version. try { sound_place_failed.name = deSerializeString(is); sound_place_failed.gain = readF1000(is); } catch(SerializationError &e) {}; } /* CItemDefManager */ // SUGG: Support chains of aliases? class CItemDefManager: public IWritableItemDefManager { #ifndef SERVER struct ClientCached { video::ITexture *inventory_texture; scene::IMesh *wield_mesh; ClientCached(): inventory_texture(NULL), wield_mesh(NULL) {} }; #endif public: CItemDefManager() { #ifndef SERVER m_main_thread = thr_get_current_thread_id(); #endif clear(); } virtual ~CItemDefManager() { #ifndef SERVER const std::vector<ClientCached*> &values = m_clientcached.getValues(); for(std::vector<ClientCached*>::const_iterator i = values.begin(); i != values.end(); ++i) { ClientCached *cc = *i; if (cc->wield_mesh) cc->wield_mesh->drop(); delete cc; } #endif for (std::map<std::string, ItemDefinition*>::iterator iter = m_item_definitions.begin(); iter != m_item_definitions.end(); ++iter) { delete iter->second; } m_item_definitions.clear(); } virtual const ItemDefinition& get(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); // Get the definition std::map<std::string, ItemDefinition*>::const_iterator i; i = m_item_definitions.find(name); if(i == m_item_definitions.end()) i = m_item_definitions.find("unknown"); assert(i != m_item_definitions.end()); return *(i->second); } virtual std::string getAlias(const std::string &name) const { StringMap::const_iterator it = m_aliases.find(name); if (it != m_aliases.end()) return it->second; return name; } virtual std::set<std::string> getAll() const { std::set<std::string> result; for(std::map<std::string, ItemDefinition *>::const_iterator it = m_item_definitions.begin(); it != m_item_definitions.end(); ++it) { result.insert(it->first); } for (StringMap::const_iterator it = m_aliases.begin(); it != m_aliases.end(); ++it) { result.insert(it->first); } return result; } virtual bool isKnown(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); // Get the definition std::map<std::string, ItemDefinition*>::const_iterator i; return m_item_definitions.find(name) != m_item_definitions.end(); } #ifndef SERVER public: ClientCached* createClientCachedDirect(const std::string &name, IGameDef *gamedef) const { infostream<<"Lazily creating item texture and mesh for \"" <<name<<"\""<<std::endl; // This is not thread-safe sanity_check(thr_is_current_thread(m_main_thread)); // Skip if already in cache ClientCached *cc = NULL; m_clientcached.get(name, &cc); if(cc) return cc; ITextureSource *tsrc = gamedef->getTextureSource(); const ItemDefinition &def = get(name); // Create new ClientCached cc = new ClientCached(); // Create an inventory texture cc->inventory_texture = NULL; if(def.inventory_image != "") cc->inventory_texture = tsrc->getTexture(def.inventory_image); ItemStack item = ItemStack(); item.name = def.name; scene::IMesh *mesh = getItemMesh(gamedef, item); cc->wield_mesh = mesh; // Put in cache m_clientcached.set(name, cc); return cc; } ClientCached* getClientCached(const std::string &name, IGameDef *gamedef) const { ClientCached *cc = NULL; m_clientcached.get(name, &cc); if(cc) return cc; if(thr_is_current_thread(m_main_thread)) { return createClientCachedDirect(name, gamedef); } else { // We're gonna ask the result to be put into here static ResultQueue<std::string, ClientCached*, u8, u8> result_queue; // Throw a request in m_get_clientcached_queue.add(name, 0, 0, &result_queue); try{ while(true) { // Wait result for a second GetResult<std::string, ClientCached*, u8, u8> result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } } catch(ItemNotFoundException &e) { errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl; return &m_dummy_clientcached; } } } // Get item inventory texture virtual video::ITexture* getInventoryTexture(const std::string &name, IGameDef *gamedef) const { ClientCached *cc = getClientCached(name, gamedef); if(!cc) return NULL; return cc->inventory_texture; } // Get item wield mesh virtual scene::IMesh* getWieldMesh(const std::string &name, IGameDef *gamedef) const { ClientCached *cc = getClientCached(name, gamedef); if(!cc) return NULL; return cc->wield_mesh; } #endif void clear() { for(std::map<std::string, ItemDefinition*>::const_iterator i = m_item_definitions.begin(); i != m_item_definitions.end(); ++i) { delete i->second; } m_item_definitions.clear(); m_aliases.clear(); // Add the four builtin items: // "" is the hand // "unknown" is returned whenever an undefined item // is accessed (is also the unknown node) // "air" is the air node // "ignore" is the ignore node ItemDefinition* hand_def = new ItemDefinition; hand_def->name = ""; hand_def->wield_image = "wieldhand.png"; hand_def->tool_capabilities = new ToolCapabilities; m_item_definitions.insert(std::make_pair("", hand_def)); ItemDefinition* unknown_def = new ItemDefinition; unknown_def->type = ITEM_NODE; unknown_def->name = "unknown"; m_item_definitions.insert(std::make_pair("unknown", unknown_def)); ItemDefinition* air_def = new ItemDefinition; air_def->type = ITEM_NODE; air_def->name = "air"; m_item_definitions.insert(std::make_pair("air", air_def)); ItemDefinition* ignore_def = new ItemDefinition; ignore_def->type = ITEM_NODE; ignore_def->name = "ignore"; m_item_definitions.insert(std::make_pair("ignore", ignore_def)); } virtual void registerItem(const ItemDefinition &def) { verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl; // Ensure that the "" item (the hand) always has ToolCapabilities if(def.name == "") FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities"); if(m_item_definitions.count(def.name) == 0) m_item_definitions[def.name] = new ItemDefinition(def); else *(m_item_definitions[def.name]) = def; // Remove conflicting alias if it exists bool alias_removed = (m_aliases.erase(def.name) != 0); if(alias_removed) infostream<<"ItemDefManager: erased alias "<<def.name <<" because item was defined"<<std::endl; } virtual void unregisterItem(const std::string &name) { verbosestream<<"ItemDefManager: unregistering \""<<name<<"\""<<std::endl; delete m_item_definitions[name]; m_item_definitions.erase(name); } virtual void registerAlias(const std::string &name, const std::string &convert_to) { if (m_item_definitions.find(name) == m_item_definitions.end()) { verbosestream<<"ItemDefManager: setting alias "<<name <<" -> "<<convert_to<<std::endl; m_aliases[name] = convert_to; } } void serialize(std::ostream &os, u16 protocol_version) { writeU8(os, 0); // version u16 count = m_item_definitions.size(); writeU16(os, count); for (std::map<std::string, ItemDefinition *>::const_iterator it = m_item_definitions.begin(); it != m_item_definitions.end(); ++it) { ItemDefinition *def = it->second; // Serialize ItemDefinition and write wrapped in a string std::ostringstream tmp_os(std::ios::binary); def->serialize(tmp_os, protocol_version); os << serializeString(tmp_os.str()); } writeU16(os, m_aliases.size()); for (StringMap::const_iterator it = m_aliases.begin(); it != m_aliases.end(); ++it) { os << serializeString(it->first); os << serializeString(it->second); } } void deSerialize(std::istream &is) { // Clear everything clear(); // Deserialize int version = readU8(is); if(version != 0) throw SerializationError("unsupported ItemDefManager version"); u16 count = readU16(is); for(u16 i=0; i<count; i++) { // Deserialize a string and grab an ItemDefinition from it std::istringstream tmp_is(deSerializeString(is), std::ios::binary); ItemDefinition def; def.deSerialize(tmp_is); // Register registerItem(def); } u16 num_aliases = readU16(is); for(u16 i=0; i<num_aliases; i++) { std::string name = deSerializeString(is); std::string convert_to = deSerializeString(is); registerAlias(name, convert_to); } } void processQueue(IGameDef *gamedef) { #ifndef SERVER //NOTE this is only thread safe for ONE consumer thread! while(!m_get_clientcached_queue.empty()) { GetRequest<std::string, ClientCached*, u8, u8> request = m_get_clientcached_queue.pop(); m_get_clientcached_queue.pushResult(request, createClientCachedDirect(request.key, gamedef)); } #endif } private: // Key is name std::map<std::string, ItemDefinition*> m_item_definitions; // Aliases StringMap m_aliases; #ifndef SERVER // The id of the thread that is allowed to use irrlicht directly threadid_t m_main_thread; // A reference to this can be returned when nothing is found, to avoid NULLs mutable ClientCached m_dummy_clientcached; // Cached textures and meshes mutable MutexedMap<std::string, ClientCached*> m_clientcached; // Queued clientcached fetches (to be processed by the main thread) mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue; #endif }; IWritableItemDefManager* createItemDefManager() { return new CItemDefManager(); }