[CSM] Implement minetest.get_csm_restrictions()
[oweals/minetest.git] / src / script / cpp_api / s_base.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 "cpp_api/s_base.h"
21 #include "cpp_api/s_internal.h"
22 #include "cpp_api/s_security.h"
23 #include "lua_api/l_object.h"
24 #include "common/c_converter.h"
25 #include "serverobject.h"
26 #include "filesys.h"
27 #include "content/mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "client/client.h"
33 #endif
34
35
36 extern "C" {
37 #include "lualib.h"
38 #if USE_LUAJIT
39         #include "luajit.h"
40 #endif
41 }
42
43 #include <cstdio>
44 #include <cstdarg>
45 #include "script/common/c_content.h"
46 #include "content_sao.h"
47 #include <sstream>
48
49
50 class ModNameStorer
51 {
52 private:
53         lua_State *L;
54 public:
55         ModNameStorer(lua_State *L_, const std::string &mod_name):
56                 L(L_)
57         {
58                 // Store current mod name in registry
59                 lua_pushstring(L, mod_name.c_str());
60                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
61         }
62         ~ModNameStorer()
63         {
64                 // Clear current mod name from registry
65                 lua_pushnil(L);
66                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
67         }
68 };
69
70
71 /*
72         ScriptApiBase
73 */
74
75 ScriptApiBase::ScriptApiBase(ScriptingType type):
76                 m_type(type)
77 {
78 #ifdef SCRIPTAPI_LOCK_DEBUG
79         m_lock_recursion_count = 0;
80 #endif
81
82         m_luastack = luaL_newstate();
83         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
84
85         lua_atpanic(m_luastack, &luaPanic);
86
87         if (m_type == ScriptingType::Client)
88                 clientOpenLibs(m_luastack);
89         else
90                 luaL_openlibs(m_luastack);
91
92         // Make the ScriptApiBase* accessible to ModApiBase
93         lua_pushlightuserdata(m_luastack, this);
94         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
95
96         // Add and save an error handler
97         lua_getglobal(m_luastack, "debug");
98         lua_getfield(m_luastack, -1, "traceback");
99         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
100         lua_pop(m_luastack, 1); // pop debug
101
102         // If we are using LuaJIT add a C++ wrapper function to catch
103         // exceptions thrown in Lua -> C++ calls
104 #if USE_LUAJIT
105         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
106         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
107         lua_pop(m_luastack, 1);
108 #endif
109
110         // Add basic globals
111         lua_newtable(m_luastack);
112         lua_setglobal(m_luastack, "core");
113
114         if (m_type == ScriptingType::Client)
115                 lua_pushstring(m_luastack, "/");
116         else
117                 lua_pushstring(m_luastack, DIR_DELIM);
118         lua_setglobal(m_luastack, "DIR_DELIM");
119
120         lua_pushstring(m_luastack, porting::getPlatformName());
121         lua_setglobal(m_luastack, "PLATFORM");
122
123         // Make sure Lua uses the right locale
124         setlocale(LC_NUMERIC, "C");
125 }
126
127 ScriptApiBase::~ScriptApiBase()
128 {
129         lua_close(m_luastack);
130 }
131
132 int ScriptApiBase::luaPanic(lua_State *L)
133 {
134         std::ostringstream oss;
135         oss << "LUA PANIC: unprotected error in call to Lua API ("
136                 << readParam<std::string>(L, -1) << ")";
137         FATAL_ERROR(oss.str().c_str());
138         // NOTREACHED
139         return 0;
140 }
141
142 void ScriptApiBase::clientOpenLibs(lua_State *L)
143 {
144         static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
145                 { "", luaopen_base },
146                 { LUA_TABLIBNAME,  luaopen_table   },
147                 { LUA_OSLIBNAME,   luaopen_os      },
148                 { LUA_STRLIBNAME,  luaopen_string  },
149                 { LUA_MATHLIBNAME, luaopen_math    },
150                 { LUA_DBLIBNAME,   luaopen_debug   },
151 #if USE_LUAJIT
152                 { LUA_JITLIBNAME,  luaopen_jit     },
153 #endif
154         };
155
156         for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
157             lua_pushcfunction(L, lib.second);
158             lua_pushstring(L, lib.first.c_str());
159             lua_call(L, 1, 0);
160         }
161 }
162
163 void ScriptApiBase::loadMod(const std::string &script_path,
164                 const std::string &mod_name)
165 {
166         ModNameStorer mod_name_storer(getStack(), mod_name);
167
168         loadScript(script_path);
169 }
170
171 void ScriptApiBase::loadScript(const std::string &script_path)
172 {
173         verbosestream << "Loading and running script from " << script_path << std::endl;
174
175         lua_State *L = getStack();
176
177         int error_handler = PUSH_ERROR_HANDLER(L);
178
179         bool ok;
180         if (m_secure) {
181                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
182         } else {
183                 ok = !luaL_loadfile(L, script_path.c_str());
184         }
185         ok = ok && !lua_pcall(L, 0, 0, error_handler);
186         if (!ok) {
187                 std::string error_msg = readParam<std::string>(L, -1);
188                 lua_pop(L, 2); // Pop error message and error handler
189                 throw ModError("Failed to load and run script from " +
190                                 script_path + ":\n" + error_msg);
191         }
192         lua_pop(L, 1); // Pop error handler
193 }
194
195 #ifndef SERVER
196 void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
197 {
198         ModNameStorer mod_name_storer(getStack(), mod_name);
199
200         sanity_check(m_type == ScriptingType::Client);
201
202         const std::string init_filename = mod_name + ":init.lua";
203         const std::string chunk_name = "@" + init_filename;
204
205         const std::string *contents = getClient()->getModFile(init_filename);
206         if (!contents)
207                 throw ModError("Mod \"" + mod_name + "\" lacks init.lua");
208
209         verbosestream << "Loading and running script " << chunk_name << std::endl;
210
211         lua_State *L = getStack();
212
213         int error_handler = PUSH_ERROR_HANDLER(L);
214
215         bool ok = ScriptApiSecurity::safeLoadString(L, *contents, chunk_name.c_str());
216         if (ok)
217                 ok = !lua_pcall(L, 0, 0, error_handler);
218         if (!ok) {
219                 std::string error_msg = luaL_checkstring(L, -1);
220                 lua_pop(L, 2); // Pop error message and error handler
221                 throw ModError("Failed to load and run mod \"" +
222                                 mod_name + "\":\n" + error_msg);
223         }
224         lua_pop(L, 1); // Pop error handler
225 }
226 #endif
227
228 // Push the list of callbacks (a lua table).
229 // Then push nargs arguments.
230 // Then call this function, which
231 // - runs the callbacks
232 // - replaces the table and arguments with the return value,
233 //     computed depending on mode
234 // This function must only be called with scriptlock held (i.e. inside of a
235 // code block with SCRIPTAPI_PRECHECKHEADER declared)
236 void ScriptApiBase::runCallbacksRaw(int nargs,
237                 RunCallbacksMode mode, const char *fxn)
238 {
239 #ifndef SERVER
240         // Hard fail for bad guarded callbacks
241         // Only run callbacks when the scripting enviroment is loaded
242         FATAL_ERROR_IF(m_type == ScriptingType::Client &&
243                         !getClient()->modsLoaded(), fxn);
244 #endif
245
246 #ifdef SCRIPTAPI_LOCK_DEBUG
247         assert(m_lock_recursion_count > 0);
248 #endif
249         lua_State *L = getStack();
250         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
251
252         // Insert error handler
253         PUSH_ERROR_HANDLER(L);
254         int error_handler = lua_gettop(L) - nargs - 1;
255         lua_insert(L, error_handler);
256
257         // Insert run_callbacks between error handler and table
258         lua_getglobal(L, "core");
259         lua_getfield(L, -1, "run_callbacks");
260         lua_remove(L, -2);
261         lua_insert(L, error_handler + 1);
262
263         // Insert mode after table
264         lua_pushnumber(L, (int)mode);
265         lua_insert(L, error_handler + 3);
266
267         // Stack now looks like this:
268         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
269
270         int result = lua_pcall(L, nargs + 2, 1, error_handler);
271         if (result != 0)
272                 scriptError(result, fxn);
273
274         lua_remove(L, error_handler);
275 }
276
277 void ScriptApiBase::realityCheck()
278 {
279         int top = lua_gettop(m_luastack);
280         if (top >= 30) {
281                 dstream << "Stack is over 30:" << std::endl;
282                 stackDump(dstream);
283                 std::string traceback = script_get_backtrace(m_luastack);
284                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
285         }
286 }
287
288 void ScriptApiBase::scriptError(int result, const char *fxn)
289 {
290         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
291 }
292
293 void ScriptApiBase::stackDump(std::ostream &o)
294 {
295         int top = lua_gettop(m_luastack);
296         for (int i = 1; i <= top; i++) {  /* repeat for each level */
297                 int t = lua_type(m_luastack, i);
298                 switch (t) {
299                         case LUA_TSTRING:  /* strings */
300                                 o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
301                                 break;
302                         case LUA_TBOOLEAN:  /* booleans */
303                                 o << (readParam<bool>(m_luastack, i) ? "true" : "false");
304                                 break;
305                         case LUA_TNUMBER:  /* numbers */ {
306                                 char buf[10];
307                                 porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
308                                 o << buf;
309                                 break;
310                         }
311                         default:  /* other values */
312                                 o << lua_typename(m_luastack, t);
313                                 break;
314                 }
315                 o << " ";
316         }
317         o << std::endl;
318 }
319
320 void ScriptApiBase::setOriginDirect(const char *origin)
321 {
322         m_last_run_mod = origin ? origin : "??";
323 }
324
325 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
326 {
327 #ifdef SCRIPTAPI_DEBUG
328         lua_State *L = getStack();
329
330         m_last_run_mod = lua_istable(L, index) ?
331                 getstringfield_default(L, index, "mod_origin", "") : "";
332         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
333 #endif
334 }
335
336 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
337 {
338         SCRIPTAPI_PRECHECKHEADER
339         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
340
341         // Create object on stack
342         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
343         int object = lua_gettop(L);
344
345         // Get core.object_refs table
346         lua_getglobal(L, "core");
347         lua_getfield(L, -1, "object_refs");
348         luaL_checktype(L, -1, LUA_TTABLE);
349         int objectstable = lua_gettop(L);
350
351         // object_refs[id] = object
352         lua_pushnumber(L, cobj->getId()); // Push id
353         lua_pushvalue(L, object); // Copy object to top of stack
354         lua_settable(L, objectstable);
355 }
356
357 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
358 {
359         SCRIPTAPI_PRECHECKHEADER
360         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
361
362         // Get core.object_refs table
363         lua_getglobal(L, "core");
364         lua_getfield(L, -1, "object_refs");
365         luaL_checktype(L, -1, LUA_TTABLE);
366         int objectstable = lua_gettop(L);
367
368         // Get object_refs[id]
369         lua_pushnumber(L, cobj->getId()); // Push id
370         lua_gettable(L, objectstable);
371         // Set object reference to NULL
372         ObjectRef::set_null(L);
373         lua_pop(L, 1); // pop object
374
375         // Set object_refs[id] = nil
376         lua_pushnumber(L, cobj->getId()); // Push id
377         lua_pushnil(L);
378         lua_settable(L, objectstable);
379 }
380
381 // Creates a new anonymous reference if cobj=NULL or id=0
382 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
383                 ServerActiveObject *cobj)
384 {
385         if (cobj == NULL || cobj->getId() == 0) {
386                 ObjectRef::create(L, cobj);
387         } else {
388                 push_objectRef(L, cobj->getId());
389                 if (cobj->isGone())
390                         warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
391                                         << "Pushing ObjectRef to removed/deactivated object"
392                                         << ", this is probably a bug." << std::endl;
393         }
394 }
395
396 void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
397 {
398         if (reason.hasLuaReference())
399                 lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
400         else
401                 lua_newtable(L);
402
403         lua_getfield(L, -1, "type");
404         bool has_type = (bool)lua_isstring(L, -1);
405         lua_pop(L, 1);
406         if (!has_type) {
407                 lua_pushstring(L, reason.getTypeAsString().c_str());
408                 lua_setfield(L, -2, "type");
409         }
410
411         lua_pushstring(L, reason.from_mod ? "mod" : "engine");
412         lua_setfield(L, -2, "from");
413
414         if (reason.object) {
415                 objectrefGetOrCreate(L, reason.object);
416                 lua_setfield(L, -2, "object");
417         }
418         if (!reason.node.empty()) {
419                 lua_pushstring(L, reason.node.c_str());
420                 lua_setfield(L, -2, "node");
421         }
422 }
423
424 Server* ScriptApiBase::getServer()
425 {
426         return dynamic_cast<Server *>(m_gamedef);
427 }
428 #ifndef SERVER
429 Client* ScriptApiBase::getClient()
430 {
431         return dynamic_cast<Client *>(m_gamedef);
432 }
433 #endif