diff --git a/script_screens_doc.md b/script_screens_doc.md index 4cdc5badd..435706fe4 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -223,6 +223,33 @@ and works with memcells, tracks and vehicles through the table `eu07.events` (`e - 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. +Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: + +| function | meaning | +|----------------------------------|------------------------------------------------------------------------------------------| +| `eu07.read_file(path)` | the contents of a file of the scenery folder (`scenery/`), or `nil`: a regular file of at most 16 MB, the path as for `lua ` | +| `eu07.write_file(path, text)` | writes `text` (any bytes) to a file of the scenery's data folder, replacing what was there, and makes the folders of `path`; returns `true`, or `nil` and the reason | +| `eu07.read_data_file(path)` | the contents of a file of the scenery's data folder, or `nil`: what `write_file` wrote there | + +The data folder is the scenery's own, in the player's folder of the game: `%APPDATA%\MaSzyna\scenery_data\\` +on Windows, `~/.config/MaSzyna/scenery_data//` on Linux (`~/Library/Application Support/MaSzyna/...` on a +Mac), `` being the `.scn` file without `.scn` (`td.scn`: `scenery_data/td/`). The game writes nowhere else +for a script, and never into its own folder; the log says where the folder is when the scenery loads its first +script. What is written there stays for the next run of the scenery, and the player may delete it. + +A path to write to is relative, with `/` or `\` between the folders, at most 8 folders deep and 200 bytes long, and +each name in it portable: no `..`, no `.`, no empty name, no drive, no `:` `<` `>` `"` `|` `?` `*` or control +characters, no `.` or space at the end, and none of the names Windows keeps for its devices (`con`, `nul`, `com1`, +`lpt1`... with or without an extension). A file is at most 1 MB (1048576 bytes), and the data folder of a scenery holds at most 256 +files and 16 MB together; a write over these limits is refused, and leaves the file as it was. + +```lua +local saved = eu07.read_data_file("state.txt") +local runs = tonumber(saved or "0") + 1 +local ok, reason = eu07.write_file("state.txt", tostring(runs)) +if not ok then eu07.events.writelog("state not saved: " .. reason) end +``` + A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global 'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries again: diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 0854579d9..7079bb2c3 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -6,6 +6,7 @@ #include "vehicle/Driver.h" #include "simulation/simulation.h" #include "scripting/luasandbox.h" +#include "utilities/utilities.h" lua::lua() { @@ -45,6 +46,9 @@ lua::lua() {nullptr, nullptr} }; luaL_register(state, "eu07.events", api); + lua_pop(state, 1); + // eu07.read_file, eu07.write_file and eu07.read_data_file, the files of the scenery in place of io + lua_sandbox::open_file_library(state, &files); } lua::~lua() @@ -67,6 +71,15 @@ void lua::interpret(const std::string &folder, const std::string &file) full_libraries = true; WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); } + // the scripts read the files of the scenery folder, and write theirs into a folder of the scenery among the + // player's files (%APPDATA%/MaSzyna, ~/.config/MaSzyna), never into the game + files.scenery = folder; + if (auto data = lua_sandbox::scenery_data_folder(user_config_path("scenery_data"), Global.SceneryFile); data != files.data) { + files.data = std::move(data); + auto const name = files.data.u8string(); + if (!name.empty()) + WriteLog("lua: the scenery scripts write their files (eu07.write_file) to \"" + std::string(name.begin(), name.end()) + "\"", logtype::lua); + } // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops // there, and the scenery goes on loading if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { diff --git a/scripting/lua.h b/scripting/lua.h index 8663103df..a0a2b9333 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -1,6 +1,7 @@ #pragma once #include #include +#include "scripting/luasandbox.h" class basic_event; class TMemCell; @@ -11,6 +12,9 @@ class lua { lua_State *state; bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened + // what eu07.read_file reads (the scenery folder) and eu07.write_file writes (the scenery's data folder), known + // when the scenery loads its scripts (interpret()) + lua_sandbox::file_folders files; static int atpanic(lua_State *s); diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index ea5f98a88..bf6ab3961 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include #include namespace lua_sandbox @@ -121,22 +123,23 @@ bool load_text_chunk(lua_State *L, std::string_view const Code, std::string cons return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); } -std::optional read_script_file(std::string const &Folder, std::string_view const Path) +std::optional read_file(std::filesystem::path const &Folder, std::string_view const Path, std::uintmax_t const Limit) { - if (false == script_screens::is_safe_relative_path(Path)) + // a NUL would end the name the system sees + if (false == script_screens::is_safe_relative_path(Path) || Path.find('\0') != std::string_view::npos) { return std::nullopt; } // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens // its files - std::filesystem::path const path{Folder + with_forward_slashes(Path)}; + auto const path{Folder / with_forward_slashes(Path)}; std::error_code error; if (false == std::filesystem::is_regular_file(path, error)) { return std::nullopt; } auto const size{std::filesystem::file_size(path, error)}; - if (error || size > max_script_file) + if (error || size > Limit) { return std::nullopt; } @@ -152,6 +155,11 @@ std::optional read_script_file(std::string const &Folder, std::stri return contents; } +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + return read_file(std::filesystem::path{Folder}, Path, max_script_file); +} + std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) { auto const name{Folder + std::string{Path}}; @@ -172,4 +180,264 @@ std::optional run_script_file(lua_State *L, std::string const &Fold return std::nullopt; } +namespace +{ + +char lower_case(char const Character) +{ + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the names Windows opens as its devices, whatever the extension +bool is_device_name(std::string_view Name) +{ + // the extension, and the spaces before it, don't count ("nul.txt", "con .log") + Name = Name.substr(0, Name.find('.')); + while (false == Name.empty() && Name.back() == ' ') + { + Name.remove_suffix(1); + } + std::string name; + std::ranges::transform(Name, std::back_inserter(name), lower_case); + if (name == "con" || name == "prn" || name == "aux" || name == "nul" || name == "conin$" || name == "conout$") + { + return true; + } + return name.size() == 4 && (name.starts_with("com") || name.starts_with("lpt")) && name[3] >= '0' && name[3] <= '9'; +} + +// a name of a file or a folder that every system takes as it is +bool is_portable_name(std::string_view const Name) +{ + if (Name.empty() || Name == "." || Name == ".." || Name.back() == '.' || Name.back() == ' ') + { + return false; + } + for (auto const character : Name) + { + if (static_cast(character) < 0x20 || character == 0x7f || + std::string_view{"<>:\"|?*"}.find(character) != std::string_view::npos) + { + return false; + } + } + return false == is_device_name(Name); +} + +// true when Path, a canonical path, is Folder, a canonical path, or inside it +bool is_inside(std::filesystem::path const &Path, std::filesystem::path const &Folder) +{ + return std::mismatch(Folder.begin(), Folder.end(), Path.begin(), Path.end()).first == Folder.end(); +} + +file_folders const &folders_of(lua_State *L) +{ + return *static_cast(lua_touserdata(L, lua_upvalueindex(1))); +} + +std::string_view check_text(lua_State *L, int const Index) +{ + std::size_t length{0}; + auto const *text{luaL_checklstring(L, Index, &length)}; + return {text, length}; +} + +void push_contents(lua_State *L, std::optional const &Contents) +{ + if (Contents.has_value()) + { + lua_pushlstring(L, Contents->data(), Contents->size()); + } + else + { + lua_pushnil(L); + } +} + +// eu07.read_file(path): the contents of a file of the scenery folder, or nil +int api_read_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.scenery.empty() ? std::nullopt : read_file(folders.scenery, path, max_script_file)); + return 1; +} + +// eu07.read_data_file(path): the contents of a file of the scenery's data folder, or nil +int api_read_data_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.data.empty() ? std::nullopt : read_file(folders.data, path, max_data_file)); + return 1; +} + +// eu07.write_file(path, text): writes the file of the scenery's data folder. true, or nil and why not +int api_write_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const contents{check_text(L, 2)}; + if (auto const error{write_data_file(folders_of(L).data, path, contents)}; error.has_value()) + { + lua_pushnil(L); + lua_pushlstring(L, error->data(), error->size()); + return 2; + } + lua_pushboolean(L, 1); + return 1; +} + +} // namespace + +bool is_safe_write_path(std::string_view const Path) +{ + if (Path.size() > max_data_path || false == script_screens::is_safe_relative_path(Path)) + { + return false; + } + std::size_t names{0}; + std::size_t start{0}; + while (start <= Path.size()) + { + auto const end{std::min(Path.find_first_of("/\\", start), Path.size())}; + if (false == is_portable_name(Path.substr(start, end - start))) + { + return false; + } + ++names; + start = end + 1; + } + // the folders, and the file in them + return names <= max_data_depth + 1; +} + +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view const Path, std::string_view const Contents) +{ + namespace fs = std::filesystem; + std::string const name{Path}; + if (Folder.empty()) + { + return name + ": no folder to write to (the game knows no folder of the player)"; + } + if (false == is_safe_write_path(Path)) + { + return name + ": not a path to write to (a relative path of portable names, at most " + std::to_string(max_data_path) + + " bytes and " + std::to_string(max_data_depth) + " folders deep, without '..')"; + } + if (Contents.size() > max_data_file) + { + return name + ": larger than " + std::to_string(max_data_file) + " bytes"; + } + auto const target{Folder / with_forward_slashes(Path)}; + std::error_code error; + // a link, a folder or anything else that isn't a file stays as it is + auto const status{fs::symlink_status(target, error)}; + auto const exists{status.type() != fs::file_type::not_found}; + if (exists && status.type() != fs::file_type::regular) + { + return name + ": not a file"; + } + std::uintmax_t replaced{0}; + if (exists) + { + replaced = fs::file_size(target, error); + if (error) + { + return name + ": can't be replaced"; + } + } + // what the folder holds, and will hold with the file in place of what was there + std::uintmax_t held{0}; + std::size_t files{0}; + if (fs::is_directory(Folder, error)) + { + for (fs::recursive_directory_iterator entry{Folder, error}, end; !error && entry != end; entry.increment(error)) + { + std::error_code entryerror; + if (entry->symlink_status(entryerror).type() == fs::file_type::regular) + { + auto const size{entry->file_size(entryerror)}; + held += entryerror ? 0 : size; + ++files; + } + } + if (error) + { + return name + ": the data folder can't be read"; + } + } + if (files + (exists ? 0 : 1) > max_data_files) + { + return name + ": the data folder holds " + std::to_string(max_data_files) + " files already"; + } + if (held - std::min(replaced, held) + Contents.size() > max_data_folder) + { + return name + ": the data folder would hold more than " + std::to_string(max_data_folder) + " bytes"; + } + fs::create_directories(target.parent_path(), error); + if (error) + { + return name + ": its folder can't be made"; + } + // still inside the data folder, should a link in it lead elsewhere + auto const root{fs::canonical(Folder, error)}; + auto const parent{error ? fs::path{} : fs::canonical(target.parent_path(), error)}; + if (error || false == is_inside(parent, root)) + { + return name + ": outside the data folder"; + } + std::ofstream file{parent / target.filename(), std::ios::binary | std::ios::trunc}; + if (false == file.is_open()) + { + return name + ": can't be opened to write"; + } + file.write(Contents.data(), static_cast(Contents.size())); + file.close(); + if (file.fail()) + { + return name + ": couldn't be written whole"; + } + return std::nullopt; +} + +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view const Scenery) +{ + auto name{with_forward_slashes(Scenery)}; + if (name.size() >= 4) + { + std::string extension; + std::ranges::transform(std::string_view{name}.substr(name.size() - 4), std::back_inserter(extension), lower_case); + if (extension == ".scn") + { + name.resize(name.size() - 4); + } + } + if (Root.empty() || false == is_safe_write_path(name)) + { + return {}; + } + return Root / name; +} + +void open_file_library(lua_State *L, file_folders const *Folders) +{ + // eu07, which the scenery scripts have for eu07.events, made when there is none + lua_getglobal(L, "eu07"); + if (false == lua_istable(L, -1)) + { + lua_pop(L, 1); + lua_newtable(L); + 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}}) + { + lua_pushlightuserdata(L, const_cast(Folders)); + lua_pushcclosure(L, function, 1); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); +} + } // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h index 167060026..5f57c62af 100644 --- a/scripting/luasandbox.h +++ b/scripting/luasandbox.h @@ -15,7 +15,9 @@ http://mozilla.org/MPL/2.0/. #include +#include #include +#include #include #include #include @@ -51,4 +53,49 @@ std::optional read_script_file(std::string const &Folder, std::stri // it ran, otherwise why it didn't std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); +// the files a scenery script reads and writes itself (eu07.read_file, eu07.write_file, eu07.read_data_file): it reads +// the files of the scenery folder, and writes only into a data folder of its scenery, outside the game + +// the largest file a script writes, all the files of a data folder together, and how many files a data folder holds +constexpr std::uintmax_t max_data_file{1024 * 1024}; +constexpr std::uintmax_t max_data_folder{16 * 1024 * 1024}; +constexpr std::size_t max_data_files{256}; +// the longest path a script writes to, and how many folders deep it goes +constexpr std::size_t max_data_path{200}; +constexpr std::size_t max_data_depth{8}; + +// the file Path of Folder, when Path is a relative path inside Folder (as read_script_file) and names a regular file of +// at most Limit bytes. nothing otherwise +std::optional read_file(std::filesystem::path const &Folder, std::string_view Path, std::uintmax_t Limit); + +// true for a path a script may write to: a relative path inside the folder (is_safe_relative_path), '/' or '\' between +// the folders, at most max_data_path bytes and max_data_depth folders deep, each name portable: not empty, not '.' or +// '..', none of the characters Windows refuses (: < > " | ? * and the control characters), no '.' or ' ' at the end, +// and not a device of Windows (con, prn, aux, nul, com0-9, lpt0-9, conin$, conout$, with an extension or without) +bool is_safe_write_path(std::string_view Path); + +// writes Contents to the file Path of Folder (a data folder), replacing what was there, and makes Folder and the folders +// of Path. refused for a path that isn't safe (is_safe_write_path), for more than max_data_file bytes, when Folder would +// hold more than max_data_files files or max_data_folder bytes, when Path names something else than a file, and when it +// leads out of Folder through a link. nothing when written, otherwise why not +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view Path, std::string_view Contents); + +// the data folder of the scenery Scenery (its .scn file, relative to the scenery folder) in Root: Root and the file +// without ".scn" (td.scn: Root/td). empty when Root is, or the name isn't a safe path (is_safe_write_path) +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view Scenery); + +// where the file functions of a scenery script read and write +struct file_folders +{ + // the scenery folder, which eu07.read_file reads, ending with a separator. empty: nothing is read + std::string scenery; + // the data folder of the scenery, which eu07.write_file writes and eu07.read_data_file reads. empty: nothing is + // written there or read from it + std::filesystem::path data; +}; + +// adds eu07.read_file(path), eu07.write_file(path, text) and eu07.read_data_file(path) to the state, on the folders of +// Folders, read on every call: Folders is to outlive the state +void open_file_library(lua_State *L, file_folders const *Folders); + } // namespace lua_sandbox diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp index 6768e27ed..344f51c63 100644 --- a/tests/unit/test_lua_sandbox.cpp +++ b/tests/unit/test_lua_sandbox.cpp @@ -12,6 +12,7 @@ #include "scripting/luasandbox.h" #include "scratch.h" +#include #include #include #include @@ -218,4 +219,209 @@ TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors CHECK(lua.run("return ran") == "11"); } +TEST_CASE("lua sandbox: eu07.read_file reads a file of the scenery folder, and nothing outside it") { + test::scratch_folder const root{"lua_sandbox_read"}; + root.write("outside.txt", "secret"); + root.write("scenery/data.txt", "line 1\nline 2"); + root.write("scenery/sub/more.txt", "more"); + root.write("scenery/folder/inner.txt", "inner"); + auto const folder{std::filesystem::path{root.path("scenery")}}; + + CHECK(lua_sandbox::read_file(folder, "data.txt", 100) == std::optional{"line 1\nline 2"}); + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 100) == std::optional{"more"}); + CHECK(lua_sandbox::read_file(folder, "sub\\more.txt", 100) == std::optional{"more"}); + // the limit is the caller's + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 4).has_value()); + CHECK_FALSE(lua_sandbox::read_file(folder, "sub/more.txt", 3).has_value()); + for (auto const &path : {std::string{"../outside.txt"}, std::string{"sub/../../outside.txt"}, std::string{"..\\outside.txt"}, + std::string{"sub\\..\\..\\outside.txt"}, root.path("outside.txt"), std::string{"/outside.txt"}, + std::string{"\\outside.txt"}, std::string{"C:outside.txt"}, std::string{"missing.txt"}, + std::string{"folder"}, std::string{}, std::string{"data.txt\0x", 10}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_file(folder, path, 100).has_value()); + } +} + +TEST_CASE("lua sandbox: the paths a script may write to") { + for (auto const *path : {"state.txt", "saves/state.txt", "saves\\state.txt", "a/b/c/d/e/f/g/h/file.txt", "con_log.txt", "comx.txt", + "com10.txt", "nul_state", ".hidden", "stan poci\xc4\x85gu.txt", "a..b"}) { + CAPTURE(path); + CHECK(lua_sandbox::is_safe_write_path(path)); + } + for (auto const &path : {std::string{}, std::string{".."}, std::string{"../x.txt"}, std::string{"a/../../x.txt"}, std::string{"..\\x.txt"}, + std::string{"/x.txt"}, std::string{"\\x.txt"}, std::string{"C:x.txt"}, std::string{"C:\\x.txt"}, + std::string{"x.txt:stream"}, std::string{"a//b.txt"}, std::string{"a/"}, std::string{"./x.txt"}, + std::string{"a/./x.txt"}, std::string{"con"}, std::string{"CON.txt"}, std::string{"saves/nul.dat"}, + std::string{"Com1"}, std::string{"lpt9.log"}, std::string{"aux"}, std::string{"prn.x.y"}, + std::string{"conin$"}, std::string{"CONOUT$.txt"}, std::string{"con .txt"}, std::string{"ab"}, std::string{"a\"b"}, std::string{"a|b"}, std::string{"a?b"}, std::string{"a*b"}, + std::string{"x."}, std::string{"x "}, std::string{"dir./x"}, std::string{"a\tb"}, std::string{"a\nb"}, + std::string{"a\0b", 3}, std::string{"a/b/c/d/e/f/g/h/i/file.txt"}, + std::string(lua_sandbox::max_data_path + 1, 'x')}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::is_safe_write_path(path)); + } + CHECK(lua_sandbox::is_safe_write_path(std::string(lua_sandbox::max_data_path, 'x'))); +} + +TEST_CASE("lua sandbox: a script writes into its data folder only, and reads back what it wrote") { + test::scratch_folder const root{"lua_sandbox_write"}; + root.write("outside.txt", "kept"); + auto const data{root.root() / "data" / "td"}; + + // the folder is made with the first file + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=1").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=1"}); + // replaced, not appended + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=2").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=2"}); + // any bytes, and the folders of the path + std::string const bytes{"a\0b\r\n\xff", 6}; + CHECK_FALSE(lua_sandbox::write_data_file(data, "saves\\day 1/bin.dat", bytes).has_value()); + CHECK(lua_sandbox::read_file(data, "saves/day 1/bin.dat", lua_sandbox::max_data_file) == std::optional{bytes}); + CHECK_FALSE(lua_sandbox::write_data_file(data, "empty.txt", "").has_value()); + CHECK(lua_sandbox::read_file(data, "empty.txt", lua_sandbox::max_data_file) == std::optional{""}); + + // nothing outside the folder + for (auto const *path : {"../outside.txt", "../../outside.txt", "..\\outside.txt", "saves/../../outside.txt", "nul", "con.txt", "x:y"}) { + CAPTURE(path); + auto const error{lua_sandbox::write_data_file(data, path, "overwritten")}; + REQUIRE(error.has_value()); + CHECK(contains(*error, "not a path to write to")); + } + CHECK(lua_sandbox::write_data_file(data, root.path("outside.txt"), "overwritten").has_value()); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"kept"}); + // a folder isn't replaced by a file + auto const folder{lua_sandbox::write_data_file(data, "saves", "x")}; + REQUIRE(folder.has_value()); + CHECK(contains(*folder, "not a file")); + CHECK(std::filesystem::is_directory(data / "saves")); + // no folder (the game knows no folder of the player), nothing written + CHECK(lua_sandbox::write_data_file(std::filesystem::path{}, "state.txt", "x").has_value()); +} + +TEST_CASE("lua sandbox: the limits of a data folder") { + test::scratch_folder const root{"lua_sandbox_limits"}; + auto const data{root.root() / "data"}; + std::string const full(static_cast(lua_sandbox::max_data_file), 'x'); + + SUBCASE("a file") { + CHECK_FALSE(lua_sandbox::write_data_file(data, "full.txt", full).has_value()); + CHECK(lua_sandbox::read_file(data, "full.txt", lua_sandbox::max_data_file).has_value()); + auto const over{lua_sandbox::write_data_file(data, "full.txt", full + "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "larger than")); + // the file stays as it was + CHECK(std::filesystem::file_size(data / "full.txt") == lua_sandbox::max_data_file); + } + SUBCASE("the bytes of the folder") { + auto const files{static_cast(lua_sandbox::max_data_folder / lua_sandbox::max_data_file)}; + for (int idx = 0; idx < files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("part{}.dat", idx), full).has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.dat", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "more than")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.dat")); + // a file replaced counts with its new size: as large again fits, and a smaller one makes room + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", full).has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", "small").has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "one_more.dat", "x").has_value()); + } + SUBCASE("the files of the folder") { + for (std::size_t idx = 0; idx < lua_sandbox::max_data_files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("sub{}/file{}.txt", idx % 4, idx), "x").has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.txt", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "files already")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.txt")); + // one that is there is still replaced + CHECK_FALSE(lua_sandbox::write_data_file(data, "sub0/file0.txt", "y").has_value()); + } +} + +TEST_CASE("lua sandbox: a link in the data folder doesn't lead a write out of it") { + test::scratch_folder const root{"lua_sandbox_link"}; + root.write("outside/kept.txt", "kept"); + auto const data{root.root() / "data"}; + std::filesystem::create_directories(data); + std::error_code error; + std::filesystem::create_directory_symlink(root.root() / "outside", data / "link", error); + if (error) { + // Windows makes links only for an administrator or in developer mode + MESSAGE("no folder link made (" << error.message() << "), not tested"); + return; + } + auto const written{lua_sandbox::write_data_file(data, "link/kept.txt", "overwritten")}; + REQUIRE(written.has_value()); + CHECK(contains(*written, "outside the data folder")); + CHECK(lua_sandbox::read_file(root.root(), "outside/kept.txt", 100) == std::optional{"kept"}); +} + +TEST_CASE("lua sandbox: the data folder of a scenery") { + std::filesystem::path const root{"user/scenery_data"}; + CHECK(lua_sandbox::scenery_data_folder(root, "td.scn") == root / "td"); + CHECK(lua_sandbox::scenery_data_folder(root, "Td.SCN") == root / "Td"); + CHECK(lua_sandbox::scenery_data_folder(root, "lines\\l107.scn") == root / "lines/l107"); + CHECK(lua_sandbox::scenery_data_folder(root, "test.scm") == root / "test.scm"); + for (auto const *scenery : {"", ".scn", "../td.scn", "/td.scn", "C:td.scn", "con.scn"}) { + CAPTURE(scenery); + CHECK(lua_sandbox::scenery_data_folder(root, scenery).empty()); + } + CHECK(lua_sandbox::scenery_data_folder(std::filesystem::path{}, "td.scn").empty()); +} + +TEST_CASE("lua sandbox: the file functions of a scenery script") { + test::scratch_folder const root{"lua_sandbox_api"}; + root.write("outside.txt", "secret"); + root.write("scenery/settings.txt", "speed=40"); + lua_sandbox::file_folders folders{root.path("scenery") + "/", root.root() / "data" / "td"}; + + sandboxed_state const lua; + // next to eu07.events, as the scenery state has it + REQUIRE_FALSE(luaL_dostring(lua.get(), "eu07 = { events = { marker = 1 } }")); + lua_sandbox::open_file_library(lua.get(), &folders); + auto const top{lua_gettop(lua.get())}; + + CHECK(lua.run("return eu07.events.marker") == "1"); + CHECK(lua.run("return eu07.read_file('settings.txt')") == "speed=40"); + CHECK(lua.run("return eu07.read_file('../outside.txt')") == "nil"); + CHECK(lua.run("return eu07.read_file('missing.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.write_file('state.txt', 'runs=' .. 1)") == "true"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "runs=1"); + // the scenery folder and the data folder are apart + CHECK(lua.run("return eu07.read_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('../../scenery/settings.txt')") == "nil"); + // a number is written as its text + CHECK(lua.run("return eu07.write_file('number.txt', 42)") == "true"); + CHECK(lua.run("return eu07.read_data_file('number.txt')") == "42"); + // a refused write gives nil and the reason + CHECK(lua.run("local ok, reason = eu07.write_file('../outside.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil ../outside.txt: not a path to write to (a relative path of portable names, at most 200 bytes and 8 folders deep, without '..')"); + CHECK(lua.run("local ok, reason = eu07.write_file('big.txt', string.rep('x', 1024 * 1024 + 1)) return reason") == + "big.txt: larger than 1048576 bytes"); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"secret"}); + // the arguments are checked + CHECK(contains(lua.run("return eu07.write_file('x.txt')"), "bad argument #2")); + CHECK(contains(lua.run("return eu07.read_file()"), "bad argument #1")); + CHECK(contains(lua.run("return eu07.write_file({}, 'x')"), "bad argument #1")); + + // the folders are read on every call: without a data folder nothing is written or read there + folders.data.clear(); + CHECK(lua.run("local ok, reason = eu07.write_file('state.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil state.txt: no folder to write to (the game knows no folder of the player)"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua_gettop(lua.get()) == top); +} + +TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { + lua_sandbox::file_folders const folders; + sandboxed_state const lua; + lua_sandbox::open_file_library(lua.get(), &folders); + CHECK(lua.run("return type(eu07.read_file) .. type(eu07.write_file) .. type(eu07.read_data_file)") == "functionfunctionfunction"); + CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); +} + #endif