]> git.lizzy.rs Git - minetest.git/blob - src/script/lua_api/l_util.cpp
3f7e15acfa79e5fd3cf9bd1934094fce41b00929
[minetest.git] / src / script / lua_api / l_util.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "lua_api/l_util.h"
21 #include "lua_api/l_internal.h"
22 #include "common/c_converter.h"
23 #include "common/c_content.h"
24 #include "cpp_api/s_async.h"
25 #include "serialization.h"
26 #include "json/json.h"
27 #include "cpp_api/s_security.h"
28 #include "areastore.h"
29 #include "porting.h"
30 #include "log.h"
31 #include "tool.h"
32 #include "filesys.h"
33 #include "settings.h"
34 #include "util/auth.h"
35 #include <algorithm>
36
37 // log([level,] text)
38 // Writes a line to the logger.
39 // The one-argument version logs to infostream.
40 // The two-argument version accepts a log level.
41 // Either the special case "deprecated" for deprecation notices, or any specified in
42 // Logger::stringToLevel(name).
43 int ModApiUtil::l_log(lua_State *L)
44 {
45         NO_MAP_LOCK_REQUIRED;
46         std::string text;
47         LogLevel level = LL_NONE;
48         if (lua_isnone(L, 2)) {
49                 text = luaL_checkstring(L, 1);
50         } else {
51                 std::string name = luaL_checkstring(L, 1);
52                 text = luaL_checkstring(L, 2);
53                 if (name == "deprecated") {
54                         log_deprecated(L, text);
55                         return 0;
56                 }
57                 level = Logger::stringToLevel(name);
58                 if (level == LL_MAX) {
59                         warningstream << "Tried to log at unknown level '" << name
60                                 << "'.  Defaulting to \"none\"." << std::endl;
61                         level = LL_NONE;
62                 }
63         }
64         g_logger.log(level, text);
65         return 0;
66 }
67
68 // get_us_time()
69 int ModApiUtil::l_get_us_time(lua_State *L)
70 {
71         NO_MAP_LOCK_REQUIRED;
72         lua_pushnumber(L, porting::getTimeUs());
73         return 1;
74 }
75
76 #define CHECK_SECURE_SETTING(L, name) \
77         if (name.compare(0, 7, "secure.") == 0) {\
78                 lua_pushliteral(L, "Attempt to set secure setting.");\
79                 lua_error(L);\
80         }
81
82 // setting_set(name, value)
83 int ModApiUtil::l_setting_set(lua_State *L)
84 {
85         NO_MAP_LOCK_REQUIRED;
86         std::string name = luaL_checkstring(L, 1);
87         std::string value = luaL_checkstring(L, 2);
88         CHECK_SECURE_SETTING(L, name);
89         g_settings->set(name, value);
90         return 0;
91 }
92
93 // setting_get(name)
94 int ModApiUtil::l_setting_get(lua_State *L)
95 {
96         NO_MAP_LOCK_REQUIRED;
97         const char *name = luaL_checkstring(L, 1);
98         try{
99                 std::string value = g_settings->get(name);
100                 lua_pushstring(L, value.c_str());
101         } catch(SettingNotFoundException &e){
102                 lua_pushnil(L);
103         }
104         return 1;
105 }
106
107 // setting_setbool(name)
108 int ModApiUtil::l_setting_setbool(lua_State *L)
109 {
110         NO_MAP_LOCK_REQUIRED;
111         std::string name = luaL_checkstring(L, 1);
112         bool value = lua_toboolean(L, 2);
113         CHECK_SECURE_SETTING(L, name);
114         g_settings->setBool(name, value);
115         return 0;
116 }
117
118 // setting_getbool(name)
119 int ModApiUtil::l_setting_getbool(lua_State *L)
120 {
121         NO_MAP_LOCK_REQUIRED;
122         const char *name = luaL_checkstring(L, 1);
123         try{
124                 bool value = g_settings->getBool(name);
125                 lua_pushboolean(L, value);
126         } catch(SettingNotFoundException &e){
127                 lua_pushnil(L);
128         }
129         return 1;
130 }
131
132 // setting_save()
133 int ModApiUtil::l_setting_save(lua_State *L)
134 {
135         NO_MAP_LOCK_REQUIRED;
136         if(g_settings_path != "")
137                 g_settings->updateConfigFile(g_settings_path.c_str());
138         return 0;
139 }
140
141 // parse_json(str[, nullvalue])
142 int ModApiUtil::l_parse_json(lua_State *L)
143 {
144         NO_MAP_LOCK_REQUIRED;
145
146         const char *jsonstr = luaL_checkstring(L, 1);
147
148         // Use passed nullvalue or default to nil
149         int nullindex = 2;
150         if (lua_isnone(L, nullindex)) {
151                 lua_pushnil(L);
152                 nullindex = lua_gettop(L);
153         }
154
155         Json::Value root;
156
157         {
158                 Json::Reader reader;
159                 std::istringstream stream(jsonstr);
160
161                 if (!reader.parse(stream, root)) {
162                         errorstream << "Failed to parse json data "
163                                 << reader.getFormattedErrorMessages();
164                         errorstream << "data: \"" << jsonstr << "\""
165                                 << std::endl;
166                         lua_pushnil(L);
167                         return 1;
168                 }
169         }
170
171         if (!push_json_value(L, root, nullindex)) {
172                 errorstream << "Failed to parse json data, "
173                         << "depth exceeds lua stack limit" << std::endl;
174                 errorstream << "data: \"" << jsonstr << "\"" << std::endl;
175                 lua_pushnil(L);
176         }
177         return 1;
178 }
179
180 // write_json(data[, styled]) -> string or nil and error message
181 int ModApiUtil::l_write_json(lua_State *L)
182 {
183         NO_MAP_LOCK_REQUIRED;
184
185         bool styled = false;
186         if (!lua_isnone(L, 2)) {
187                 styled = lua_toboolean(L, 2);
188                 lua_pop(L, 1);
189         }
190
191         Json::Value root;
192         try {
193                 read_json_value(L, root, 1);
194         } catch (SerializationError &e) {
195                 lua_pushnil(L);
196                 lua_pushstring(L, e.what());
197                 return 2;
198         }
199
200         std::string out;
201         if (styled) {
202                 Json::StyledWriter writer;
203                 out = writer.write(root);
204         } else {
205                 Json::FastWriter writer;
206                 out = writer.write(root);
207         }
208         lua_pushlstring(L, out.c_str(), out.size());
209         return 1;
210 }
211
212 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
213 int ModApiUtil::l_get_dig_params(lua_State *L)
214 {
215         NO_MAP_LOCK_REQUIRED;
216         std::map<std::string, int> groups;
217         read_groups(L, 1, groups);
218         ToolCapabilities tp = read_tool_capabilities(L, 2);
219         if(lua_isnoneornil(L, 3))
220                 push_dig_params(L, getDigParams(groups, &tp));
221         else
222                 push_dig_params(L, getDigParams(groups, &tp,
223                                         luaL_checknumber(L, 3)));
224         return 1;
225 }
226
227 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
228 int ModApiUtil::l_get_hit_params(lua_State *L)
229 {
230         NO_MAP_LOCK_REQUIRED;
231         std::map<std::string, int> groups;
232         read_groups(L, 1, groups);
233         ToolCapabilities tp = read_tool_capabilities(L, 2);
234         if(lua_isnoneornil(L, 3))
235                 push_hit_params(L, getHitParams(groups, &tp));
236         else
237                 push_hit_params(L, getHitParams(groups, &tp,
238                                         luaL_checknumber(L, 3)));
239         return 1;
240 }
241
242 // get_password_hash(name, raw_password)
243 int ModApiUtil::l_get_password_hash(lua_State *L)
244 {
245         NO_MAP_LOCK_REQUIRED;
246         std::string name = luaL_checkstring(L, 1);
247         std::string raw_password = luaL_checkstring(L, 2);
248         std::string hash = translatePassword(name, raw_password);
249         lua_pushstring(L, hash.c_str());
250         return 1;
251 }
252
253 // is_yes(arg)
254 int ModApiUtil::l_is_yes(lua_State *L)
255 {
256         NO_MAP_LOCK_REQUIRED;
257
258         lua_getglobal(L, "tostring"); // function to be called
259         lua_pushvalue(L, 1); // 1st argument
260         lua_call(L, 1, 1); // execute function
261         std::string str(lua_tostring(L, -1)); // get result
262         lua_pop(L, 1);
263
264         bool yes = is_yes(str);
265         lua_pushboolean(L, yes);
266         return 1;
267 }
268
269 int ModApiUtil::l_get_builtin_path(lua_State *L)
270 {
271         NO_MAP_LOCK_REQUIRED;
272
273         std::string path = porting::path_share + DIR_DELIM + "builtin";
274         lua_pushstring(L, path.c_str());
275         return 1;
276 }
277
278 // compress(data, method, level)
279 int ModApiUtil::l_compress(lua_State *L)
280 {
281         NO_MAP_LOCK_REQUIRED;
282
283         size_t size;
284         const char *data = luaL_checklstring(L, 1, &size);
285
286         int level = -1;
287         if (!lua_isnone(L, 3) && !lua_isnil(L, 3))
288                 level = luaL_checknumber(L, 3);
289
290         std::ostringstream os;
291         compressZlib(std::string(data, size), os, level);
292
293         std::string out = os.str();
294
295         lua_pushlstring(L, out.data(), out.size());
296         return 1;
297 }
298
299 // decompress(data, method)
300 int ModApiUtil::l_decompress(lua_State *L)
301 {
302         NO_MAP_LOCK_REQUIRED;
303
304         size_t size;
305         const char *data = luaL_checklstring(L, 1, &size);
306
307         std::istringstream is(std::string(data, size));
308         std::ostringstream os;
309         decompressZlib(is, os);
310
311         std::string out = os.str();
312
313         lua_pushlstring(L, out.data(), out.size());
314         return 1;
315 }
316
317 // mkdir(path)
318 int ModApiUtil::l_mkdir(lua_State *L)
319 {
320         NO_MAP_LOCK_REQUIRED;
321         const char *path = luaL_checkstring(L, 1);
322         CHECK_SECURE_PATH_OPTIONAL(L, path);
323         lua_pushboolean(L, fs::CreateAllDirs(path));
324         return 1;
325 }
326
327 // get_dir_list(path, is_dir)
328 int ModApiUtil::l_get_dir_list(lua_State *L)
329 {
330         NO_MAP_LOCK_REQUIRED;
331         const char *path = luaL_checkstring(L, 1);
332         short is_dir = lua_isboolean(L, 2) ? lua_toboolean(L, 2) : -1;
333
334         CHECK_SECURE_PATH_OPTIONAL(L, path);
335
336         std::vector<fs::DirListNode> list = fs::GetDirListing(path);
337
338         int index = 0;
339         lua_newtable(L);
340
341         for (size_t i = 0; i < list.size(); i++) {
342                 if (is_dir == -1 || is_dir == list[i].dir) {
343                         lua_pushstring(L, list[i].name.c_str());
344                         lua_rawseti(L, -2, ++index);
345                 }
346         }
347
348         return 1;
349 }
350
351 int ModApiUtil::l_request_insecure_environment(lua_State *L)
352 {
353         NO_MAP_LOCK_REQUIRED;
354         if (!ScriptApiSecurity::isSecure(L)) {
355                 lua_getglobal(L, "_G");
356                 return 1;
357         }
358         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
359         if (!lua_isstring(L, -1)) {
360                 lua_pushnil(L);
361                 return 1;
362         }
363         const char *mod_name = lua_tostring(L, -1);
364         std::string trusted_mods = g_settings->get("secure.trusted_mods");
365         std::vector<std::string> mod_list = str_split(trusted_mods, ',');
366         if (std::find(mod_list.begin(), mod_list.end(), mod_name) == mod_list.end()) {
367                 lua_pushnil(L);
368                 return 1;
369         }
370         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
371         return 1;
372 }
373
374
375 void ModApiUtil::Initialize(lua_State *L, int top)
376 {
377         API_FCT(log);
378
379         API_FCT(get_us_time);
380
381         API_FCT(setting_set);
382         API_FCT(setting_get);
383         API_FCT(setting_setbool);
384         API_FCT(setting_getbool);
385         API_FCT(setting_save);
386
387         API_FCT(parse_json);
388         API_FCT(write_json);
389
390         API_FCT(get_dig_params);
391         API_FCT(get_hit_params);
392
393         API_FCT(get_password_hash);
394
395         API_FCT(is_yes);
396
397         API_FCT(get_builtin_path);
398
399         API_FCT(compress);
400         API_FCT(decompress);
401
402         API_FCT(mkdir);
403         API_FCT(get_dir_list);
404
405         API_FCT(request_insecure_environment);
406 }
407
408 void ModApiUtil::InitializeAsync(AsyncEngine& engine)
409 {
410         ASYNC_API_FCT(log);
411
412         ASYNC_API_FCT(get_us_time);
413
414         //ASYNC_API_FCT(setting_set);
415         ASYNC_API_FCT(setting_get);
416         //ASYNC_API_FCT(setting_setbool);
417         ASYNC_API_FCT(setting_getbool);
418         //ASYNC_API_FCT(setting_save);
419
420         ASYNC_API_FCT(parse_json);
421         ASYNC_API_FCT(write_json);
422
423         ASYNC_API_FCT(is_yes);
424
425         ASYNC_API_FCT(get_builtin_path);
426
427         ASYNC_API_FCT(compress);
428         ASYNC_API_FCT(decompress);
429
430         ASYNC_API_FCT(mkdir);
431         ASYNC_API_FCT(get_dir_list);
432 }
433