diff options
author | Elias Fleckenstein <eliasfleckenstein@web.de> | 2020-11-04 16:19:54 +0100 |
---|---|---|
committer | Elias Fleckenstein <eliasfleckenstein@web.de> | 2020-11-04 16:19:54 +0100 |
commit | ad148587dcf5244c2d2011dba339786c765c54c4 (patch) | |
tree | bdd914121cd326da2ed26679838878e3edffc841 /src/script/cpp_api | |
parent | 1145b05ea0bda87dc0827821385810eced08f774 (diff) | |
download | dragonfireclient-ad148587dcf5244c2d2011dba339786c765c54c4.tar.xz |
Make Lint Happy
Diffstat (limited to 'src/script/cpp_api')
25 files changed, 629 insertions, 711 deletions
diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index 5f1f9297e..d0e520ae9 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -42,7 +42,6 @@ AsyncEngine::~AsyncEngine() workerThread->stop(); } - // Wake up all threads for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin(); it != workerThreads.end(); ++it) { @@ -77,16 +76,16 @@ void AsyncEngine::initialize(unsigned int numEngines) initDone = true; for (unsigned int i = 0; i < numEngines; i++) { - AsyncWorkerThread *toAdd = new AsyncWorkerThread(this, - std::string("AsyncWorker-") + itos(i)); + AsyncWorkerThread *toAdd = new AsyncWorkerThread( + this, std::string("AsyncWorker-") + itos(i)); workerThreads.push_back(toAdd); toAdd->start(); } } /******************************************************************************/ -unsigned int AsyncEngine::queueAsyncJob(const std::string &func, - const std::string ¶ms) +unsigned int AsyncEngine::queueAsyncJob( + const std::string &func, const std::string ¶ms) { jobQueueMutex.lock(); LuaJobInfo toAdd; @@ -158,7 +157,8 @@ void AsyncEngine::step(lua_State *L) } /******************************************************************************/ -void AsyncEngine::pushFinishedJobs(lua_State* L) { +void AsyncEngine::pushFinishedJobs(lua_State *L) +{ // Result Table MutexAutoLock l(resultQueueMutex); @@ -170,7 +170,7 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) { LuaJobInfo jobDone = resultQueue.front(); resultQueue.pop_front(); - lua_createtable(L, 0, 2); // Pre-allocate space for two map fields + lua_createtable(L, 0, 2); // Pre-allocate space for two map fields int top_lvl2 = lua_gettop(L); lua_pushstring(L, "jobid"); @@ -179,7 +179,7 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) { lua_pushstring(L, "retval"); lua_pushlstring(L, jobDone.serializedResult.data(), - jobDone.serializedResult.size()); + jobDone.serializedResult.size()); lua_settable(L, top_lvl2); lua_rawseti(L, top, index++); @@ -187,7 +187,7 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) { } /******************************************************************************/ -void AsyncEngine::prepareEnvironment(lua_State* L, int top) +void AsyncEngine::prepareEnvironment(lua_State *L, int top) { for (StateInitializer &stateInitializer : stateInitializers) { stateInitializer(L, top); @@ -195,11 +195,10 @@ void AsyncEngine::prepareEnvironment(lua_State* L, int top) } /******************************************************************************/ -AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher, - const std::string &name) : - Thread(name), - ScriptApiBase(ScriptingType::Async), - jobDispatcher(jobDispatcher) +AsyncWorkerThread::AsyncWorkerThread( + AsyncEngine *jobDispatcher, const std::string &name) : + Thread(name), + ScriptApiBase(ScriptingType::Async), jobDispatcher(jobDispatcher) { lua_State *L = getStack(); @@ -221,7 +220,7 @@ AsyncWorkerThread::~AsyncWorkerThread() } /******************************************************************************/ -void* AsyncWorkerThread::run() +void *AsyncWorkerThread::run() { lua_State *L = getStack(); @@ -229,8 +228,8 @@ void* AsyncWorkerThread::run() try { loadScript(script); } catch (const ModError &e) { - errorstream << "Execution of async base environment failed: " - << e.what() << std::endl; + errorstream << "Execution of async base environment failed: " << e.what() + << std::endl; FATAL_ERROR("Execution of async base environment failed"); } @@ -258,11 +257,9 @@ void* AsyncWorkerThread::run() luaL_checktype(L, -1, LUA_TFUNCTION); // Call it - lua_pushlstring(L, - toProcess.serializedFunction.data(), + lua_pushlstring(L, toProcess.serializedFunction.data(), toProcess.serializedFunction.size()); - lua_pushlstring(L, - toProcess.serializedParams.data(), + lua_pushlstring(L, toProcess.serializedParams.data(), toProcess.serializedParams.size()); int result = lua_pcall(L, 2, 1, error_handler); @@ -276,14 +273,13 @@ void* AsyncWorkerThread::run() toProcess.serializedResult = std::string(retval, length); } - lua_pop(L, 1); // Pop retval + lua_pop(L, 1); // Pop retval // Put job result jobDispatcher->putJobResult(toProcess); } - lua_pop(L, 2); // Pop core and error handler + lua_pop(L, 2); // Pop core and error handler return 0; } - diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index b1f4bf45f..1dc4145ba 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -31,7 +31,6 @@ with this program; if not, write to the Free Software Foundation, Inc., // Forward declarations class AsyncEngine; - // Declarations // Data required to queue a job @@ -52,9 +51,10 @@ struct LuaJobInfo }; // Asynchronous working environment -class AsyncWorkerThread : public Thread, public ScriptApiBase { +class AsyncWorkerThread : public Thread, public ScriptApiBase +{ public: - AsyncWorkerThread(AsyncEngine* jobDispatcher, const std::string &name); + AsyncWorkerThread(AsyncEngine *jobDispatcher, const std::string &name); virtual ~AsyncWorkerThread(); void *run(); @@ -64,9 +64,11 @@ private: }; // Asynchornous thread and job management -class AsyncEngine { +class AsyncEngine +{ friend class AsyncWorkerThread; typedef void (*StateInitializer)(lua_State *L, int top); + public: AsyncEngine() = default; ~AsyncEngine(); @@ -125,7 +127,7 @@ protected: * @param L Lua stack to initialize * @param top Stack position */ - void prepareEnvironment(lua_State* L, int top); + void prepareEnvironment(lua_State *L, int top); private: // Variable locking the engine against further modification @@ -149,7 +151,7 @@ private: std::deque<LuaJobInfo> resultQueue; // List of current worker threads - std::vector<AsyncWorkerThread*> workerThreads; + std::vector<AsyncWorkerThread *> workerThreads; // Counter semaphore for job dispatching Semaphore jobQueueCounter; diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index 1d62d8b65..72774f6ca 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -32,11 +32,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #endif - extern "C" { #include "lualib.h" #if USE_LUAJIT - #include "luajit.h" +#include "luajit.h" #endif } @@ -45,14 +44,13 @@ extern "C" { #include "script/common/c_content.h" #include <sstream> - class ModNameStorer { private: lua_State *L; + public: - ModNameStorer(lua_State *L_, const std::string &mod_name): - L(L_) + ModNameStorer(lua_State *L_, const std::string &mod_name) : L(L_) { // Store current mod name in registry lua_pushstring(L, mod_name.c_str()); @@ -66,13 +64,11 @@ public: } }; - /* ScriptApiBase */ -ScriptApiBase::ScriptApiBase(ScriptingType type): - m_type(type) +ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) { #ifdef SCRIPTAPI_LOCK_DEBUG m_lock_recursion_count = 0; @@ -86,7 +82,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType type): /*if (m_type == ScriptingType::Client) clientOpenLibs(m_luastack); else*/ - luaL_openlibs(m_luastack); + luaL_openlibs(m_luastack); // Make the ScriptApiBase* accessible to ModApiBase #if INDIRECT_SCRIPTAPI_RIDX @@ -105,7 +101,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType type): // If we are using LuaJIT add a C++ wrapper function to catch // exceptions thrown in Lua -> C++ calls #if USE_LUAJIT - lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper); + lua_pushlightuserdata(m_luastack, (void *)script_exception_wrapper); luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); lua_pop(m_luastack, 1); #endif @@ -136,7 +132,7 @@ int ScriptApiBase::luaPanic(lua_State *L) { std::ostringstream oss; oss << "LUA PANIC: unprotected error in call to Lua API (" - << readParam<std::string>(L, -1) << ")"; + << readParam<std::string>(L, -1) << ")"; FATAL_ERROR(oss.str().c_str()); // NOTREACHED return 0; @@ -145,26 +141,25 @@ int ScriptApiBase::luaPanic(lua_State *L) void ScriptApiBase::clientOpenLibs(lua_State *L) { static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = { - { "", luaopen_base }, - { LUA_TABLIBNAME, luaopen_table }, - { LUA_OSLIBNAME, luaopen_os }, - { LUA_STRLIBNAME, luaopen_string }, - { LUA_MATHLIBNAME, luaopen_math }, - { LUA_DBLIBNAME, luaopen_debug }, + {"", luaopen_base}, + {LUA_TABLIBNAME, luaopen_table}, + {LUA_OSLIBNAME, luaopen_os}, + {LUA_STRLIBNAME, luaopen_string}, + {LUA_MATHLIBNAME, luaopen_math}, + {LUA_DBLIBNAME, luaopen_debug}, #if USE_LUAJIT - { LUA_JITLIBNAME, luaopen_jit }, + {LUA_JITLIBNAME, luaopen_jit}, #endif }; for (const std::pair<std::string, lua_CFunction> &lib : m_libs) { - lua_pushcfunction(L, lib.second); - lua_pushstring(L, lib.first.c_str()); - lua_call(L, 1, 0); + 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) +void ScriptApiBase::loadMod(const std::string &script_path, const std::string &mod_name) { ModNameStorer mod_name_storer(getStack(), mod_name); @@ -191,8 +186,8 @@ void ScriptApiBase::loadScript(const std::string &script_path) if (!error_msg) error_msg = "(error object is not a string)"; lua_pop(L, 2); // Pop error message and error handler - throw ModError("Failed to load and run script from " + - script_path + ":\n" + error_msg); + throw ModError("Failed to load and run script from " + script_path + + ":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } @@ -225,8 +220,8 @@ void ScriptApiBase::loadModFromMemory(const std::string &mod_name) if (!error_msg) error_msg = "(error object is not a string)"; lua_pop(L, 2); // Pop error message and error handler - throw ModError("Failed to load and run mod \"" + - mod_name + "\":\n" + error_msg); + throw ModError("Failed to load and run mod \"" + mod_name + "\":\n" + + error_msg); } lua_pop(L, 1); // Pop error handler } @@ -240,14 +235,13 @@ void ScriptApiBase::loadModFromMemory(const std::string &mod_name) // 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) +void ScriptApiBase::runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn) { #ifndef SERVER // Hard fail for bad guarded callbacks // Only run callbacks when the scripting enviroment is loaded - FATAL_ERROR_IF(m_type == ScriptingType::Client && - !getClient()->modsLoaded(), fxn); + FATAL_ERROR_IF(m_type == ScriptingType::Client && !getClient()->modsLoaded(), + fxn); #endif #ifdef SCRIPTAPI_LOCK_DEBUG @@ -300,24 +294,25 @@ void ScriptApiBase::scriptError(int result, const char *fxn) void ScriptApiBase::stackDump(std::ostream &o) { int top = lua_gettop(m_luastack); - for (int i = 1; i <= top; i++) { /* repeat for each level */ + 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; + 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 << " "; } @@ -334,9 +329,10 @@ 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()); + 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 } @@ -357,7 +353,7 @@ void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER - //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl; + // infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl; // Create object on stack ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack @@ -371,14 +367,14 @@ void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) // object_refs[id] = object lua_pushnumber(L, cobj->getId()); // Push id - lua_pushvalue(L, object); // Copy object to top of stack + 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; + // infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl; // Get core.object_refs table lua_getglobal(L, "core"); @@ -400,8 +396,7 @@ void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj) } // Creates a new anonymous reference if cobj=NULL or id=0 -void ScriptApiBase::objectrefGetOrCreate(lua_State *L, - ServerActiveObject *cobj) +void ScriptApiBase::objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj) { if (cobj == NULL || cobj->getId() == 0) { ObjectRef::create(L, cobj); @@ -409,12 +404,13 @@ void ScriptApiBase::objectrefGetOrCreate(lua_State *L, push_objectRef(L, cobj->getId()); if (cobj->isGone()) warningstream << "ScriptApiBase::objectrefGetOrCreate(): " - << "Pushing ObjectRef to removed/deactivated object" - << ", this is probably a bug." << std::endl; + << "Pushing ObjectRef to removed/deactivated object" + << ", this is probably a bug." << std::endl; } } -void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason) +void ScriptApiBase::pushPlayerHPChangeReason( + lua_State *L, const PlayerHPChangeReason &reason) { if (reason.hasLuaReference()) lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference); @@ -442,12 +438,12 @@ void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeR } } -Server* ScriptApiBase::getServer() +Server *ScriptApiBase::getServer() { return dynamic_cast<Server *>(m_gamedef); } #ifndef SERVER -Client* ScriptApiBase::getClient() +Client *ScriptApiBase::getClient() { return dynamic_cast<Client *>(m_gamedef); } diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index 36331ad37..d2081ad5c 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -45,20 +45,20 @@ extern "C" { // use that name to bypass security! #define BUILTIN_MOD_NAME "*builtin*" -#define PCALL_RES(RES) { \ - int result_ = (RES); \ - if (result_ != 0) { \ - scriptError(result_, __FUNCTION__); \ - } \ -} +#define PCALL_RES(RES) \ + { \ + int result_ = (RES); \ + if (result_ != 0) { \ + scriptError(result_, __FUNCTION__); \ + } \ + } -#define runCallbacks(nargs, mode) \ - runCallbacksRaw((nargs), (mode), __FUNCTION__) +#define runCallbacks(nargs, mode) runCallbacksRaw((nargs), (mode), __FUNCTION__) -#define setOriginFromTable(index) \ - setOriginFromTableRaw(index, __FUNCTION__) +#define setOriginFromTable(index) setOriginFromTableRaw(index, __FUNCTION__) -enum class ScriptingType: u8 { +enum class ScriptingType : u8 +{ Async, Client, MainMenu, @@ -76,14 +76,13 @@ class GUIEngine; class ServerActiveObject; struct PlayerHPChangeReason; -class ScriptApiBase : protected LuaHelper { +class ScriptApiBase : protected LuaHelper +{ public: ScriptApiBase(ScriptingType type); - // fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually inherit from this one. - ScriptApiBase() - { - FATAL_ERROR("ScriptApiBase created without ScriptingType!"); - } + // fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually + // inherit from this one. + ScriptApiBase() { FATAL_ERROR("ScriptApiBase created without ScriptingType!"); } virtual ~ScriptApiBase(); DISABLE_CLASS_COPY(ScriptApiBase); @@ -95,18 +94,17 @@ public: void loadModFromMemory(const std::string &mod_name); #endif - void runCallbacksRaw(int nargs, - RunCallbacksMode mode, const char *fxn); + void runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn); /* object */ void addObjectReference(ServerActiveObject *cobj); void removeObjectReference(ServerActiveObject *cobj); IGameDef *getGameDef() { return m_gamedef; } - Server* getServer(); + Server *getServer(); ScriptingType getType() { return m_type; } #ifndef SERVER - Client* getClient(); + Client *getClient(); Game *getGame() { return m_game; } #endif @@ -126,50 +124,49 @@ protected: friend class ModApiEnvMod; friend class LuaVoxelManip; - lua_State* getStack() - { return m_luastack; } + lua_State *getStack() { return m_luastack; } void realityCheck(); void scriptError(int result, const char *fxn); void stackDump(std::ostream &o); - void setGameDef(IGameDef* gamedef) { m_gamedef = gamedef; } + void setGameDef(IGameDef *gamedef) { m_gamedef = gamedef; } #ifndef SERVER void setGame(Game *game) { m_game = game; } #endif - Environment* getEnv() { return m_environment; } - void setEnv(Environment* env) { m_environment = env; } + Environment *getEnv() { return m_environment; } + void setEnv(Environment *env) { m_environment = env; } #ifndef SERVER - GUIEngine* getGuiEngine() { return m_guiengine; } - void setGuiEngine(GUIEngine* guiengine) { m_guiengine = guiengine; } + GUIEngine *getGuiEngine() { return m_guiengine; } + void setGuiEngine(GUIEngine *guiengine) { m_guiengine = guiengine; } #endif void objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj); - void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason& reason); + void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason); std::recursive_mutex m_luastackmutex; - std::string m_last_run_mod; - bool m_secure = false; + std::string m_last_run_mod; + bool m_secure = false; #ifdef SCRIPTAPI_LOCK_DEBUG - int m_lock_recursion_count{}; + int m_lock_recursion_count{}; std::thread::id m_owning_thread; #endif private: static int luaPanic(lua_State *L); - lua_State *m_luastack = nullptr; + lua_State *m_luastack = nullptr; - IGameDef *m_gamedef = nullptr; + IGameDef *m_gamedef = nullptr; #ifndef SERVER - Game *m_game = nullptr; + Game *m_game = nullptr; #endif - Environment *m_environment = nullptr; + Environment *m_environment = nullptr; #ifndef SERVER - GUIEngine *m_guiengine = nullptr; + GUIEngine *m_guiengine = nullptr; #endif - ScriptingType m_type; + ScriptingType m_type; }; diff --git a/src/script/cpp_api/s_client.cpp b/src/script/cpp_api/s_client.cpp index dd9019d4d..e6c9eea1a 100644 --- a/src/script/cpp_api/s_client.cpp +++ b/src/script/cpp_api/s_client.cpp @@ -120,13 +120,13 @@ void ScriptApiClient::environment_step(float dtime) try { runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getClient()->setFatalError(std::string("Client environment_step: ") + e.what() + "\n" - + script_get_backtrace(L)); + getClient()->setFatalError(std::string("Client environment_step: ") + + e.what() + "\n" + script_get_backtrace(L)); } } -void ScriptApiClient::on_formspec_input(const std::string &formname, - const StringMap &fields) +void ScriptApiClient::on_formspec_input( + const std::string &formname, const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -187,7 +187,8 @@ bool ScriptApiClient::on_punchnode(v3s16 p, MapNode node) return readParam<bool>(L, -1); } -bool ScriptApiClient::on_placenode(const PointedThing &pointed, const ItemDefinition &item) +bool ScriptApiClient::on_placenode( + const PointedThing &pointed, const ItemDefinition &item) { SCRIPTAPI_PRECHECKHEADER @@ -237,11 +238,11 @@ bool ScriptApiClient::on_inventory_open(Inventory *inventory) void ScriptApiClient::open_enderchest() { SCRIPTAPI_PRECHECKHEADER - + PUSH_ERROR_HANDLER(L); int error_handler = lua_gettop(L) - 1; lua_insert(L, error_handler); - + lua_getglobal(L, "core"); lua_getfield(L, -1, "open_enderchest"); if (lua_isfunction(L, -1)) diff --git a/src/script/cpp_api/s_entity.cpp b/src/script/cpp_api/s_entity.cpp index ea9320051..baf455e1b 100644 --- a/src/script/cpp_api/s_entity.cpp +++ b/src/script/cpp_api/s_entity.cpp @@ -29,8 +29,8 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) { SCRIPTAPI_PRECHECKHEADER - verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\"" - <<name<<"\""<<std::endl; + verbosestream << "scriptapi_luaentity_add: id=" << id << " name=\"" << name + << "\"" << std::endl; // Get core.registered_entities[name] lua_getglobal(L, "core"); @@ -39,13 +39,14 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) lua_pushstring(L, name); lua_gettable(L, -2); // Should be a table, which we will use as a prototype - //luaL_checktype(L, -1, LUA_TTABLE); - if (lua_type(L, -1) != LUA_TTABLE){ - errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl; + // luaL_checktype(L, -1, LUA_TTABLE); + if (lua_type(L, -1) != LUA_TTABLE) { + errorstream << "LuaEntity name \"" << name << "\" not defined" + << std::endl; return false; } int prototype_table = lua_gettop(L); - //dump2(L, "prototype_table"); + // dump2(L, "prototype_table"); // Create entity object lua_newtable(L); @@ -67,15 +68,15 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) lua_getglobal(L, "core"); lua_getfield(L, -1, "luaentities"); luaL_checktype(L, -1, LUA_TTABLE); - lua_pushnumber(L, id); // Push id + lua_pushnumber(L, id); // Push id lua_pushvalue(L, object); // Copy object to top of stack lua_settable(L, -3); return true; } -void ScriptApiEntity::luaentity_Activate(u16 id, - const std::string &staticdata, u32 dtime_s) +void ScriptApiEntity::luaentity_Activate( + u16 id, const std::string &staticdata, u32 dtime_s) { SCRIPTAPI_PRECHECKHEADER @@ -127,7 +128,7 @@ std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id) { SCRIPTAPI_PRECHECKHEADER - //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl; + // infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl; int error_handler = PUSH_ERROR_HANDLER(L); @@ -156,12 +157,12 @@ std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id) return std::string(s, len); } -void ScriptApiEntity::luaentity_GetProperties(u16 id, - ServerActiveObject *self, ObjectProperties *prop) +void ScriptApiEntity::luaentity_GetProperties( + u16 id, ServerActiveObject *self, ObjectProperties *prop) { SCRIPTAPI_PRECHECKHEADER - //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl; + // infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl; // Get core.luaentities[id] luaentity_get(L, id); @@ -178,8 +179,8 @@ void ScriptApiEntity::luaentity_GetProperties(u16 id, lua_pop(L, 1); } -void ScriptApiEntity::luaentity_Step(u16 id, float dtime, - const collisionMoveResult *moveresult) +void ScriptApiEntity::luaentity_Step( + u16 id, float dtime, const collisionMoveResult *moveresult) { SCRIPTAPI_PRECHECKHEADER @@ -212,18 +213,18 @@ void ScriptApiEntity::luaentity_Step(u16 id, float dtime, // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch, // tool_capabilities, direction, damage) -bool ScriptApiEntity::luaentity_Punch(u16 id, - ServerActiveObject *puncher, float time_from_last_punch, - const ToolCapabilities *toolcap, v3f dir, s16 damage) +bool ScriptApiEntity::luaentity_Punch(u16 id, ServerActiveObject *puncher, + float time_from_last_punch, const ToolCapabilities *toolcap, v3f dir, + s16 damage) { SCRIPTAPI_PRECHECKHEADER - //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; + // infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; int error_handler = PUSH_ERROR_HANDLER(L); // Get core.luaentities[id] - luaentity_get(L,id); + luaentity_get(L, id); int object = lua_gettop(L); // State: object is at top of stack // Get function @@ -233,8 +234,8 @@ bool ScriptApiEntity::luaentity_Punch(u16 id, return false; } luaL_checktype(L, -1, LUA_TFUNCTION); - lua_pushvalue(L, object); // self - objectrefGetOrCreate(L, puncher); // Clicker reference + lua_pushvalue(L, object); // self + objectrefGetOrCreate(L, puncher); // Clicker reference lua_pushnumber(L, time_from_last_punch); push_tool_capabilities(L, *toolcap); push_v3f(L, dir); @@ -249,8 +250,8 @@ bool ScriptApiEntity::luaentity_Punch(u16 id, } // Calls entity[field](ObjectRef self, ObjectRef sao) -bool ScriptApiEntity::luaentity_run_simple_callback(u16 id, - ServerActiveObject *sao, const char *field) +bool ScriptApiEntity::luaentity_run_simple_callback( + u16 id, ServerActiveObject *sao, const char *field) { SCRIPTAPI_PRECHECKHEADER @@ -267,8 +268,8 @@ bool ScriptApiEntity::luaentity_run_simple_callback(u16 id, return false; } luaL_checktype(L, -1, LUA_TFUNCTION); - lua_pushvalue(L, object); // self - objectrefGetOrCreate(L, sao); // killer reference + lua_pushvalue(L, object); // self + objectrefGetOrCreate(L, sao); // killer reference setOriginFromTable(object); PCALL_RES(lua_pcall(L, 2, 1, error_handler)); diff --git a/src/script/cpp_api/s_entity.h b/src/script/cpp_api/s_entity.h index b5f7a6586..93960ed03 100644 --- a/src/script/cpp_api/s_entity.h +++ b/src/script/cpp_api/s_entity.h @@ -26,28 +26,26 @@ struct ObjectProperties; struct ToolCapabilities; struct collisionMoveResult; -class ScriptApiEntity - : virtual public ScriptApiBase +class ScriptApiEntity : virtual public ScriptApiBase { public: bool luaentity_Add(u16 id, const char *name); - void luaentity_Activate(u16 id, - const std::string &staticdata, u32 dtime_s); + void luaentity_Activate(u16 id, const std::string &staticdata, u32 dtime_s); void luaentity_Remove(u16 id); std::string luaentity_GetStaticdata(u16 id); - void luaentity_GetProperties(u16 id, - ServerActiveObject *self, ObjectProperties *prop); - void luaentity_Step(u16 id, float dtime, - const collisionMoveResult *moveresult); - bool luaentity_Punch(u16 id, - ServerActiveObject *puncher, float time_from_last_punch, - const ToolCapabilities *toolcap, v3f dir, s16 damage); + void luaentity_GetProperties( + u16 id, ServerActiveObject *self, ObjectProperties *prop); + void luaentity_Step(u16 id, float dtime, const collisionMoveResult *moveresult); + bool luaentity_Punch(u16 id, ServerActiveObject *puncher, + float time_from_last_punch, const ToolCapabilities *toolcap, + v3f dir, s16 damage); bool luaentity_on_death(u16 id, ServerActiveObject *killer); void luaentity_Rightclick(u16 id, ServerActiveObject *clicker); void luaentity_on_attach_child(u16 id, ServerActiveObject *child); void luaentity_on_detach_child(u16 id, ServerActiveObject *child); void luaentity_on_detach(u16 id, ServerActiveObject *parent); + private: - bool luaentity_run_simple_callback(u16 id, ServerActiveObject *sao, - const char *field); + bool luaentity_run_simple_callback( + u16 id, ServerActiveObject *sao, const char *field); }; diff --git a/src/script/cpp_api/s_env.cpp b/src/script/cpp_api/s_env.cpp index 8da5debaa..7511c0226 100644 --- a/src/script/cpp_api/s_env.cpp +++ b/src/script/cpp_api/s_env.cpp @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_env.h" #include "server.h" -void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, - u32 blockseed) +void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, u32 blockseed) { SCRIPTAPI_PRECHECKHEADER @@ -44,7 +43,7 @@ void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, void ScriptApiEnv::environment_Step(float dtime) { SCRIPTAPI_PRECHECKHEADER - //infostream << "scriptapi_environment_step" << std::endl; + // infostream << "scriptapi_environment_step" << std::endl; // Get core.registered_globalsteps lua_getglobal(L, "core"); @@ -54,9 +53,9 @@ void ScriptApiEnv::environment_Step(float dtime) try { runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getServer()->setAsyncFatalError( - std::string("environment_Step: ") + e.what() + "\n" - + script_get_backtrace(L)); + getServer()->setAsyncFatalError(std::string("environment_Step: ") + + e.what() + "\n" + + script_get_backtrace(L)); } } @@ -72,14 +71,13 @@ void ScriptApiEnv::player_event(ServerActiveObject *player, const std::string &t lua_getfield(L, -1, "registered_playerevents"); // Call callbacks - objectrefGetOrCreate(L, player); // player - lua_pushstring(L,type.c_str()); // event type + objectrefGetOrCreate(L, player); // player + lua_pushstring(L, type.c_str()); // event type try { runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getServer()->setAsyncFatalError( - std::string("player_event: ") + e.what() + "\n" - + script_get_backtrace(L) ); + getServer()->setAsyncFatalError(std::string("player_event: ") + e.what() + + "\n" + script_get_backtrace(L)); } } @@ -116,7 +114,8 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) while (lua_next(L, table)) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); - trigger_contents.emplace_back(readParam<std::string>(L, -1)); + trigger_contents.emplace_back( + readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -133,7 +132,8 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) while (lua_next(L, table)) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); - required_neighbors.emplace_back(readParam<std::string>(L, -1)); + required_neighbors.emplace_back( + readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -156,7 +156,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) lua_pop(L, 1); LuaABM *abm = new LuaABM(L, id, trigger_contents, required_neighbors, - trigger_interval, trigger_chance, simple_catch_up); + trigger_interval, trigger_chance, simple_catch_up); env->addActiveBlockModifier(abm); @@ -201,15 +201,15 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) std::string name; getstringfield(L, current_lbm, "name", name); - bool run_at_every_load = getboolfield_default(L, current_lbm, - "run_at_every_load", false); + bool run_at_every_load = getboolfield_default( + L, current_lbm, "run_at_every_load", false); lua_getfield(L, current_lbm, "action"); luaL_checktype(L, current_lbm + 1, LUA_TFUNCTION); lua_pop(L, 1); - LuaLBM *lbm = new LuaLBM(L, id, trigger_contents, name, - run_at_every_load); + LuaLBM *lbm = new LuaLBM( + L, id, trigger_contents, name, run_at_every_load); env->addLoadingBlockModifierDef(lbm); @@ -220,7 +220,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) } void ScriptApiEnv::on_emerge_area_completion( - v3s16 blockpos, int action, ScriptCallbackState *state) + v3s16 blockpos, int action, ScriptCallbackState *state) { Server *server = getServer(); @@ -249,9 +249,8 @@ void ScriptApiEnv::on_emerge_area_completion( try { PCALL_RES(lua_pcall(L, 4, 0, error_handler)); } catch (LuaError &e) { - server->setAsyncFatalError( - std::string("on_emerge_area_completion: ") + e.what() + "\n" - + script_get_backtrace(L)); + server->setAsyncFatalError(std::string("on_emerge_area_completion: ") + + e.what() + "\n" + script_get_backtrace(L)); } lua_pop(L, 1); // Pop error handler diff --git a/src/script/cpp_api/s_env.h b/src/script/cpp_api/s_env.h index 232a08aaf..1848c7a94 100644 --- a/src/script/cpp_api/s_env.h +++ b/src/script/cpp_api/s_env.h @@ -38,8 +38,8 @@ public: void player_event(ServerActiveObject *player, const std::string &type); // Called after emerge of a block queued from core.emerge_area() - void on_emerge_area_completion(v3s16 blockpos, int action, - ScriptCallbackState *state); + void on_emerge_area_completion( + v3s16 blockpos, int action, ScriptCallbackState *state); void initializeEnvironment(ServerEnvironment *env); }; diff --git a/src/script/cpp_api/s_internal.h b/src/script/cpp_api/s_internal.h index 83b3b9d27..858b827de 100644 --- a/src/script/cpp_api/s_internal.h +++ b/src/script/cpp_api/s_internal.h @@ -34,13 +34,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifdef SCRIPTAPI_LOCK_DEBUG #include <cassert> -class LockChecker { +class LockChecker +{ public: LockChecker(int *recursion_counter, std::thread::id *owning_thread) { m_lock_recursion_counter = recursion_counter; - m_owning_thread = owning_thread; - m_original_level = *recursion_counter; + m_owning_thread = owning_thread; + m_original_level = *recursion_counter; if (*m_lock_recursion_counter > 0) { assert(*m_owning_thread == std::this_thread::get_id()); @@ -67,19 +68,18 @@ private: std::thread::id *m_owning_thread; }; -#define SCRIPTAPI_LOCK_CHECK \ - LockChecker scriptlock_checker( \ - &this->m_lock_recursion_count, \ - &this->m_owning_thread) +#define SCRIPTAPI_LOCK_CHECK \ + LockChecker scriptlock_checker( \ + &this->m_lock_recursion_count, &this->m_owning_thread) #else - #define SCRIPTAPI_LOCK_CHECK while(0) +#define SCRIPTAPI_LOCK_CHECK while (0) #endif -#define SCRIPTAPI_PRECHECKHEADER \ - RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \ - SCRIPTAPI_LOCK_CHECK; \ - realityCheck(); \ - lua_State *L = getStack(); \ - assert(lua_checkstack(L, 20)); \ - StackUnroller stack_unroller(L); +#define SCRIPTAPI_PRECHECKHEADER \ + RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \ + SCRIPTAPI_LOCK_CHECK; \ + realityCheck(); \ + lua_State *L = getStack(); \ + assert(lua_checkstack(L, 20)); \ + StackUnroller stack_unroller(L); diff --git a/src/script/cpp_api/s_inventory.cpp b/src/script/cpp_api/s_inventory.cpp index e9c09f72e..e4d3f990d 100644 --- a/src/script/cpp_api/s_inventory.cpp +++ b/src/script/cpp_api/s_inventory.cpp @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Return number of accepted items to be moved int ScriptApiDetached::detached_inventory_AllowMove( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -41,14 +40,15 @@ int ScriptApiDetached::detached_inventory_AllowMove( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 1, error_handler)); - if(!lua_isnumber(L, -1)) - throw LuaError("allow_move should return a number. name=" + ma.from_inv.name); + if (!lua_isnumber(L, -1)) + throw LuaError("allow_move should return a number. name=" + + ma.from_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -56,8 +56,7 @@ int ScriptApiDetached::detached_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiDetached::detached_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -68,14 +67,15 @@ int ScriptApiDetached::detached_inventory_AllowPut( return stack.count; // All will be accepted // Call function(inv, listname, index, stack, player) - InvRef::create(L, ma.to_inv); // inv + InvRef::create(L, ma.to_inv); // inv lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) - throw LuaError("allow_put should return a number. name=" + ma.to_inv.name); + throw LuaError("allow_put should return a number. name=" + + ma.to_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -83,8 +83,7 @@ int ScriptApiDetached::detached_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiDetached::detached_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -95,14 +94,15 @@ int ScriptApiDetached::detached_inventory_AllowTake( return stack.count; // All will be accepted // Call function(inv, listname, index, stack, player) - InvRef::create(L, ma.from_inv); // inv + InvRef::create(L, ma.from_inv); // inv lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) - throw LuaError("allow_take should return a number. name=" + ma.from_inv.name); + throw LuaError("allow_take should return a number. name=" + + ma.from_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -110,8 +110,7 @@ int ScriptApiDetached::detached_inventory_AllowTake( // Report moved items void ScriptApiDetached::detached_inventory_OnMove( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -125,19 +124,18 @@ void ScriptApiDetached::detached_inventory_OnMove( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report put items void ScriptApiDetached::detached_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -152,16 +150,15 @@ void ScriptApiDetached::detached_inventory_OnPut( InvRef::create(L, ma.to_inv); lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report taken items void ScriptApiDetached::detached_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -175,11 +172,11 @@ void ScriptApiDetached::detached_inventory_OnTake( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Retrieves core.detached_inventories[name][callbackname] @@ -199,7 +196,8 @@ bool ScriptApiDetached::getDetachedInventoryCallback( lua_remove(L, -2); // Should be a table if (lua_type(L, -1) != LUA_TTABLE) { - errorstream<<"Detached inventory \""<<name<<"\" not defined"<<std::endl; + errorstream << "Detached inventory \"" << name << "\" not defined" + << std::endl; lua_pop(L, 1); return false; } @@ -218,8 +216,8 @@ bool ScriptApiDetached::getDetachedInventoryCallback( return false; } - errorstream << "Detached inventory \"" << name << "\" callback \"" - << callbackname << "\" is not a function" << std::endl; + errorstream << "Detached inventory \"" << name << "\" callback \"" << callbackname + << "\" is not a function" << std::endl; lua_pop(L, 1); return false; } diff --git a/src/script/cpp_api/s_inventory.h b/src/script/cpp_api/s_inventory.h index e79b3d18b..c6476190e 100644 --- a/src/script/cpp_api/s_inventory.h +++ b/src/script/cpp_api/s_inventory.h @@ -24,35 +24,29 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MoveAction; struct ItemStack; -class ScriptApiDetached - : virtual public ScriptApiBase +class ScriptApiDetached : virtual public ScriptApiBase { public: /* Detached inventory callbacks */ // Return number of accepted items to be moved int detached_inventory_AllowMove( - const MoveAction &ma, int count, - ServerActiveObject *player); + const MoveAction &ma, int count, ServerActiveObject *player); // Return number of accepted items to be put - int detached_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, + int detached_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Return number of accepted items to be taken - int detached_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, + int detached_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report moved items void detached_inventory_OnMove( - const MoveAction &ma, int count, - ServerActiveObject *player); + const MoveAction &ma, int count, ServerActiveObject *player); // Report put items - void detached_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, + void detached_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report taken items - void detached_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, + void detached_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); + private: bool getDetachedInventoryCallback( const std::string &name, const char *callbackname); diff --git a/src/script/cpp_api/s_item.cpp b/src/script/cpp_api/s_item.cpp index 24955cefc..4e77ad412 100644 --- a/src/script/cpp_api/s_item.cpp +++ b/src/script/cpp_api/s_item.cpp @@ -29,8 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventory.h" #include "inventorymanager.h" -bool ScriptApiItem::item_OnDrop(ItemStack &item, - ServerActiveObject *dropper, v3f pos) +bool ScriptApiItem::item_OnDrop(ItemStack &item, ServerActiveObject *dropper, v3f pos) { SCRIPTAPI_PRECHECKHEADER @@ -52,12 +51,12 @@ bool ScriptApiItem::item_OnDrop(ItemStack &item, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } -bool ScriptApiItem::item_OnPlace(ItemStack &item, - ServerActiveObject *placer, const PointedThing &pointed) +bool ScriptApiItem::item_OnPlace( + ItemStack &item, ServerActiveObject *placer, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -84,12 +83,12 @@ bool ScriptApiItem::item_OnPlace(ItemStack &item, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } -bool ScriptApiItem::item_OnUse(ItemStack &item, - ServerActiveObject *user, const PointedThing &pointed) +bool ScriptApiItem::item_OnUse( + ItemStack &item, ServerActiveObject *user, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -104,19 +103,19 @@ bool ScriptApiItem::item_OnUse(ItemStack &item, objectrefGetOrCreate(L, user); pushPointedThing(pointed); PCALL_RES(lua_pcall(L, 3, 1, error_handler)); - if(!lua_isnil(L, -1)) { + if (!lua_isnil(L, -1)) { try { item = read_item(L, -1, getServer()->idef()); } catch (LuaError &e) { throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } -bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, - ServerActiveObject *user, const PointedThing &pointed) +bool ScriptApiItem::item_OnSecondaryUse( + ItemStack &item, ServerActiveObject *user, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -136,7 +135,7 @@ bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } @@ -168,7 +167,7 @@ bool ScriptApiItem::item_OnCraft(ItemStack &item, ServerActiveObject *user, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } @@ -184,7 +183,7 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user, LuaItemStack::create(L, item); objectrefGetOrCreate(L, user); - //Push inventory list + // Push inventory list std::vector<ItemStack> items; for (u32 i = 0; i < old_craft_grid->getSize(); i++) { items.push_back(old_craft_grid->getItem(i)); @@ -200,7 +199,7 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } @@ -210,10 +209,10 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user, // function onto the stack // If core.registered_items[name] doesn't exist, core.nodedef_default // is tried instead so unknown items can still be manipulated to some degree -bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname, - const v3s16 *p) +bool ScriptApiItem::getItemCallback( + const char *name, const char *callbackname, const v3s16 *p) { - lua_State* L = getStack(); + lua_State *L = getStack(); lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_items"); @@ -247,8 +246,8 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname, } if (!lua_isnil(L, -1)) { - errorstream << "Item \"" << name << "\" callback \"" - << callbackname << "\" is not a function" << std::endl; + errorstream << "Item \"" << name << "\" callback \"" << callbackname + << "\" is not a function" << std::endl; } lua_pop(L, 1); return false; @@ -256,8 +255,7 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname, void ScriptApiItem::pushPointedThing(const PointedThing &pointed, bool hitpoint) { - lua_State* L = getStack(); + lua_State *L = getStack(); push_pointed_thing(L, pointed, false, hitpoint); } - diff --git a/src/script/cpp_api/s_item.h b/src/script/cpp_api/s_item.h index 25a3501f9..530f14bbc 100644 --- a/src/script/cpp_api/s_item.h +++ b/src/script/cpp_api/s_item.h @@ -31,32 +31,32 @@ class ModApiItemMod; class InventoryList; struct InventoryLocation; -class ScriptApiItem -: virtual public ScriptApiBase +class ScriptApiItem : virtual public ScriptApiBase { public: - bool item_OnDrop(ItemStack &item, - ServerActiveObject *dropper, v3f pos); - bool item_OnPlace(ItemStack &item, - ServerActiveObject *placer, const PointedThing &pointed); - bool item_OnUse(ItemStack &item, - ServerActiveObject *user, const PointedThing &pointed); - bool item_OnSecondaryUse(ItemStack &item, - ServerActiveObject *user, const PointedThing &pointed); + bool item_OnDrop(ItemStack &item, ServerActiveObject *dropper, v3f pos); + bool item_OnPlace(ItemStack &item, ServerActiveObject *placer, + const PointedThing &pointed); + bool item_OnUse(ItemStack &item, ServerActiveObject *user, + const PointedThing &pointed); + bool item_OnSecondaryUse(ItemStack &item, ServerActiveObject *user, + const PointedThing &pointed); bool item_OnCraft(ItemStack &item, ServerActiveObject *user, - const InventoryList *old_craft_grid, const InventoryLocation &craft_inv); + const InventoryList *old_craft_grid, + const InventoryLocation &craft_inv); bool item_CraftPredict(ItemStack &item, ServerActiveObject *user, - const InventoryList *old_craft_grid, const InventoryLocation &craft_inv); + const InventoryList *old_craft_grid, + const InventoryLocation &craft_inv); protected: friend class LuaItemStack; friend class ModApiItemMod; - bool getItemCallback(const char *name, const char *callbackname, const v3s16 *p = nullptr); + bool getItemCallback(const char *name, const char *callbackname, + const v3s16 *p = nullptr); /*! * Pushes a `pointed_thing` tabe to the stack. * \param hitpoint If true, the exact pointing location is also pushed */ void pushPointedThing(const PointedThing &pointed, bool hitpoint = false); - }; diff --git a/src/script/cpp_api/s_mainmenu.h b/src/script/cpp_api/s_mainmenu.h index aef36ce39..0f6ff9f78 100644 --- a/src/script/cpp_api/s_mainmenu.h +++ b/src/script/cpp_api/s_mainmenu.h @@ -23,7 +23,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/string.h" #include "gui/guiMainMenu.h" -class ScriptApiMainMenu : virtual public ScriptApiBase { +class ScriptApiMainMenu : virtual public ScriptApiBase +{ public: /** * Hand over MainMenuDataForScript to lua to inform lua of the content diff --git a/src/script/cpp_api/s_node.cpp b/src/script/cpp_api/s_node.cpp index e0f9bcd78..928fda6e2 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -26,10 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "environment.h" #include "util/pointedthing.h" - // Should be ordered exactly like enum NodeDrawType in nodedef.h -struct EnumString ScriptApiNode::es_DrawType[] = - { +struct EnumString ScriptApiNode::es_DrawType[] = { {NDT_NORMAL, "normal"}, {NDT_AIRLIKE, "airlike"}, {NDT_LIQUID, "liquid"}, @@ -49,10 +47,9 @@ struct EnumString ScriptApiNode::es_DrawType[] = {NDT_MESH, "mesh"}, {NDT_PLANTLIKE_ROOTED, "plantlike_rooted"}, {0, NULL}, - }; +}; -struct EnumString ScriptApiNode::es_ContentParamType2[] = - { +struct EnumString ScriptApiNode::es_ContentParamType2[] = { {CPT2_NONE, "none"}, {CPT2_FULL, "full"}, {CPT2_FLOWINGLIQUID, "flowingliquid"}, @@ -66,35 +63,32 @@ struct EnumString ScriptApiNode::es_ContentParamType2[] = {CPT2_COLORED_WALLMOUNTED, "colorwallmounted"}, {CPT2_GLASSLIKE_LIQUID_LEVEL, "glasslikeliquidlevel"}, {0, NULL}, - }; +}; -struct EnumString ScriptApiNode::es_LiquidType[] = - { +struct EnumString ScriptApiNode::es_LiquidType[] = { {LIQUID_NONE, "none"}, {LIQUID_FLOWING, "flowing"}, {LIQUID_SOURCE, "source"}, {0, NULL}, - }; +}; -struct EnumString ScriptApiNode::es_ContentParamType[] = - { +struct EnumString ScriptApiNode::es_ContentParamType[] = { {CPT_NONE, "none"}, {CPT_LIGHT, "light"}, {0, NULL}, - }; +}; -struct EnumString ScriptApiNode::es_NodeBoxType[] = - { +struct EnumString ScriptApiNode::es_NodeBoxType[] = { {NODEBOX_REGULAR, "regular"}, {NODEBOX_FIXED, "fixed"}, {NODEBOX_WALLMOUNTED, "wallmounted"}, {NODEBOX_LEVELED, "leveled"}, {NODEBOX_CONNECTED, "connected"}, {0, NULL}, - }; +}; -bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, - ServerActiveObject *puncher, const PointedThing &pointed) +bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, ServerActiveObject *puncher, + const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -112,12 +106,11 @@ bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, objectrefGetOrCreate(L, puncher); pushPointedThing(pointed); PCALL_RES(lua_pcall(L, 4, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler return true; } -bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, - ServerActiveObject *digger) +bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, ServerActiveObject *digger) { SCRIPTAPI_PRECHECKHEADER @@ -134,7 +127,7 @@ bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, pushnode(L, node, ndef); objectrefGetOrCreate(L, digger); PCALL_RES(lua_pcall(L, 3, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler return true; } @@ -153,7 +146,7 @@ void ScriptApiNode::node_on_construct(v3s16 p, MapNode node) // Call function push_v3s16(L, p); PCALL_RES(lua_pcall(L, 1, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } void ScriptApiNode::node_on_destruct(v3s16 p, MapNode node) @@ -171,7 +164,7 @@ void ScriptApiNode::node_on_destruct(v3s16 p, MapNode node) // Call function push_v3s16(L, p); PCALL_RES(lua_pcall(L, 1, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } bool ScriptApiNode::node_on_flood(v3s16 p, MapNode node, MapNode newnode) @@ -211,7 +204,7 @@ void ScriptApiNode::node_after_destruct(v3s16 p, MapNode node) push_v3s16(L, p); pushnode(L, node, ndef); PCALL_RES(lua_pcall(L, 2, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime) @@ -228,16 +221,14 @@ bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime) // Call function push_v3s16(L, p); - lua_pushnumber(L,dtime); + lua_pushnumber(L, dtime); PCALL_RES(lua_pcall(L, 2, 1, error_handler)); lua_remove(L, error_handler); return readParam<bool>(L, -1, false); } -void ScriptApiNode::node_on_receive_fields(v3s16 p, - const std::string &formname, - const StringMap &fields, - ServerActiveObject *sender) +void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, + const StringMap &fields, ServerActiveObject *sender) { SCRIPTAPI_PRECHECKHEADER @@ -255,9 +246,9 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, return; // Call function - push_v3s16(L, p); // pos + push_v3s16(L, p); // pos lua_pushstring(L, formname.c_str()); // formname - lua_newtable(L); // fields + lua_newtable(L); // fields StringMap::const_iterator it; for (it = fields.begin(); it != fields.end(); ++it) { const std::string &name = it->first; @@ -266,7 +257,7 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, lua_pushlstring(L, value.c_str(), value.size()); lua_settable(L, -3); } - objectrefGetOrCreate(L, sender); // player + objectrefGetOrCreate(L, sender); // player PCALL_RES(lua_pcall(L, 4, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } diff --git a/src/script/cpp_api/s_node.h b/src/script/cpp_api/s_node.h index 81b44f0f0..8f4e41479 100644 --- a/src/script/cpp_api/s_node.h +++ b/src/script/cpp_api/s_node.h @@ -27,27 +27,23 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MapNode; class ServerActiveObject; -class ScriptApiNode - : virtual public ScriptApiBase, - public ScriptApiNodemeta +class ScriptApiNode : virtual public ScriptApiBase, public ScriptApiNodemeta { public: ScriptApiNode() = default; virtual ~ScriptApiNode() = default; - bool node_on_punch(v3s16 p, MapNode node, - ServerActiveObject *puncher, const PointedThing &pointed); - bool node_on_dig(v3s16 p, MapNode node, - ServerActiveObject *digger); + bool node_on_punch(v3s16 p, MapNode node, ServerActiveObject *puncher, + const PointedThing &pointed); + bool node_on_dig(v3s16 p, MapNode node, ServerActiveObject *digger); void node_on_construct(v3s16 p, MapNode node); void node_on_destruct(v3s16 p, MapNode node); bool node_on_flood(v3s16 p, MapNode node, MapNode newnode); void node_after_destruct(v3s16 p, MapNode node); bool node_on_timer(v3s16 p, MapNode node, f32 dtime); - void node_on_receive_fields(v3s16 p, - const std::string &formname, - const StringMap &fields, - ServerActiveObject *sender); + void node_on_receive_fields(v3s16 p, const std::string &formname, + const StringMap &fields, ServerActiveObject *sender); + public: static struct EnumString es_DrawType[]; static struct EnumString es_ContentParamType[]; diff --git a/src/script/cpp_api/s_nodemeta.cpp b/src/script/cpp_api/s_nodemeta.cpp index c081e9fc4..b7bd5f7c8 100644 --- a/src/script/cpp_api/s_nodemeta.cpp +++ b/src/script/cpp_api/s_nodemeta.cpp @@ -28,8 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Return number of accepted items to be moved int ScriptApiNodemeta::nodemeta_inventory_AllowMove( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -44,21 +43,23 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowMove( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", &ma.to_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", + &ma.to_inv.p)) return count; // function(pos, from_list, from_index, to_list, to_index, count, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 1, error_handler)); if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_move should" - " return a number, guilty node: " + nodename); + " return a number, guilty node: " + + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -66,8 +67,7 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiNodemeta::nodemeta_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -82,19 +82,21 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowPut( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", &ma.to_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", + &ma.to_inv.p)) return stack.count; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); - if(!lua_isnumber(L, -1)) + if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_put should" - " return a number, guilty node: " + nodename); + " return a number, guilty node: " + + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -102,8 +104,7 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiNodemeta::nodemeta_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -118,19 +119,21 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowTake( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", + &ma.from_inv.p)) return stack.count; // Call function(pos, listname, index, count, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_take should" - " return a number, guilty node: " + nodename); + " return a number, guilty node: " + + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -138,8 +141,7 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowTake( // Report moved items void ScriptApiNodemeta::nodemeta_inventory_OnMove( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -154,25 +156,25 @@ void ScriptApiNodemeta::nodemeta_inventory_OnMove( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", + &ma.from_inv.p)) return; // function(pos, from_list, from_index, to_list, to_index, count, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report put items void ScriptApiNodemeta::nodemeta_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -191,19 +193,18 @@ void ScriptApiNodemeta::nodemeta_inventory_OnPut( return; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report taken items void ScriptApiNodemeta::nodemeta_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -218,15 +219,16 @@ void ScriptApiNodemeta::nodemeta_inventory_OnTake( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", + &ma.from_inv.p)) return; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } diff --git a/src/script/cpp_api/s_nodemeta.h b/src/script/cpp_api/s_nodemeta.h index 8c7cdd93e..609898a30 100644 --- a/src/script/cpp_api/s_nodemeta.h +++ b/src/script/cpp_api/s_nodemeta.h @@ -26,9 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MoveAction; struct ItemStack; -class ScriptApiNodemeta - : virtual public ScriptApiBase, - public ScriptApiItem +class ScriptApiNodemeta : virtual public ScriptApiBase, public ScriptApiItem { public: ScriptApiNodemeta() = default; @@ -36,28 +34,22 @@ public: // Return number of accepted items to be moved int nodemeta_inventory_AllowMove( - const MoveAction &ma, int count, - ServerActiveObject *player); + const MoveAction &ma, int count, ServerActiveObject *player); // Return number of accepted items to be put - int nodemeta_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, + int nodemeta_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Return number of accepted items to be taken - int nodemeta_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, + int nodemeta_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report moved items void nodemeta_inventory_OnMove( - const MoveAction &ma, int count, - ServerActiveObject *player); + const MoveAction &ma, int count, ServerActiveObject *player); // Report put items - void nodemeta_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, + void nodemeta_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report taken items - void nodemeta_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, + void nodemeta_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); -private: +private: }; diff --git a/src/script/cpp_api/s_player.cpp b/src/script/cpp_api/s_player.cpp index 712120c61..c9ab81db9 100644 --- a/src/script/cpp_api/s_player.cpp +++ b/src/script/cpp_api/s_player.cpp @@ -39,7 +39,8 @@ void ScriptApiPlayer::on_newplayer(ServerActiveObject *player) runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player, const PlayerHPChangeReason &reason) +void ScriptApiPlayer::on_dieplayer( + ServerActiveObject *player, const PlayerHPChangeReason &reason) { SCRIPTAPI_PRECHECKHEADER @@ -56,11 +57,8 @@ void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player, const PlayerHPCha } bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, - ServerActiveObject *hitter, - float time_from_last_punch, - const ToolCapabilities *toolcap, - v3f dir, - s16 damage) + ServerActiveObject *hitter, float time_from_last_punch, + const ToolCapabilities *toolcap, v3f dir, s16 damage) { SCRIPTAPI_PRECHECKHEADER // Get core.registered_on_punchplayers @@ -77,8 +75,8 @@ bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, return readParam<bool>(L, -1); } -s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, - s32 hp_change, const PlayerHPChangeReason &reason) +s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, s32 hp_change, + const PlayerHPChangeReason &reason) { SCRIPTAPI_PRECHECKHEADER @@ -115,9 +113,7 @@ bool ScriptApiPlayer::on_respawnplayer(ServerActiveObject *player) } bool ScriptApiPlayer::on_prejoinplayer( - const std::string &name, - const std::string &ip, - std::string *reason) + const std::string &name, const std::string &ip, std::string *reason) { SCRIPTAPI_PRECHECKHEADER @@ -163,8 +159,7 @@ void ScriptApiPlayer::on_joinplayer(ServerActiveObject *player, s64 last_login) runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, - bool timeout) +void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, bool timeout) { SCRIPTAPI_PRECHECKHEADER @@ -177,8 +172,7 @@ void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_cheat(ServerActiveObject *player, - const std::string &cheat_type) +void ScriptApiPlayer::on_cheat(ServerActiveObject *player, const std::string &cheat_type) { SCRIPTAPI_PRECHECKHEADER @@ -194,8 +188,7 @@ void ScriptApiPlayer::on_cheat(ServerActiveObject *player, } void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, - const std::string &formname, - const StringMap &fields) + const std::string &formname, const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -220,7 +213,8 @@ void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC); } -void ScriptApiPlayer::on_authplayer(const std::string &name, const std::string &ip, bool is_success) +void ScriptApiPlayer::on_authplayer( + const std::string &name, const std::string &ip, bool is_success) { SCRIPTAPI_PRECHECKHEADER @@ -236,13 +230,12 @@ void ScriptApiPlayer::on_authplayer(const std::string &name, const std::string & } void ScriptApiPlayer::pushMoveArguments( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { lua_State *L = getStack(); objectrefGetOrCreate(L, player); // player - lua_pushstring(L, "move"); // action - InvRef::create(L, ma.from_inv); // inventory + lua_pushstring(L, "move"); // action + InvRef::create(L, ma.from_inv); // inventory lua_newtable(L); { // Table containing the action information @@ -261,15 +254,14 @@ void ScriptApiPlayer::pushMoveArguments( } } -void ScriptApiPlayer::pushPutTakeArguments( - const char *method, const InventoryLocation &loc, - const std::string &listname, int index, const ItemStack &stack, - ServerActiveObject *player) +void ScriptApiPlayer::pushPutTakeArguments(const char *method, + const InventoryLocation &loc, const std::string &listname, int index, + const ItemStack &stack, ServerActiveObject *player) { lua_State *L = getStack(); objectrefGetOrCreate(L, player); // player - lua_pushstring(L, method); // action - InvRef::create(L, loc); // inventory + lua_pushstring(L, method); // action + InvRef::create(L, loc); // inventory lua_newtable(L); { // Table containing the action information @@ -286,8 +278,7 @@ void ScriptApiPlayer::pushPutTakeArguments( // Return number of accepted items to be moved int ScriptApiPlayer::player_inventory_AllowMove( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -301,8 +292,7 @@ int ScriptApiPlayer::player_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiPlayer::player_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -316,8 +306,7 @@ int ScriptApiPlayer::player_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiPlayer::player_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -331,8 +320,7 @@ int ScriptApiPlayer::player_inventory_AllowTake( // Report moved items void ScriptApiPlayer::player_inventory_OnMove( - const MoveAction &ma, int count, - ServerActiveObject *player) + const MoveAction &ma, int count, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -344,8 +332,7 @@ void ScriptApiPlayer::player_inventory_OnMove( // Report put items void ScriptApiPlayer::player_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -357,8 +344,7 @@ void ScriptApiPlayer::player_inventory_OnPut( // Report taken items void ScriptApiPlayer::player_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/cpp_api/s_player.h b/src/script/cpp_api/s_player.h index a337f975b..5a1cf15b8 100644 --- a/src/script/cpp_api/s_player.h +++ b/src/script/cpp_api/s_player.h @@ -51,38 +51,33 @@ public: const PlayerHPChangeReason &reason); void on_playerReceiveFields(ServerActiveObject *player, const std::string &formname, const StringMap &fields); - void on_authplayer(const std::string &name, const std::string &ip, bool is_success); + void on_authplayer( + const std::string &name, const std::string &ip, bool is_success); // Player inventory callbacks // Return number of accepted items to be moved int player_inventory_AllowMove( - const MoveAction &ma, int count, - ServerActiveObject *player); + const MoveAction &ma, int count, ServerActiveObject *player); // Return number of accepted items to be put - int player_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + int player_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Return number of accepted items to be taken - int player_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + int player_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Report moved items void player_inventory_OnMove( - const MoveAction &ma, int count, - ServerActiveObject *player); + const MoveAction &ma, int count, ServerActiveObject *player); // Report put items - void player_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + void player_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Report taken items - void player_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + void player_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); + private: - void pushPutTakeArguments( - const char *method, const InventoryLocation &loc, - const std::string &listname, int index, const ItemStack &stack, - ServerActiveObject *player); - void pushMoveArguments(const MoveAction &ma, - int count, ServerActiveObject *player); + void pushPutTakeArguments(const char *method, const InventoryLocation &loc, + const std::string &listname, int index, const ItemStack &stack, + ServerActiveObject *player); + void pushMoveArguments( + const MoveAction &ma, int count, ServerActiveObject *player); }; diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index 9d65819c0..21bc7eb0a 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -29,19 +29,20 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <string> #include <iostream> - -#define SECURE_API(lib, name) \ - lua_pushcfunction(L, sl_##lib##_##name); \ +#define SECURE_API(lib, name) \ + lua_pushcfunction(L, sl_##lib##_##name); \ lua_setfield(L, -2, #name); - -static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1) +static inline void copy_safe(lua_State *L, const char *list[], unsigned len, + int from = -2, int to = -1) { - if (from < 0) from = lua_gettop(L) + from + 1; - if (to < 0) to = lua_gettop(L) + to + 1; + if (from < 0) + from = lua_gettop(L) + from + 1; + if (to < 0) + to = lua_gettop(L) + to + 1; for (unsigned i = 0; i < (len / sizeof(list[0])); i++) { lua_getfield(L, from, list[i]); - lua_setfield(L, to, list[i]); + lua_setfield(L, to, list[i]); } } @@ -50,91 +51,90 @@ static inline void push_original(lua_State *L, const char *lib, const char *func { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); lua_getfield(L, -1, lib); - lua_remove(L, -2); // Remove globals_backup + lua_remove(L, -2); // Remove globals_backup lua_getfield(L, -1, func); - lua_remove(L, -2); // Remove lib + lua_remove(L, -2); // Remove lib } - void ScriptApiSecurity::initializeSecurity() { static const char *whitelist[] = { - "assert", - "core", - "collectgarbage", - "DIR_DELIM", - "error", - "getfenv", - "getmetatable", - "ipairs", - "next", - "pairs", - "pcall", - "print", - "rawequal", - "rawget", - "rawset", - "select", - "setfenv", - "setmetatable", - "tonumber", - "tostring", - "type", - "unpack", - "_VERSION", - "xpcall", - // Completely safe libraries - "coroutine", - "string", - "table", - "math", + "assert", + "core", + "collectgarbage", + "DIR_DELIM", + "error", + "getfenv", + "getmetatable", + "ipairs", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawset", + "select", + "setfenv", + "setmetatable", + "tonumber", + "tostring", + "type", + "unpack", + "_VERSION", + "xpcall", + // Completely safe libraries + "coroutine", + "string", + "table", + "math", }; static const char *io_whitelist[] = { - "open", - "close", - "flush", - "read", - "type", - "write", + "open", + "close", + "flush", + "read", + "type", + "write", }; static const char *os_whitelist[] = { - "clock", - "date", - "difftime", - "getenv", - "setlocale", - "time", - "tmpname", + "clock", + "date", + "difftime", + "getenv", + "setlocale", + "time", + "tmpname", }; static const char *debug_whitelist[] = { - "gethook", - "traceback", - "getinfo", - "getmetatable", - "setupvalue", - "setmetatable", - "upvalueid", - "sethook", - "debug", - "setlocal", + "gethook", + "traceback", + "getinfo", + "getmetatable", + "setupvalue", + "setmetatable", + "upvalueid", + "sethook", + "debug", + "setlocal", }; static const char *package_whitelist[] = { - "config", - "cpath", - "path", - "searchpath", + "config", + "cpath", + "path", + "searchpath", }; #if USE_LUAJIT static const char *jit_whitelist[] = { - "arch", - "flush", - "off", - "on", - "opt", - "os", - "status", - "version", - "version_num", + "arch", + "flush", + "off", + "on", + "opt", + "os", + "status", + "version", + "version_num", }; #endif m_secure = true; @@ -154,7 +154,6 @@ void ScriptApiSecurity::initializeSecurity() lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); int old_globals = lua_gettop(L); - // Copy safe base functions lua_getglobal(L, "_G"); copy_safe(L, whitelist, sizeof(whitelist)); @@ -167,21 +166,19 @@ void ScriptApiSecurity::initializeSecurity() SECURE_API(g, require); lua_pop(L, 1); - // Copy safe IO functions lua_getfield(L, old_globals, "io"); lua_newtable(L); copy_safe(L, io_whitelist, sizeof(io_whitelist)); // And replace unsafe ones - //SECURE_API(io, open); + // SECURE_API(io, open); SECURE_API(io, input); SECURE_API(io, output); SECURE_API(io, lines); lua_setglobal(L, "io"); - lua_pop(L, 1); // Pop old IO - + lua_pop(L, 1); // Pop old IO // Copy safe OS functions lua_getfield(L, old_globals, "os"); @@ -193,23 +190,21 @@ void ScriptApiSecurity::initializeSecurity() SECURE_API(os, rename); lua_setglobal(L, "os"); - lua_pop(L, 1); // Pop old OS - + lua_pop(L, 1); // Pop old OS // Copy safe debug functions lua_getfield(L, old_globals, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); lua_setglobal(L, "debug"); - lua_pop(L, 1); // Pop old debug - + lua_pop(L, 1); // Pop old debug // Copy safe package fields lua_getfield(L, old_globals, "package"); lua_newtable(L); copy_safe(L, package_whitelist, sizeof(package_whitelist)); lua_setglobal(L, "package"); - lua_pop(L, 1); // Pop old package + lua_pop(L, 1); // Pop old package #if USE_LUAJIT // Copy safe jit functions, if they exist @@ -219,7 +214,7 @@ void ScriptApiSecurity::initializeSecurity() copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); lua_setglobal(L, "jit"); } - lua_pop(L, 1); // Pop old jit + lua_pop(L, 1); // Pop old jit #endif lua_pop(L, 1); // Pop globals_backup @@ -228,57 +223,49 @@ void ScriptApiSecurity::initializeSecurity() void ScriptApiSecurity::initializeSecurityClient() { static const char *whitelist[] = { - "assert", - "core", - "collectgarbage", - "DIR_DELIM", - "error", - "getfenv", - "ipairs", - "next", - "pairs", - "pcall", - "print", - "rawequal", - "rawget", - "rawset", - "select", - "setfenv", - // getmetatable can be used to escape the sandbox - "setmetatable", - "tonumber", - "tostring", - "type", - "unpack", - "_VERSION", - "xpcall", - // Completely safe libraries - "coroutine", - "string", - "table", - "math", - }; - static const char *os_whitelist[] = { - "clock", - "date", - "difftime", - "time" - }; - static const char *debug_whitelist[] = { - "getinfo", - "traceback" + "assert", + "core", + "collectgarbage", + "DIR_DELIM", + "error", + "getfenv", + "ipairs", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawset", + "select", + "setfenv", + // getmetatable can be used to escape the sandbox + "setmetatable", + "tonumber", + "tostring", + "type", + "unpack", + "_VERSION", + "xpcall", + // Completely safe libraries + "coroutine", + "string", + "table", + "math", }; + static const char *os_whitelist[] = {"clock", "date", "difftime", "time"}; + static const char *debug_whitelist[] = {"getinfo", "traceback"}; #if USE_LUAJIT static const char *jit_whitelist[] = { - "arch", - "flush", - "off", - "on", - "opt", - "os", - "status", - "version", - "version_num", + "arch", + "flush", + "off", + "on", + "opt", + "os", + "status", + "version", + "version_num", }; #endif @@ -312,16 +299,14 @@ void ScriptApiSecurity::initializeSecurityClient() lua_newtable(L); copy_safe(L, os_whitelist, sizeof(os_whitelist)); lua_setfield(L, -3, "os"); - lua_pop(L, 1); // Pop old OS - + lua_pop(L, 1); // Pop old OS // Copy safe debug functions lua_getglobal(L, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); lua_setfield(L, -3, "debug"); - lua_pop(L, 1); // Pop old debug - + lua_pop(L, 1); // Pop old debug #if USE_LUAJIT // Copy safe jit functions, if they exist @@ -329,7 +314,7 @@ void ScriptApiSecurity::initializeSecurityClient() lua_newtable(L); copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); lua_setfield(L, -3, "jit"); - lua_pop(L, 1); // Pop old jit + lua_pop(L, 1); // Pop old jit #endif // Set the environment to the one we created earlier @@ -339,9 +324,9 @@ void ScriptApiSecurity::initializeSecurityClient() int ScriptApiSecurity::getThread(lua_State *L) { #if LUA_VERSION_NUM <= 501 - int is_main = lua_pushthread(L); // Push the main thread + int is_main = lua_pushthread(L); // Push the main thread FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state " - "isn't the main Lua thread!"); + "isn't the main Lua thread!"); return lua_gettop(L); #endif return 0; @@ -349,21 +334,21 @@ int ScriptApiSecurity::getThread(lua_State *L) void ScriptApiSecurity::createEmptyEnv(lua_State *L) { - lua_newtable(L); // Create new environment + lua_newtable(L); // Create new environment lua_pushvalue(L, -1); - lua_setfield(L, -2, "_G"); // Create the _G loop + lua_setfield(L, -2, "_G"); // Create the _G loop } void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread) { -#if LUA_VERSION_NUM >= 502 // Lua >= 5.2 +#if LUA_VERSION_NUM >= 502 // Lua >= 5.2 // Set the global environment lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); -#else // Lua <= 5.1 - // Set the environment of the main thread +#else // Lua <= 5.1 + // Set the environment of the main thread FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set " - "environment of the main Lua thread!"); - lua_pop(L, 1); // Pop thread + "environment of the main Lua thread!"); + lua_pop(L, 1); // Pop thread #endif } @@ -375,7 +360,8 @@ bool ScriptApiSecurity::isSecure(lua_State *L) return secure; } -bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name) +bool ScriptApiSecurity::safeLoadString( + lua_State *L, const std::string &code, const char *chunk_name) { if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) { lua_pushliteral(L, "Bytecode prohibited when mod security is enabled."); @@ -386,7 +372,8 @@ bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, co return true; } -bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name) +bool ScriptApiSecurity::safeLoadFile( + lua_State *L, const char *path, const char *display_name) { FILE *fp; char *chunk_name; @@ -411,7 +398,8 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char int c = std::getc(fp); if (c == '#') { // Skip the first line - while ((c = std::getc(fp)) != EOF && c != '\n') {} + while ((c = std::getc(fp)) != EOF && c != '\n') { + } if (c == '\n') std::getc(fp); start = std::ftell(fp); @@ -423,7 +411,7 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete [] chunk_name; + delete[] chunk_name; } return false; } @@ -435,7 +423,7 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete [] chunk_name; + delete[] chunk_name; } return false; } @@ -446,31 +434,31 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char if (num_read != size) { lua_pushliteral(L, "Error reading file to load."); if (path) - delete [] chunk_name; + delete[] chunk_name; return false; } bool result = safeLoadString(L, code, chunk_name); if (path) - delete [] chunk_name; + delete[] chunk_name; return result; } - -bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, - bool write_required, bool *write_allowed) +bool ScriptApiSecurity::checkPath( + lua_State *L, const char *path, bool write_required, bool *write_allowed) { if (write_allowed) *write_allowed = false; - std::string str; // Transient + std::string str; // Transient std::string abs_path = fs::AbsolutePath(path); if (!abs_path.empty()) { // Don't allow accessing the settings file str = fs::AbsolutePath(g_settings_path); - if (str == abs_path) return false; + if (str == abs_path) + return false; } // If we couldn't find the absolute path (path doesn't exist) then @@ -482,15 +470,18 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, std::string component; cur_path = fs::RemoveLastPathComponent(cur_path, &component); if (component == "..") { - // Parent components can't be allowed or we could allow something like + // Parent components can't be allowed or we could allow something + // like // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd. - // If we have previous non-relative elements in the path we might be - // able to remove them so that things like worlds/foo/noexist/../auth.txt - // could be allowed, but those paths will be interpreted as nonexistent - // by the operating system anyways. + // If we have previous non-relative elements in the path we might + // be able to remove them so that things like + // worlds/foo/noexist/../auth.txt could be allowed, but those + // paths will be interpreted as nonexistent by the operating + // system anyways. return false; } - removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed); + removed.append(component).append( + removed.empty() ? "" : DIR_DELIM + removed); abs_path = fs::AbsolutePath(cur_path); } if (abs_path.empty()) @@ -504,9 +495,9 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *script; #if INDIRECT_SCRIPTAPI_RIDX - script = (ScriptApiBase *) *(void**)(lua_touserdata(L, -1)); + script = (ScriptApiBase *)*(void **)(lua_touserdata(L, -1)); #else - script = (ScriptApiBase *) lua_touserdata(L, -1); + script = (ScriptApiBase *)lua_touserdata(L, -1); #endif lua_pop(L, 1); const IGameDef *gamedef = script->getGameDef(); @@ -520,24 +511,27 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, // Builtin can access anything if (mod_name == BUILTIN_MOD_NAME) { - if (write_allowed) *write_allowed = true; + if (write_allowed) + *write_allowed = true; return true; } // Allow paths in mod path - // Don't bother if write access isn't important, since it will be handled later + // Don't bother if write access isn't important, since it will be handled + // later if (write_required || write_allowed != NULL) { const ModSpec *mod = gamedef->getModSpec(mod_name); if (mod) { str = fs::AbsolutePath(mod->path); if (!str.empty() && fs::PathStartsWith(abs_path, str)) { - if (write_allowed) *write_allowed = true; + if (write_allowed) + *write_allowed = true; return true; } } } } - lua_pop(L, 1); // Pop mod name + lua_pop(L, 1); // Pop mod name // Allow read-only access to all mod directories if (!write_required) { @@ -564,7 +558,8 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, } // Allow all other paths in world path if (fs::PathStartsWith(abs_path, str)) { - if (write_allowed) *write_allowed = true; + if (write_allowed) + *write_allowed = true; return true; } } @@ -573,7 +568,6 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, return false; } - int ScriptApiSecurity::sl_g_dofile(lua_State *L) { int nret = sl_g_loadfile(L); @@ -588,7 +582,6 @@ int ScriptApiSecurity::sl_g_dofile(lua_State *L) return lua_gettop(L) - (top_precall - 1); } - int ScriptApiSecurity::sl_g_load(lua_State *L) { size_t len; @@ -627,12 +620,11 @@ int ScriptApiSecurity::sl_g_load(lua_State *L) return 1; } - int ScriptApiSecurity::sl_g_loadfile(lua_State *L) { #ifndef SERVER lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); - ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1); + ScriptApiBase *script = (ScriptApiBase *)lua_touserdata(L, -1); lua_pop(L, 1); // Client implementation @@ -672,7 +664,6 @@ int ScriptApiSecurity::sl_g_loadfile(lua_State *L) return 1; } - int ScriptApiSecurity::sl_g_loadstring(lua_State *L) { const char *chunk_name = "=(load)"; @@ -695,14 +686,12 @@ int ScriptApiSecurity::sl_g_loadstring(lua_State *L) return 1; } - int ScriptApiSecurity::sl_g_require(lua_State *L) { lua_pushliteral(L, "require() is disabled when mod security is on."); return lua_error(L); } - int ScriptApiSecurity::sl_io_open(lua_State *L) { bool with_mode = lua_gettop(L) > 1; @@ -715,8 +704,7 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) luaL_checktype(L, 2, LUA_TSTRING); const char *mode = lua_tostring(L, 2); write_requested = strchr(mode, 'w') != NULL || - strchr(mode, '+') != NULL || - strchr(mode, 'a') != NULL; + strchr(mode, '+') != NULL || strchr(mode, 'a') != NULL; } CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL); @@ -730,7 +718,6 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) return 2; } - int ScriptApiSecurity::sl_io_input(lua_State *L) { if (lua_isstring(L, 1)) { @@ -744,7 +731,6 @@ int ScriptApiSecurity::sl_io_input(lua_State *L) return 1; } - int ScriptApiSecurity::sl_io_output(lua_State *L) { if (lua_isstring(L, 1)) { @@ -758,7 +744,6 @@ int ScriptApiSecurity::sl_io_output(lua_State *L) return 1; } - int ScriptApiSecurity::sl_io_lines(lua_State *L) { if (lua_isstring(L, 1)) { @@ -775,7 +760,6 @@ int ScriptApiSecurity::sl_io_lines(lua_State *L) return lua_gettop(L) - top_precall; } - int ScriptApiSecurity::sl_os_rename(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -793,7 +777,6 @@ int ScriptApiSecurity::sl_os_rename(lua_State *L) return 2; } - int ScriptApiSecurity::sl_os_remove(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -805,4 +788,3 @@ int ScriptApiSecurity::sl_os_remove(lua_State *L) lua_call(L, 1, 2); return 2; } - diff --git a/src/script/cpp_api/s_security.h b/src/script/cpp_api/s_security.h index 73e763548..075950845 100644 --- a/src/script/cpp_api/s_security.h +++ b/src/script/cpp_api/s_security.h @@ -21,22 +21,20 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_base.h" - -#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \ - if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \ - throw LuaError(std::string("Mod security: Blocked attempted ") + \ - (write_required ? "write to " : "read from ") + path); \ +#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \ + if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \ + throw LuaError(std::string("Mod security: Blocked attempted ") + \ + (write_required ? "write to " : "read from ") + path); \ } -#define CHECK_SECURE_PATH(L, path, write_required) \ - if (ScriptApiSecurity::isSecure(L)) { \ - CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \ +#define CHECK_SECURE_PATH(L, path, write_required) \ + if (ScriptApiSecurity::isSecure(L)) { \ + CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \ } -#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \ - if (ScriptApiSecurity::isSecure(L)) { \ - CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \ +#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \ + if (ScriptApiSecurity::isSecure(L)) { \ + CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \ } - class ScriptApiSecurity : virtual public ScriptApiBase { public: @@ -51,12 +49,14 @@ public: // Checks if the Lua state has been secured static bool isSecure(lua_State *L); // Loads a string as Lua code safely (doesn't allow bytecode). - static bool safeLoadString(lua_State *L, const std::string &code, const char *chunk_name); + static bool safeLoadString( + lua_State *L, const std::string &code, const char *chunk_name); // Loads a file as Lua code safely (doesn't allow bytecode). - static bool safeLoadFile(lua_State *L, const char *path, const char *display_name = NULL); + static bool safeLoadFile( + lua_State *L, const char *path, const char *display_name = NULL); // Checks if mods are allowed to read (and optionally write) to the path static bool checkPath(lua_State *L, const char *path, bool write_required, - bool *write_allowed=NULL); + bool *write_allowed = NULL); private: // Syntax: "sl_" <Library name or 'g' (global)> '_' <Function name> diff --git a/src/script/cpp_api/s_server.cpp b/src/script/cpp_api/s_server.cpp index 96cb28b28..1cb3f99f1 100644 --- a/src/script/cpp_api/s_server.cpp +++ b/src/script/cpp_api/s_server.cpp @@ -21,10 +21,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_internal.h" #include "common/c_converter.h" -bool ScriptApiServer::getAuth(const std::string &playername, - std::string *dst_password, - std::set<std::string> *dst_privs, - s64 *dst_last_login) +bool ScriptApiServer::getAuth(const std::string &playername, std::string *dst_password, + std::set<std::string> *dst_privs, s64 *dst_last_login) { SCRIPTAPI_PRECHECKHEADER @@ -54,10 +52,10 @@ bool ScriptApiServer::getAuth(const std::string &playername, throw LuaError("Authentication handler didn't return privilege table"); if (dst_privs) readPrivileges(-1, *dst_privs); - lua_pop(L, 1); // Remove key from privs table + lua_pop(L, 1); // Remove key from privs table s64 last_login; - if(!getintfield(L, -1, "last_login", last_login)) + if (!getintfield(L, -1, "last_login", last_login)) throw LuaError("Authentication handler didn't return last_login"); if (dst_last_login) *dst_last_login = (s64)last_login; @@ -71,7 +69,7 @@ void ScriptApiServer::getAuthHandler() lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_auth_handler"); - if (lua_isnil(L, -1)){ + if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_getfield(L, -1, "builtin_auth_handler"); } @@ -102,8 +100,8 @@ void ScriptApiServer::readPrivileges(int index, std::set<std::string> &result) } } -void ScriptApiServer::createAuth(const std::string &playername, - const std::string &password) +void ScriptApiServer::createAuth( + const std::string &playername, const std::string &password) { SCRIPTAPI_PRECHECKHEADER @@ -119,8 +117,8 @@ void ScriptApiServer::createAuth(const std::string &playername, lua_pop(L, 1); // Pop error handler } -bool ScriptApiServer::setPassword(const std::string &playername, - const std::string &password) +bool ScriptApiServer::setPassword( + const std::string &playername, const std::string &password) { SCRIPTAPI_PRECHECKHEADER @@ -137,8 +135,7 @@ bool ScriptApiServer::setPassword(const std::string &playername, return lua_toboolean(L, -1); } -bool ScriptApiServer::on_chat_message(const std::string &name, - const std::string &message) +bool ScriptApiServer::on_chat_message(const std::string &name, const std::string &message) { SCRIPTAPI_PRECHECKHEADER @@ -174,8 +171,8 @@ void ScriptApiServer::on_shutdown() runCallbacks(0, RUN_CALLBACKS_MODE_FIRST); } -std::string ScriptApiServer::formatChatMessage(const std::string &name, - const std::string &message) +std::string ScriptApiServer::formatChatMessage( + const std::string &name, const std::string &message) { SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/cpp_api/s_server.h b/src/script/cpp_api/s_server.h index d8639cba7..db574bd56 100644 --- a/src/script/cpp_api/s_server.h +++ b/src/script/cpp_api/s_server.h @@ -22,8 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_base.h" #include <set> -class ScriptApiServer - : virtual public ScriptApiBase +class ScriptApiServer : virtual public ScriptApiBase { public: // Calls on_chat_message handlers @@ -37,18 +36,15 @@ public: void on_shutdown(); // Calls core.format_chat_message - std::string formatChatMessage(const std::string &name, - const std::string &message); + std::string formatChatMessage( + const std::string &name, const std::string &message); /* auth */ - bool getAuth(const std::string &playername, - std::string *dst_password, - std::set<std::string> *dst_privs, - s64 *dst_last_login = nullptr); - void createAuth(const std::string &playername, - const std::string &password); - bool setPassword(const std::string &playername, - const std::string &password); + bool getAuth(const std::string &playername, std::string *dst_password, + std::set<std::string> *dst_privs, s64 *dst_last_login = nullptr); + void createAuth(const std::string &playername, const std::string &password); + bool setPassword(const std::string &playername, const std::string &password); + private: void getAuthHandler(); void readPrivileges(int index, std::set<std::string> &result); |