Allow damage for attached objects, add attach/detach callbacks (#6786)
[oweals/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 "lua_api/l_settings.h"
23 #include "common/c_converter.h"
24 #include "common/c_content.h"
25 #include "cpp_api/s_async.h"
26 #include "serialization.h"
27 #include <json/json.h>
28 #include "cpp_api/s_security.h"
29 #include "porting.h"
30 #include "convert_json.h"
31 #include "debug.h"
32 #include "log.h"
33 #include "tool.h"
34 #include "filesys.h"
35 #include "settings.h"
36 #include "util/auth.h"
37 #include "util/base64.h"
38 #include "config.h"
39 #include "version.h"
40 #include "util/hex.h"
41 #include "util/sha1.h"
42 #include <algorithm>
43
44
45 // log([level,] text)
46 // Writes a line to the logger.
47 // The one-argument version logs to infostream.
48 // The two-argument version accepts a log level.
49 // Either the special case "deprecated" for deprecation notices, or any specified in
50 // Logger::stringToLevel(name).
51 int ModApiUtil::l_log(lua_State *L)
52 {
53         NO_MAP_LOCK_REQUIRED;
54         std::string text;
55         LogLevel level = LL_NONE;
56         if (lua_isnone(L, 2)) {
57                 text = luaL_checkstring(L, 1);
58         } else {
59                 std::string name = luaL_checkstring(L, 1);
60                 text = luaL_checkstring(L, 2);
61                 if (name == "deprecated") {
62                         log_deprecated(L, text);
63                         return 0;
64                 }
65                 level = Logger::stringToLevel(name);
66                 if (level == LL_MAX) {
67                         warningstream << "Tried to log at unknown level '" << name
68                                 << "'.  Defaulting to \"none\"." << std::endl;
69                         level = LL_NONE;
70                 }
71         }
72         g_logger.log(level, text);
73         return 0;
74 }
75
76 // get_us_time()
77 int ModApiUtil::l_get_us_time(lua_State *L)
78 {
79         NO_MAP_LOCK_REQUIRED;
80         lua_pushnumber(L, porting::getTimeUs());
81         return 1;
82 }
83
84 // parse_json(str[, nullvalue])
85 int ModApiUtil::l_parse_json(lua_State *L)
86 {
87         NO_MAP_LOCK_REQUIRED;
88
89         const char *jsonstr = luaL_checkstring(L, 1);
90
91         // Use passed nullvalue or default to nil
92         int nullindex = 2;
93         if (lua_isnone(L, nullindex)) {
94                 lua_pushnil(L);
95                 nullindex = lua_gettop(L);
96         }
97
98         Json::Value root;
99
100         {
101                 std::istringstream stream(jsonstr);
102
103                 Json::CharReaderBuilder builder;
104                 builder.settings_["collectComments"] = false;
105                 std::string errs;
106
107                 if (!Json::parseFromStream(builder, stream, &root, &errs)) {
108                         errorstream << "Failed to parse json data " << errs << std::endl;
109                         size_t jlen = strlen(jsonstr);
110                         if (jlen > 100) {
111                                 errorstream << "Data (" << jlen
112                                         << " bytes) printed to warningstream." << std::endl;
113                                 warningstream << "data: \"" << jsonstr << "\"" << std::endl;
114                         } else {
115                                 errorstream << "data: \"" << jsonstr << "\"" << std::endl;
116                         }
117                         lua_pushnil(L);
118                         return 1;
119                 }
120         }
121
122         if (!push_json_value(L, root, nullindex)) {
123                 errorstream << "Failed to parse json data, "
124                         << "depth exceeds lua stack limit" << std::endl;
125                 errorstream << "data: \"" << jsonstr << "\"" << std::endl;
126                 lua_pushnil(L);
127         }
128         return 1;
129 }
130
131 // write_json(data[, styled]) -> string or nil and error message
132 int ModApiUtil::l_write_json(lua_State *L)
133 {
134         NO_MAP_LOCK_REQUIRED;
135
136         bool styled = false;
137         if (!lua_isnone(L, 2)) {
138                 styled = lua_toboolean(L, 2);
139                 lua_pop(L, 1);
140         }
141
142         Json::Value root;
143         try {
144                 read_json_value(L, root, 1);
145         } catch (SerializationError &e) {
146                 lua_pushnil(L);
147                 lua_pushstring(L, e.what());
148                 return 2;
149         }
150
151         std::string out;
152         if (styled) {
153                 out = root.toStyledString();
154         } else {
155                 out = fastWriteJson(root);
156         }
157         lua_pushlstring(L, out.c_str(), out.size());
158         return 1;
159 }
160
161 // get_dig_params(groups, tool_capabilities)
162 int ModApiUtil::l_get_dig_params(lua_State *L)
163 {
164         NO_MAP_LOCK_REQUIRED;
165         ItemGroupList groups;
166         read_groups(L, 1, groups);
167         ToolCapabilities tp = read_tool_capabilities(L, 2);
168         push_dig_params(L, getDigParams(groups, &tp));
169         return 1;
170 }
171
172 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
173 int ModApiUtil::l_get_hit_params(lua_State *L)
174 {
175         NO_MAP_LOCK_REQUIRED;
176         std::unordered_map<std::string, int> groups;
177         read_groups(L, 1, groups);
178         ToolCapabilities tp = read_tool_capabilities(L, 2);
179         if(lua_isnoneornil(L, 3))
180                 push_hit_params(L, getHitParams(groups, &tp));
181         else
182                 push_hit_params(L, getHitParams(groups, &tp,
183                                         luaL_checknumber(L, 3)));
184         return 1;
185 }
186
187 // check_password_entry(name, entry, password)
188 int ModApiUtil::l_check_password_entry(lua_State *L)
189 {
190         NO_MAP_LOCK_REQUIRED;
191         std::string name = luaL_checkstring(L, 1);
192         std::string entry = luaL_checkstring(L, 2);
193         std::string password = luaL_checkstring(L, 3);
194
195         if (base64_is_valid(entry)) {
196                 std::string hash = translate_password(name, password);
197                 lua_pushboolean(L, hash == entry);
198                 return 1;
199         }
200
201         std::string salt;
202         std::string verifier;
203
204         if (!decode_srp_verifier_and_salt(entry, &verifier, &salt)) {
205                 // invalid format
206                 warningstream << "Invalid password format for " << name << std::endl;
207                 lua_pushboolean(L, false);
208                 return 1;
209         }
210         std::string gen_verifier = generate_srp_verifier(name, password, salt);
211
212         lua_pushboolean(L, gen_verifier == verifier);
213         return 1;
214 }
215
216 // get_password_hash(name, raw_password)
217 int ModApiUtil::l_get_password_hash(lua_State *L)
218 {
219         NO_MAP_LOCK_REQUIRED;
220         std::string name = luaL_checkstring(L, 1);
221         std::string raw_password = luaL_checkstring(L, 2);
222         std::string hash = translate_password(name, raw_password);
223         lua_pushstring(L, hash.c_str());
224         return 1;
225 }
226
227 // is_yes(arg)
228 int ModApiUtil::l_is_yes(lua_State *L)
229 {
230         NO_MAP_LOCK_REQUIRED;
231
232         lua_getglobal(L, "tostring"); // function to be called
233         lua_pushvalue(L, 1); // 1st argument
234         lua_call(L, 1, 1); // execute function
235         std::string str(lua_tostring(L, -1)); // get result
236         lua_pop(L, 1);
237
238         bool yes = is_yes(str);
239         lua_pushboolean(L, yes);
240         return 1;
241 }
242
243 // get_builtin_path()
244 int ModApiUtil::l_get_builtin_path(lua_State *L)
245 {
246         NO_MAP_LOCK_REQUIRED;
247
248         std::string path = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM;
249         lua_pushstring(L, path.c_str());
250
251         return 1;
252 }
253
254 // compress(data, method, level)
255 int ModApiUtil::l_compress(lua_State *L)
256 {
257         NO_MAP_LOCK_REQUIRED;
258
259         size_t size;
260         const char *data = luaL_checklstring(L, 1, &size);
261
262         int level = -1;
263         if (!lua_isnone(L, 3) && !lua_isnil(L, 3))
264                 level = luaL_checknumber(L, 3);
265
266         std::ostringstream os;
267         compressZlib(std::string(data, size), os, level);
268
269         std::string out = os.str();
270
271         lua_pushlstring(L, out.data(), out.size());
272         return 1;
273 }
274
275 // decompress(data, method)
276 int ModApiUtil::l_decompress(lua_State *L)
277 {
278         NO_MAP_LOCK_REQUIRED;
279
280         size_t size;
281         const char *data = luaL_checklstring(L, 1, &size);
282
283         std::istringstream is(std::string(data, size));
284         std::ostringstream os;
285         decompressZlib(is, os);
286
287         std::string out = os.str();
288
289         lua_pushlstring(L, out.data(), out.size());
290         return 1;
291 }
292
293 // encode_base64(string)
294 int ModApiUtil::l_encode_base64(lua_State *L)
295 {
296         NO_MAP_LOCK_REQUIRED;
297
298         size_t size;
299         const char *data = luaL_checklstring(L, 1, &size);
300
301         std::string out = base64_encode((const unsigned char *)(data), size);
302
303         lua_pushlstring(L, out.data(), out.size());
304         return 1;
305 }
306
307 // decode_base64(string)
308 int ModApiUtil::l_decode_base64(lua_State *L)
309 {
310         NO_MAP_LOCK_REQUIRED;
311
312         size_t size;
313         const char *data = luaL_checklstring(L, 1, &size);
314
315         std::string out = base64_decode(std::string(data, size));
316
317         lua_pushlstring(L, out.data(), out.size());
318         return 1;
319 }
320
321 // mkdir(path)
322 int ModApiUtil::l_mkdir(lua_State *L)
323 {
324         NO_MAP_LOCK_REQUIRED;
325         const char *path = luaL_checkstring(L, 1);
326         CHECK_SECURE_PATH(L, path, true);
327         lua_pushboolean(L, fs::CreateAllDirs(path));
328         return 1;
329 }
330
331 // get_dir_list(path, is_dir)
332 int ModApiUtil::l_get_dir_list(lua_State *L)
333 {
334         NO_MAP_LOCK_REQUIRED;
335         const char *path = luaL_checkstring(L, 1);
336         bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all
337         bool list_dirs = lua_toboolean(L, 2); // true: list dirs, false: list files
338
339         CHECK_SECURE_PATH(L, path, false);
340
341         std::vector<fs::DirListNode> list = fs::GetDirListing(path);
342
343         int index = 0;
344         lua_newtable(L);
345
346         for (const fs::DirListNode &dln : list) {
347                 if (list_all || list_dirs == dln.dir) {
348                         lua_pushstring(L, dln.name.c_str());
349                         lua_rawseti(L, -2, ++index);
350                 }
351         }
352
353         return 1;
354 }
355
356 // safe_file_write(path, content)
357 int ModApiUtil::l_safe_file_write(lua_State *L)
358 {
359         NO_MAP_LOCK_REQUIRED;
360         const char *path = luaL_checkstring(L, 1);
361         size_t size;
362         const char *content = luaL_checklstring(L, 2, &size);
363
364         CHECK_SECURE_PATH(L, path, true);
365
366         bool ret = fs::safeWriteToFile(path, std::string(content, size));
367         lua_pushboolean(L, ret);
368
369         return 1;
370 }
371
372 // request_insecure_environment()
373 int ModApiUtil::l_request_insecure_environment(lua_State *L)
374 {
375         NO_MAP_LOCK_REQUIRED;
376
377         // Just return _G if security is disabled
378         if (!ScriptApiSecurity::isSecure(L)) {
379                 lua_getglobal(L, "_G");
380                 return 1;
381         }
382
383         // We have to make sure that this function is being called directly by
384         // a mod, otherwise a malicious mod could override this function and
385         // steal its return value.
386         lua_Debug info;
387         // Make sure there's only one item below this function on the stack...
388         if (lua_getstack(L, 2, &info)) {
389                 return 0;
390         }
391         FATAL_ERROR_IF(!lua_getstack(L, 1, &info), "lua_getstack() failed");
392         FATAL_ERROR_IF(!lua_getinfo(L, "S", &info), "lua_getinfo() failed");
393         // ...and that that item is the main file scope.
394         if (strcmp(info.what, "main") != 0) {
395                 return 0;
396         }
397
398         // Get mod name
399         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
400         if (!lua_isstring(L, -1)) {
401                 return 0;
402         }
403
404         // Check secure.trusted_mods
405         const char *mod_name = lua_tostring(L, -1);
406         std::string trusted_mods = g_settings->get("secure.trusted_mods");
407         trusted_mods.erase(std::remove_if(trusted_mods.begin(),
408                         trusted_mods.end(), static_cast<int(*)(int)>(&std::isspace)),
409                         trusted_mods.end());
410         std::vector<std::string> mod_list = str_split(trusted_mods, ',');
411         if (std::find(mod_list.begin(), mod_list.end(), mod_name) ==
412                         mod_list.end()) {
413                 return 0;
414         }
415
416         // Push insecure environment
417         lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
418         return 1;
419 }
420
421 // get_version()
422 int ModApiUtil::l_get_version(lua_State *L)
423 {
424         lua_createtable(L, 0, 3);
425         int table = lua_gettop(L);
426
427         lua_pushstring(L, PROJECT_NAME_C);
428         lua_setfield(L, table, "project");
429
430         lua_pushstring(L, g_version_string);
431         lua_setfield(L, table, "string");
432
433         if (strcmp(g_version_string, g_version_hash) != 0) {
434                 lua_pushstring(L, g_version_hash);
435                 lua_setfield(L, table, "hash");
436         }
437
438         return 1;
439 }
440
441 int ModApiUtil::l_sha1(lua_State *L)
442 {
443         NO_MAP_LOCK_REQUIRED;
444         size_t size;
445         const char *data = luaL_checklstring(L, 1, &size);
446         bool hex = !lua_isboolean(L, 2) || !lua_toboolean(L, 2);
447
448         // Compute actual checksum of data
449         std::string data_sha1;
450         {
451                 SHA1 ctx;
452                 ctx.addBytes(data, size);
453                 unsigned char *data_tmpdigest = ctx.getDigest();
454                 data_sha1.assign((char*) data_tmpdigest, 20);
455                 free(data_tmpdigest);
456         }
457
458         if (hex) {
459                 std::string sha1_hex = hex_encode(data_sha1);
460                 lua_pushstring(L, sha1_hex.c_str());
461         } else {
462                 lua_pushlstring(L, data_sha1.data(), data_sha1.size());
463         }
464
465         return 1;
466 }
467
468 void ModApiUtil::Initialize(lua_State *L, int top)
469 {
470         API_FCT(log);
471
472         API_FCT(get_us_time);
473
474         API_FCT(parse_json);
475         API_FCT(write_json);
476
477         API_FCT(get_dig_params);
478         API_FCT(get_hit_params);
479
480         API_FCT(check_password_entry);
481         API_FCT(get_password_hash);
482
483         API_FCT(is_yes);
484
485         API_FCT(get_builtin_path);
486
487         API_FCT(compress);
488         API_FCT(decompress);
489
490         API_FCT(mkdir);
491         API_FCT(get_dir_list);
492         API_FCT(safe_file_write);
493
494         API_FCT(request_insecure_environment);
495
496         API_FCT(encode_base64);
497         API_FCT(decode_base64);
498
499         API_FCT(get_version);
500         API_FCT(sha1);
501
502         LuaSettings::create(L, g_settings, g_settings_path);
503         lua_setfield(L, top, "settings");
504 }
505
506 void ModApiUtil::InitializeClient(lua_State *L, int top)
507 {
508         API_FCT(log);
509
510         API_FCT(get_us_time);
511
512         API_FCT(parse_json);
513         API_FCT(write_json);
514
515         API_FCT(is_yes);
516
517         API_FCT(compress);
518         API_FCT(decompress);
519
520         API_FCT(encode_base64);
521         API_FCT(decode_base64);
522
523         API_FCT(get_version);
524         API_FCT(sha1);
525 }
526
527 void ModApiUtil::InitializeAsync(lua_State *L, int top)
528 {
529         API_FCT(log);
530
531         API_FCT(get_us_time);
532
533         API_FCT(parse_json);
534         API_FCT(write_json);
535
536         API_FCT(is_yes);
537
538         API_FCT(get_builtin_path);
539
540         API_FCT(compress);
541         API_FCT(decompress);
542
543         API_FCT(mkdir);
544         API_FCT(get_dir_list);
545
546         API_FCT(encode_base64);
547         API_FCT(decode_base64);
548
549         API_FCT(get_version);
550         API_FCT(sha1);
551
552         LuaSettings::create(L, g_settings, g_settings_path);
553         lua_setfield(L, top, "settings");
554 }
555