From 3ae8d4e72ed13d9d723ffc4546cfab393eda23d0 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 08:54:00 +0100 Subject: [PATCH] fix(scripting): typed scenery handles, sandbox keys from eu07.ini only, GCC 13 build - the scenery API (eu07.events) hands out a full userdata of its own locked metatable for each kind of object (event, track, isolated, vehicle, memcell), checked with luaL_checkudata: a handle of another kind, a light userdata or any other value is a Lua error, not an object taken for another. nil stays "no object". one object has one handle while the script holds it, so handles compare and key tables as before. event handlers get their handles built inside lua_cpcall, and nil for no activator - memcell_values keeps its text as a std::string: the text of a number was read from a stack slot popped before use - newproxy is gone from the sandboxed libraries - a config block of a scenery no longer changes what only eu07.ini sets (lua.fulllibraries, execonexit, extcam.cmd/rec, screenshotsdir, network.server/client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport, python/luascreens/wasm.enabled): kept before its keys are read, put back before FinalizeConfig(), each attempt logged - open_file_library() iterates luaL_Reg instead of a std::pair GCC 13 deduces as a pair of an array and a function --- CMakeLists.txt | 1 + script_screens_doc.md | 13 ++- scripting/lua.cpp | 73 +++++++++----- scripting/lua.h | 4 +- scripting/luasandbox.cpp | 87 ++++++++++++++++- scripting/luasandbox.h | 33 +++++++ simulation/simulationstateserializer.cpp | 5 +- tests/unit/test_ini_only_settings.cpp | 116 +++++++++++++++++++++++ tests/unit/test_lua_sandbox.cpp | 110 ++++++++++++++++++++- utilities/Globals.cpp | 17 +++- utilities/Globals.h | 10 +- utilities/inionlysettings.cpp | 82 ++++++++++++++++ utilities/inionlysettings.h | 55 +++++++++++ 13 files changed, 571 insertions(+), 35 deletions(-) create mode 100644 tests/unit/test_ini_only_settings.cpp create mode 100644 utilities/inionlysettings.cpp create mode 100644 utilities/inionlysettings.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b73b0805..eb3e12aff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -541,6 +541,7 @@ set(CORE_SOURCES "McZapkie/Oerlikon_ESt.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/inionlysettings.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" diff --git a/script_screens_doc.md b/script_screens_doc.md index 435706fe4..7ebf14caf 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -221,7 +221,13 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; - a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on - loading. An event handler that fails is logged with the name of the event, and the simulation goes on. + loading. An event handler that fails is logged with the name of the event, and the simulation goes on; +- the events, tracks, isolated circuits, memcells and vehicles the functions give (`event_find`, `track_find`, + `memcell_find`, the event and the vehicle an event handler gets...) are handles of their kind: equal for the same + object, usable as keys of a table, and taken only where that kind goes. Another kind, or any other value, is an + error (`bad argument #1 to 'memcell_update' (eu07.memcell expected, got userdata)`); `nil`, which the find + functions give for a missing object, is taken as no object, as before. An event run without a vehicle gives its + handler `nil` for the vehicle. Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: @@ -257,3 +263,8 @@ again: | key | default | meaning | |---------------------|---------|------------------------------------------------------------------------------------------| | `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | + +Only `eu07.ini` sets it: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, +`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`feedbackmode`, `feedbackport`, `python.enabled`, `luascreens.enabled` and `wasm.enabled`. diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 7079bb2c3..2011413b5 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -18,6 +18,9 @@ lua::lua() // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) lua_sandbox::open_safe_libraries(state); lua_sandbox::open_clock_library(state); + // the events, tracks, isolated circuits, vehicles and memcells a script holds: a userdata of a metatable of each + // kind, which the functions check + lua_sandbox::open_handles(state); static constexpr luaL_Reg api[] = { @@ -100,14 +103,33 @@ void lua::unref(lua_State *L, const int ref) luaL_unref(L, LUA_REGISTRYINDEX, ref); } +namespace { + +struct event_call { + int handler; + basic_event *event; + TDynamicObject *activator; +}; + +// calls the handler of the event (event_call) with the handles of the event and its activator (nil when there is none) +int call_handler(lua_State *L) +{ + auto const &call = *static_cast(lua_touserdata(L, 1)); + lua_rawgeti(L, LUA_REGISTRYINDEX, call.handler); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, call.event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::vehicle, call.activator); + lua_call(L, 2, 0); + return 0; +} + +} // namespace + /// Executes the callback function of an event created with `scriptapi_event_create`. void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, const TDynamicObject *activator) { - lua_rawgeti(L, LUA_REGISTRYINDEX, handler); - lua_pushlightuserdata(L, event); - lua_pushlightuserdata(L, const_cast(activator)); - // in protected mode: a handler that fails is logged, and the simulation goes on - if (lua_pcall(L, 2, 0, 0) != 0) { + event_call call{handler, event, const_cast(activator)}; + // in protected mode, the handles made as well: a handler that fails is logged, and the simulation goes on + if (lua_cpcall(L, call_handler, &call) != 0) { auto const *error = lua_tostring(L, -1); ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); lua_pop(L, 1); @@ -133,12 +155,17 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - // no text in the table is an empty one: the memcell and the vehicle take the text as a string + luaL_checktype(L, idx, LUA_TTABLE); + // no text in the table is an empty one: the memcell and the vehicle take the text as a string. copied: the text of + // a number is made on the stack, and gone with it memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); - if (lua_isstring(L, -1)) - mc.str = lua_tostring(L, -1); + if (lua_isstring(L, -1)) { + std::size_t length = 0; + auto const *text = lua_tolstring(L, -1, &length); + mc.str.assign(text, length); + } lua_pop(L, 1); lua_pushstring(L, "num1"); lua_gettable(L, idx); @@ -167,7 +194,7 @@ int lua::scriptapi_event_create(lua_State *L) event->m_delayrandom = randomdelay; if (simulation::Events.insert(event)) { - lua_pushlightuserdata(L, event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, event); return 1; } return 0; @@ -179,7 +206,7 @@ int lua::scriptapi_event_find(lua_State *L) basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { - lua_pushlightuserdata(L, foundevent); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, foundevent); return 1; } ErrorLog("lua: missing event: " + name); @@ -196,7 +223,7 @@ int lua::scriptapi_event_exists(lua_State *L) int lua::scriptapi_event_getname(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); if (event) { lua_pushstring(L, event->m_name.c_str()); @@ -207,8 +234,8 @@ int lua::scriptapi_event_getname(lua_State *L) int lua::scriptapi_event_dispatch(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); if (event) simulation::Events.AddToQuery(event, activator, delay); @@ -218,7 +245,7 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { std::string name = luaL_checkstring(L, 1); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) @@ -234,7 +261,7 @@ int lua::scriptapi_track_find(lua_State *L) TTrack *track = simulation::Paths.find(name); if (track) { - lua_pushlightuserdata(L, track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, track); return 1; } ErrorLog("lua: missing track: " + name); @@ -243,7 +270,7 @@ int lua::scriptapi_track_find(lua_State *L) int lua::scriptapi_track_isoccupied(lua_State *L) { - auto *track = static_cast(lua_touserdata(L, 1)); + auto *track = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track); if (track) { lua_pushboolean(L, !track->IsEmpty()); @@ -271,7 +298,7 @@ int lua::scriptapi_isolated_find(lua_State *L) TIsolated *isolated = TIsolated::Find(name); if (isolated) { - lua_pushlightuserdata(L, isolated); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::isolated, isolated); return 1; } ErrorLog("lua: missing isolated: " + name); @@ -280,7 +307,7 @@ int lua::scriptapi_isolated_find(lua_State *L) int lua::scriptapi_isolated_isoccupied(lua_State *L) { - auto *isolated = static_cast(lua_touserdata(L, 1)); + auto *isolated = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::isolated); if (isolated) { lua_pushboolean(L, isolated->Busy()); @@ -304,7 +331,7 @@ int lua::scriptapi_isolated_isoccupied_n(lua_State *L) int lua::scriptapi_train_getname(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); if (dyn && dyn->Mechanik) { lua_pushstring(L, dyn->Mechanik->TrainName().c_str()); @@ -315,7 +342,7 @@ int lua::scriptapi_train_getname(lua_State *L) int lua::scriptapi_dynobj_putvalues(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); auto [str, num1, num2] = get_memcell_values(L, 2); if (!dyn) return 0; @@ -333,7 +360,7 @@ int lua::scriptapi_memcell_find(lua_State *L) TMemCell *mc = simulation::Memory.find(str); if (mc) { - lua_pushlightuserdata(L, mc); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, mc); return 1; } ErrorLog("lua: missing memcell: " + str); @@ -342,7 +369,7 @@ int lua::scriptapi_memcell_find(lua_State *L) int lua::scriptapi_memcell_read(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); push_memcell_values(L, mc); return 1; } @@ -359,7 +386,7 @@ int lua::scriptapi_memcell_read_n(lua_State *L) int lua::scriptapi_memcell_update(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); auto [str, num1, num2] = get_memcell_values(L, 2); if (mc) mc->UpdateValues(str, num1, num2, diff --git a/scripting/lua.h b/scripting/lua.h index a0a2b9333..dc28a01e4 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -3,10 +3,12 @@ #include #include "scripting/luasandbox.h" +#include + class basic_event; class TMemCell; class TDynamicObject; -struct memcell_values { const char *str; double num1; double num2; }; +struct memcell_values { std::string str; double num1; double num2; }; class lua { diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index bf6ab3961..16e7f70ba 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreenrules.h" #include +#include #include #include #include @@ -76,8 +77,9 @@ void open_safe_libraries(lua_State *L) open_library(L, luaopen_string, LUA_STRLIBNAME); open_library(L, luaopen_math, LUA_MATHLIBNAME); open_library(L, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hooks (the instruction limit of the Lua screens), at any allocation and in lua_close + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) { lua_pushnil(L); lua_setglobal(L, name); @@ -430,8 +432,9 @@ void open_file_library(lua_State *L, file_folders const *Folders) lua_pushvalue(L, -1); lua_setglobal(L, "eu07"); } - for (auto const &[name, function] : {std::pair{"read_file", api_read_file}, std::pair{"write_file", api_write_file}, - std::pair{"read_data_file", api_read_data_file}}) + // luaL_Reg, not std::pair: GCC deduces std::pair{"read_file", api_read_file} as a pair of an array and a function + static constexpr luaL_Reg functions[]{{"read_file", api_read_file}, {"write_file", api_write_file}, {"read_data_file", api_read_data_file}}; + for (auto const &[name, function] : functions) { lua_pushlightuserdata(L, const_cast(Folders)); lua_pushcclosure(L, function, 1); @@ -440,4 +443,80 @@ void open_file_library(lua_State *L, file_folders const *Folders) lua_pop(L, 1); } +namespace +{ + +constexpr std::array handle_names{"eu07.event", "eu07.track", "eu07.isolated", "eu07.vehicle", "eu07.memcell"}; +// the addresses are the keys of the handles of each kind in the registry: the objects, to their userdata +constexpr std::array handle_cache_keys{}; + +void *cache_key(handle_kind const Kind) +{ + return const_cast(&handle_cache_keys[static_cast(Kind)]); // NOSONAR: the address is only a key +} + +} // namespace + +char const *handle_name(handle_kind const Kind) +{ + return handle_names[static_cast(Kind)]; +} + +void open_handles(lua_State *L) +{ + for (std::size_t idx = 0; idx < handle_names.size(); ++idx) + { + auto const kind{static_cast(idx)}; + luaL_newmetatable(L, handle_name(kind)); + // getmetatable() of a handle gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); + lua_pop(L, 1); + // the handles made, weak: a handle the script dropped is collected, and made again when asked for + lua_pushlightuserdata(L, cache_key(kind)); + lua_newtable(L); + lua_createtable(L, 0, 1); + lua_pushliteral(L, "v"); + lua_setfield(L, -2, "__mode"); + lua_setmetatable(L, -2); + lua_rawset(L, LUA_REGISTRYINDEX); + } +} + +void push_handle(lua_State *L, handle_kind const Kind, void *Object) +{ + if (Object == nullptr) + { + lua_pushnil(L); + return; + } + lua_pushlightuserdata(L, cache_key(Kind)); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_pushlightuserdata(L, Object); + lua_rawget(L, -2); + if (false == lua_isnil(L, -1)) + { + // the cache, the handle + lua_remove(L, -2); + return; + } + lua_pop(L, 1); + *static_cast(lua_newuserdata(L, sizeof(void *))) = Object; + luaL_getmetatable(L, handle_name(Kind)); + lua_setmetatable(L, -2); + lua_pushlightuserdata(L, Object); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + lua_remove(L, -2); +} + +void *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + if (lua_isnoneornil(L, Index)) + { + return nullptr; + } + return *static_cast(luaL_checkudata(L, Index, handle_name(Kind))); +} + } // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index 5f57c62af..dfb1cd024 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -98,4 +98,37 @@ struct file_folders // Folders, read on every call: Folders is to outlive the state void open_file_library(lua_State *L, file_folders const *Folders); +// the objects of the simulation a scenery script holds (eu07.events): each kind is a userdata of a metatable of its +// own, so a function given the handle of another kind, a light userdata or anything else raises a Lua error, and never +// takes one object for another. the objects outlive the state (the scenery's events, tracks, memcells and isolated +// track circuits, and its vehicles, which the game takes off the tracks but doesn't delete) +enum class handle_kind +{ + event, + track, + isolated, + vehicle, + memcell +}; + +// the name of the metatable of the kind, as the errors give it ("eu07.memcell expected, got userdata") +char const *handle_name(handle_kind Kind); + +// makes the metatables of the handles; once, before the first handle. a script can't reach them (getmetatable gives +// false) +void open_handles(lua_State *L); + +// pushes the handle of Object, of the kind, or nil for nullptr. one object has one handle while the script holds it: +// the handles of an object found twice are equal, and the same key of a table +void push_handle(lua_State *L, handle_kind Kind, void *Object); + +// the object of the handle at Index: nullptr for nil or nothing (what the find functions give for a missing object), +// a Lua error (bad argument) for anything else than a handle of the kind +void *check_handle(lua_State *L, int Index, handle_kind Kind); + +template Type_ *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + return static_cast(check_handle(L, Index, Kind)); +} + } // namespace lua_sandbox diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index c39870600..b93c69f2d 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -362,8 +362,9 @@ state_serializer::deserialize_camera( cParser &Input, scene::scratch_data &Scrat void state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scratchpad ) { - // config parameters (re)definition - Global.ConfigParse( Input ); + // config parameters (re)definition, but for what only eu07.ini sets: programs to run, connections, the sandbox of + // the scripts (utilities/inionlysettings.h) + Global.ConfigParse( Input, config_source::scenery ); if( Global.test.enabled ) { // a scenery doesn't get to turn on what a test keeps off simulation::apply_test_mode_settings(); diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp new file mode 100644 index 000000000..8ae73fe43 --- /dev/null +++ b/tests/unit/test_ini_only_settings.cpp @@ -0,0 +1,116 @@ +#include "stdafx.h" +#include "doctest.h" + +// the settings only eu07.ini sets (utilities/inionlysettings.h): a config block of a scenery is read by the parser of +// eu07.ini (global_settings::ConfigParse with config_source::scenery), which keeps these as eu07.ini set them, and puts +// them back before FinalizeConfig() acts on any. here the keeping, as ConfigParse does it around the keys of a scenery + +#include "utilities/Globals.h" +#include "utilities/inionlysettings.h" + +#include +#include +#include +#include + +namespace { + +bool listed(std::vector const &Keys, std::string_view const Key) { + return std::ranges::find(Keys, Key) != Keys.end(); +} + +} // namespace + +TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts all libraries") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = false; + ini_only_settings const ini{*settings}; + // "config lua.fulllibraries yes endconfig" in the .scn + settings->lua_fulllibraries = true; + auto const changed{ini.restore(*settings)}; + CHECK_FALSE(settings->lua_fulllibraries); + CHECK(changed == std::vector{"lua.fulllibraries"}); +} + +TEST_CASE("ini only settings: what eu07.ini turned on stays on") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = true; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + settings->lua_fulllibraries = false; + settings->python_enabled = true; + auto const changed{ini.restore(*settings)}; + CHECK(settings->lua_fulllibraries); + CHECK_FALSE(settings->python_enabled); + CHECK(changed.size() == 2); +} + +TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { + auto const settings{std::make_unique()}; + settings->luascreens_enabled = false; + settings->wasm_enabled = false; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + + settings->exec_on_exit = "cmd /c del something"; + settings->extcam_cmd = "evil.exe"; + settings->extcam_rec = "evil.exe"; + settings->screenshot_dir = "C:/Users/Public"; + settings->network_servers.emplace_back("tcp", "0.0.0.0:7424"); + settings->network_client.emplace("tcp", "example.com:7424"); + settings->motiontelemetry_conf.enable = true; + settings->motiontelemetry_conf.address = "example.com"; + settings->iFeedbackMode = 4; + settings->iFeedbackPort = 0x378; + settings->luascreens_enabled = true; + settings->wasm_enabled = true; + settings->python_enabled = true; +#ifdef WITH_UART + settings->uart_conf.enable = true; + settings->uart_conf.port = "COM1"; +#endif +#ifdef WITH_ZMQ + settings->zmq_address = "tcp://*:5555"; +#endif + // and a key a scenery may set + settings->fFriction = 0.5; + + auto const changed{ini.restore(*settings)}; + CHECK(settings->exec_on_exit.empty()); + CHECK(settings->extcam_cmd.empty()); + CHECK(settings->extcam_rec.empty()); + CHECK(settings->screenshot_dir.empty()); + CHECK(settings->network_servers.empty()); + CHECK_FALSE(settings->network_client.has_value()); + CHECK_FALSE(settings->motiontelemetry_conf.enable); + CHECK(settings->motiontelemetry_conf.address.empty()); + CHECK(settings->iFeedbackMode == 1); + CHECK(settings->iFeedbackPort == 0); + CHECK_FALSE(settings->luascreens_enabled); + CHECK_FALSE(settings->wasm_enabled); + CHECK_FALSE(settings->python_enabled); + for (auto const *key : {"execonexit", "extcam.cmd", "extcam.rec", "screenshotsdir", "network.server", "network.client", "motiontelemetry", + "feedbackmode", "feedbackport", "luascreens.enabled", "wasm.enabled", "python.enabled"}) { + CAPTURE(key); + CHECK(listed(changed, key)); + } +#ifdef WITH_UART + CHECK_FALSE(settings->uart_conf.enable); + CHECK(settings->uart_conf.port.empty()); + CHECK(listed(changed, "uart")); +#endif +#ifdef WITH_ZMQ + CHECK(settings->zmq_address.empty()); + CHECK(listed(changed, "zmq.address")); +#endif + // the rest is the scenery's to set + CHECK(settings->fFriction == doctest::Approx(0.5)); +} + +TEST_CASE("ini only settings: nothing changed, nothing to tell") { + auto const settings{std::make_unique()}; + settings->exec_on_exit = "notify.exe"; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(settings->exec_on_exit == "notify.exe"); +} diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index 344f51c63..bc0753162 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -65,7 +65,7 @@ bool contains(std::string_view const Text, std::string_view const Part) { TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { sandboxed_state const lua; for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", - "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "newproxy", "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", "os.setlocale"}) { CAPTURE(name); CHECK(lua.run(std::format("return {}", name)) == "nil"); @@ -424,4 +424,112 @@ TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); } +TEST_CASE("lua sandbox: no userdata of the script's own, whose __gc would run without the hooks") { + sandboxed_state const lua; + CHECK(lua.run("return newproxy") == "nil"); + // a table's __gc isn't called (Lua 5.1, LuaJIT): no other way to a finalizer of the script's own + CHECK(lua.run("collected = false setmetatable({}, { __gc = function() collected = true end }) collectgarbage() collectgarbage() return collected") == + "false"); +} + +namespace { + +// two objects of the simulation, of which a script holds handles +int memcell_object{1}; +int track_object{2}; + +// eu07.test_memcell(handle): the number of the memcell object, nil for none; eu07.test_track(handle) likewise +int test_memcell(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +int test_track(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +// a state with the handles, the functions above, and the globals memcell, track (handles), memcell2 (the memcell's +// handle pushed again) and light (a light userdata, which a script can't make, as the game gave them before) +class handle_state : public sandboxed_state { + public: + handle_state() { + auto *L{get()}; + lua_sandbox::open_handles(L); + lua_register(L, "test_memcell", test_memcell); + lua_register(L, "test_track", test_track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell2"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &track_object); + lua_setglobal(L, "track"); + // the address of the memcell as a handle of another kind: told apart all the same + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &memcell_object); + lua_setglobal(L, "memcell_as_track"); + lua_pushlightuserdata(L, &memcell_object); + lua_setglobal(L, "light"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, nullptr); + lua_setglobal(L, "none"); + } +}; + +} // namespace + +TEST_CASE("lua sandbox: a handle of the scenery api reaches the object of its kind") { + handle_state const lua; + CHECK(lua.run("return test_memcell(memcell)") == "1"); + CHECK(lua.run("return test_track(track)") == "2"); + CHECK(lua.run("return type(memcell)") == "userdata"); + // what the find functions give for a missing object, and what the functions take as no object + CHECK(lua.run("return none") == "nil"); + CHECK(lua.run("return test_memcell(nil)") == "nil"); + CHECK(lua.run("return test_memcell()") == "nil"); + // one object, one handle: equal, and the same key of a table + CHECK(lua.run("return rawequal(memcell, memcell2)") == "true"); + CHECK(lua.run("local t = { [memcell] = 'cell' } return t[memcell2]") == "cell"); + CHECK(lua.run("return rawequal(memcell, memcell_as_track)") == "false"); + // the handle of a dropped handle is made again + REQUIRE_FALSE(luaL_dostring(lua.get(), "memcell = nil memcell2 = nil collectgarbage() collectgarbage()")); + lua_sandbox::push_handle(lua.get(), lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(lua.get(), "memcell"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a handle of another kind, or anything else, is a Lua error and not an object") { + handle_state const lua; + // a track where a memcell goes (memcell_update(track_find(...)) once wrote into a track as a memcell). not a tail + // call, which LuaJIT gives no function name in the message + CHECK(contains(lua.run("local r = test_memcell(track) return r"), "bad argument #1 to 'test_memcell' (eu07.memcell expected, got userdata)")); + CHECK(contains(lua.run("local r = test_track(memcell) return r"), "bad argument #1 to 'test_track' (eu07.track expected, got userdata)")); + CHECK(contains(lua.run("return test_memcell(memcell_as_track)"), "eu07.memcell expected")); + CHECK(contains(lua.run("return test_memcell(light)"), "eu07.memcell expected, got userdata")); + for (auto const *value : {"1", "'memcell'", "{}", "true", "false", "print", "coroutine.create(function() end)"}) { + CAPTURE(value); + CHECK(contains(lua.run(std::format("return test_memcell({})", value)), "eu07.memcell expected")); + } + // the error is the script's: caught by pcall, and the state goes on + CHECK(lua.run("return (pcall(test_memcell, track))") == "false"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a script can't reach the metatable of a handle") { + handle_state const lua; + CHECK(lua.run("return getmetatable(memcell)") == "false"); + CHECK(contains(lua.run("local r = setmetatable(memcell, {}) return r"), "bad argument #1 to 'setmetatable' (table expected, got userdata)")); + // no field to read or write + CHECK(contains(lua.run("return memcell.x"), "attempt to index")); + CHECK(contains(lua.run("memcell.x = 1"), "attempt to index")); +} + #endif diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 2b5684dab..9ac0f3bff 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "utilities/inionlysettings.h" #include "utilities/utilities.h" #include "Console.h" #include "scripting/PyInt.h" @@ -957,7 +958,8 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view } // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or - // require: they then reach files and programs as the player does + // require: they then reach files and programs as the player does. from eu07.ini only: a config block of the + // scenery doesn't change it (utilities/inionlysettings.h) if (token == "lua.fulllibraries") { ParseOne(Parser, lua_fulllibraries, 1); @@ -1451,8 +1453,10 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return false; } -void global_settings::ConfigParse(cParser& Parser) +void global_settings::ConfigParse(cParser& Parser, config_source const Source) { + // what a scenery doesn't change, kept before its keys are read + std::optional const inionly{Source == config_source::scenery ? std::make_optional(*this) : std::nullopt}; std::string token; do @@ -1507,6 +1511,15 @@ void global_settings::ConfigParse(cParser& Parser) } while (true); + if (inionly.has_value()) + { + // put back before FinalizeConfig() acts on them (feedbackmode) + for (auto const key : inionly->restore(*this)) + { + ErrorLog("scenery config: \"" + std::string(key) + "\" is read from eu07.ini only, ignored"); + } + } + FinalizeConfig(); } diff --git a/utilities/Globals.h b/utilities/Globals.h index 25c7872c8..f77bd65de 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -25,6 +25,12 @@ http://mozilla.org/MPL/2.0/. #include "input/zmq_input.h" #endif +// where the keys global_settings::ConfigParse reads come from +enum class config_source { + ini, // eu07.ini, and the file given with -ini + scenery // a config block of a scenery (.scn, .inc), read as it loads +}; + struct global_settings { // members // data items @@ -403,7 +409,9 @@ struct global_settings { // methods void LoadIniFile( std::string asFileName ); void FinalizeConfig(); - void ConfigParse(cParser &parser); + // the keys of eu07.ini. Source: where they come from, eu07.ini or a config block of a scenery, which doesn't change + // the settings only eu07.ini sets (utilities/inionlysettings.h) + void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp new file mode 100644 index 000000000..836954bf1 --- /dev/null +++ b/utilities/inionlysettings.cpp @@ -0,0 +1,82 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/inionlysettings.h" + +namespace +{ + +// puts Kept back into Current, and adds Key to Changed when they differed +template void keep(Type_ &Current, Type_ const &Kept, std::string_view const Key, std::vector &Changed) +{ + if (false == (Current == Kept)) + { + Current = Kept; + Changed.push_back(Key); + } +} + +} // namespace + +ini_only_settings::ini_only_settings(global_settings const &Settings) + : m_exec_on_exit{Settings.exec_on_exit}, m_screenshot_dir{Settings.screenshot_dir}, m_extcam_cmd{Settings.extcam_cmd}, + m_extcam_rec{Settings.extcam_rec}, m_network_servers{Settings.network_servers}, m_network_client{Settings.network_client}, +#ifdef WITH_ZMQ + m_zmq_address{Settings.zmq_address}, +#endif + m_motiontelemetry{Settings.motiontelemetry_conf}, +#ifdef WITH_UART + m_uart{Settings.uart_conf}, +#endif + m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled} +{ +} + +std::vector ini_only_settings::restore(global_settings &Settings) const +{ + std::vector changed; + keep(Settings.exec_on_exit, m_exec_on_exit, "execonexit", changed); + keep(Settings.screenshot_dir, m_screenshot_dir, "screenshotsdir", changed); + keep(Settings.extcam_cmd, m_extcam_cmd, "extcam.cmd", changed); + keep(Settings.extcam_rec, m_extcam_rec, "extcam.rec", changed); + keep(Settings.network_servers, m_network_servers, "network.server", changed); + keep(Settings.network_client, m_network_client, "network.client", changed); +#ifdef WITH_ZMQ + keep(Settings.zmq_address, m_zmq_address, "zmq.address", changed); +#endif + // the structures as a whole, told apart by what turns them on and where they lead + { + auto ¤t{Settings.motiontelemetry_conf}; + if (current.enable != m_motiontelemetry.enable || current.proto != m_motiontelemetry.proto || current.address != m_motiontelemetry.address || + current.port != m_motiontelemetry.port) + { + changed.emplace_back("motiontelemetry"); + } + current = m_motiontelemetry; + } +#ifdef WITH_UART + { + auto ¤t{Settings.uart_conf}; + if (current.enable != m_uart.enable || current.port != m_uart.port) + { + changed.emplace_back("uart"); + } + current = m_uart; + } +#endif + keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); + keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); + keep(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + return changed; +} diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h new file mode 100644 index 000000000..eff5c067f --- /dev/null +++ b/utilities/inionlysettings.h @@ -0,0 +1,55 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "utilities/Globals.h" + +#include +#include +#include +#include +#include + +// the settings only eu07.ini sets. a scenery's config block is read by the parser of eu07.ini +// (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program +// (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports +// (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled) or take its own scripts +// out of the sandbox (lua.fulllibraries). they keep what eu07.ini set +class ini_only_settings +{ + public: + // what Settings holds now, as eu07.ini set it + explicit ini_only_settings(global_settings const &Settings); + + // puts back into Settings what changed since, and gives the keys of eu07.ini whose settings changed + std::vector restore(global_settings &Settings) const; + + private: + std::string m_exec_on_exit; + std::string m_screenshot_dir; + std::string m_extcam_cmd; + std::string m_extcam_rec; + std::vector> m_network_servers; + std::optional> m_network_client; +#ifdef WITH_ZMQ + std::string m_zmq_address; +#endif + motiontelemetry::conf_t m_motiontelemetry; +#ifdef WITH_UART + uart_input::conf_t m_uart; +#endif + int m_feedback_mode; + int m_feedback_port; + bool m_python_enabled; + bool m_luascreens_enabled; + bool m_lua_fulllibraries; + bool m_wasm_enabled; +};