LCOV - code coverage report
Current view: top level - source/ps/scripting - JSInterface_VFS.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 55 123 44.7 %
Date: 2026-12-03 01:19:39 Functions: 11 22 50.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "JSInterface_VFS.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "lib/file/file_system.h"
      24             : #include "lib/file/io/write_buffer.h"
      25             : #include "lib/file/vfs/vfs.h"
      26             : #include "lib/file/vfs/vfs_util.h"
      27             : #include "lib/os_path.h"
      28             : #include "lib/path.h"
      29             : #include "lib/status.h"
      30             : #include "lib/sysdep/filesystem.h"
      31             : #include "lib/utf8.h"
      32             : #include "ps/CLogger.h"
      33             : #include "ps/CStr.h"
      34             : #include "ps/Errors.h"
      35             : #include "ps/Filesystem.h"
      36             : #include "ps/algorithm.h"
      37             : #include "scriptinterface/FunctionWrapper.h"
      38             : #include "scriptinterface/JSON.h"
      39             : #include "scriptinterface/Object.h"
      40             : #include "scriptinterface/Conversions.h"
      41             : #include "scriptinterface/Request.h"
      42             : 
      43             : #include <algorithm>
      44             : #include <array>
      45             : #include <cstddef>
      46             : #include <cstdint>
      47             : #include <filesystem>
      48             : #include <fmt/format.h>
      49             : #include <js/Array.h>
      50             : #include <js/PropertyAndElement.h>
      51             : #include <js/RootingAPI.h>
      52             : #include <js/TypeDecls.h>
      53             : #include <js/Value.h>
      54             : #include <sstream>
      55             : #include <stdexcept>
      56             : #include <string>
      57             : #include <string_view>
      58             : #include <system_error>
      59             : 
      60             : namespace Script { class Interface; }
      61             : 
      62             : namespace JSI_VFS
      63             : {
      64             : using namespace std::literals;
      65             : 
      66             : // Only allow engine compartments to read files they may be concerned about.
      67             : namespace PathRestriction
      68             : {
      69             : constexpr std::array<std::wstring_view, 8> GUI{L"gui/"sv, L"simulation/"sv, L"maps/"sv, L"campaigns/"sv,
      70             :     L"saves/campaigns/"sv, L"config/matchsettings.json"sv, L"config/matchsettings.mp.json"sv,
      71             :     L"moddata"sv};
      72             : 
      73             : constexpr std::array<std::wstring_view, 1> SIMULATION{L"simulation/"sv};
      74             : 
      75             : constexpr std::array<std::wstring_view, 2> MAPS{L"simulation/"sv, L"maps/"sv};
      76             : }
      77             : 
      78             : // shared error handling code
      79             : #define JS_CHECK_FILE_ERR(err)\
      80             :     /* this is liable to happen often, so don't complain */\
      81             :     if (err == ERR::VFS_FILE_NOT_FOUND)\
      82             :     {\
      83             :         return 0; \
      84             :     }\
      85             :     /* unknown failure. We output an error message. */\
      86             :     else if (err < 0)\
      87             :         LOGERROR("Unknown failure in VFS {}", err );
      88             :     /* else: success */
      89             : 
      90             : 
      91             : // Tests whether the current script context is allowed to read from the given directory
      92             : template<auto& restriction>
      93        1476 : bool PathRestrictionMet(const std::wstring& filePath)
      94             : {
      95        2952 :     if (std::any_of(restriction.begin(), restriction.end(), [&](const std::wstring_view allowedPath)
      96             :         {
      97        1476 :             return filePath.find(allowedPath) == 0;
      98             :         }))
      99             :     {
     100             :         return true;
     101             :     }
     102             : 
     103           0 :     std::wstring allowedPaths;
     104           0 :     for (std::size_t i = 0; i < restriction.size(); ++i)
     105             :     {
     106           0 :         if (i != 0)
     107           0 :             allowedPaths += L", ";
     108             : 
     109           0 :         allowedPaths += L"\"" + static_cast<std::wstring>(restriction[i]) + L"\"";
     110             :     }
     111             : 
     112           0 :     throw std::logic_error{fmt::format(
     113             :         "Restricted access to {}. This part of the engine may only read from {}!",
     114           0 :         utf8_from_wstring(filePath).c_str(), utf8_from_wstring(allowedPaths).c_str())};
     115             : 
     116             :     return false;
     117           0 : }
     118             : 
     119             : 
     120             : // state held across multiple BuildDirEntListCB calls; init by BuildDirEntList.
     121          48 : struct BuildDirEntListState
     122             : {
     123             :     const Script::Request& rq;
     124             :     JS::PersistentRootedObject filename_array;
     125             :     int cur_idx;
     126             : 
     127          24 :     BuildDirEntListState(const Script::Request& rq)
     128          24 :         : rq(rq),
     129          24 :         filename_array(rq.cx),
     130          24 :         cur_idx(0)
     131             :     {
     132          24 :         filename_array = JS::NewArrayObject(rq.cx, 0);
     133          24 :     }
     134             : };
     135             : 
     136             : // called for each matching directory entry; add its full pathname to array.
     137        1449 : static Status BuildDirEntListCB(const VfsPath& pathname, const CFileInfo&, uintptr_t cbData)
     138             : {
     139        1449 :     BuildDirEntListState* s = (BuildDirEntListState*)cbData;
     140             : 
     141        1449 :     JS::RootedObject filenameArrayObj(s->rq.cx, s->filename_array);
     142        1449 :     JS::RootedValue val(s->rq.cx);
     143        2898 :     Script::ToJSVal(s->rq, &val, CStrW(pathname.string()) );
     144        1449 :     JS_SetElement(s->rq.cx, filenameArrayObj, s->cur_idx++, val);
     145        1449 :     return INFO::OK;
     146        1449 : }
     147             : 
     148             : 
     149             : // Return an array of pathname strings, one for each matching entry in the
     150             : // specified directory.
     151             : //   filter_string: default "" matches everything; otherwise, see vfs_next_dirent.
     152             : //   recurse: should subdirectories be included in the search? default false.
     153             : template<auto& restriction>
     154          24 : JS::Value BuildDirEntList(const Script::Request& rq, const std::wstring& path, const std::wstring& filterStr,
     155             :     bool recurse)
     156             : {
     157          24 :     if (!PathRestrictionMet<restriction>(path))
     158             :         return JS::NullValue();
     159             : 
     160             :     // convert to const wchar_t*; if there's no filter, pass 0 for speed
     161             :     // (interpreted as: "accept all files without comparing").
     162          24 :     const wchar_t* filter = 0;
     163          24 :     if (!filterStr.empty())
     164          24 :         filter = filterStr.c_str();
     165             : 
     166          24 :     int flags = recurse ? vfs::DIR_RECURSIVE : 0;
     167             : 
     168             :     // build array in the callback function
     169          24 :     BuildDirEntListState state(rq);
     170          72 :     vfs::ForEachFile(g_VFS, path, BuildDirEntListCB, (uintptr_t)&state, filter, flags);
     171             : 
     172          24 :     return JS::ObjectValue(*state.filename_array);
     173          24 : }
     174             : 
     175             : // Return true iff the file exits
     176             : template<auto& restriction>
     177           0 : bool FileExists(const std::wstring& filename)
     178             : {
     179           0 :     return PathRestrictionMet<restriction>(filename) && g_VFS->GetFileInfo(filename, 0) == INFO::OK;
     180             : }
     181             : 
     182             : // Return current size of file.
     183           0 : unsigned int GetFileSize(const std::wstring& filename)
     184             : {
     185           0 :     CFileInfo fileInfo;
     186           0 :     Status err = g_VFS->GetFileInfo(filename, &fileInfo);
     187           0 :     JS_CHECK_FILE_ERR(err);
     188             : 
     189           0 :     return (unsigned int)fileInfo.Size();
     190           0 : }
     191             : 
     192             : // Return file contents in a string. Assume file is UTF-8 encoded text.
     193             : template<auto& restriction>
     194           0 : JS::Value ReadFile(const Script::Request& rq, const std::wstring& filename)
     195             : {
     196           0 :     if (!PathRestrictionMet<restriction>(filename))
     197             :         return JS::NullValue();
     198             : 
     199           0 :     CVFSFile file;
     200           0 :     if (file.Load(g_VFS, filename) != PSRETURN_OK)
     201             :         return JS::NullValue();
     202             : 
     203           0 :     CStr contents = file.DecodeUTF8(); // assume it's UTF-8
     204             : 
     205             :     // Fix CRLF line endings. (This function will only ever be used on text files.)
     206           0 :     PS::ReplaceSubrange(contents, "\r\n", "\n");
     207             : 
     208             :     // Decode as UTF-8
     209           0 :     JS::RootedValue ret(rq.cx);
     210           0 :     Script::ToJSVal(rq, &ret, contents.FromUTF8());
     211           0 :     return ret;
     212           0 : }
     213             : 
     214             : // Return file contents as an array of lines. Assume file is UTF-8 encoded text.
     215             : template<auto& restriction>
     216           0 : JS::Value ReadFileLines(const Script::Request& rq, const std::wstring& filename)
     217             : {
     218           0 :     if (!PathRestrictionMet<restriction>(filename))
     219             :         return JS::NullValue();
     220             : 
     221           0 :     CVFSFile file;
     222           0 :     if (file.Load(g_VFS, filename) != PSRETURN_OK)
     223             :         return JS::NullValue();
     224             : 
     225           0 :     CStr contents = file.DecodeUTF8(); // assume it's UTF-8
     226             : 
     227             :     // Fix CRLF line endings. (This function will only ever be used on text files.)
     228           0 :     PS::ReplaceSubrange(contents, "\r\n", "\n");
     229             : 
     230             :     // split into array of strings (one per line)
     231           0 :     std::stringstream ss(contents);
     232             : 
     233           0 :     JS::RootedValueVector lineArray{rq.cx};
     234             : 
     235           0 :     std::string line;
     236             : 
     237           0 :     while (std::getline(ss, line))
     238             :     {
     239             :         // Decode each line as UTF-8
     240           0 :         JS::RootedValue val(rq.cx);
     241           0 :         Script::ToJSVal(rq, &val, CStr(line).FromUTF8());
     242           0 :         if (!lineArray.append(val))
     243           0 :             throw std::runtime_error{"Append failed"};
     244             :     }
     245             : 
     246           0 :     return JS::ObjectValue(*JS::NewArrayObject(rq.cx, lineArray));
     247           0 : }
     248             : 
     249             : // Return file contents parsed as a JS Object
     250             : template<auto& restriction>
     251        1452 : JS::Value ReadJSONFile(const Script::Interface& scriptInterface, const std::wstring& filePath)
     252             : {
     253        1452 :     Script::Request rq(scriptInterface);
     254        1452 :     if (!PathRestrictionMet<restriction>(filePath))
     255             :         return JS::NullValue();
     256             : 
     257        1452 :     JS::RootedValue out(rq.cx);
     258        4356 :     Script::ReadJSONFile(rq, filePath, &out);
     259        1452 :     return out;
     260        1452 : }
     261             : 
     262             : // Save given JS Object to a JSON file
     263             : template<auto& restriction>
     264           0 : void WriteJSONFile(const Script::Interface& scriptInterface, const std::wstring& filePath,
     265             :     JS::HandleValue val1)
     266             : {
     267           0 :     Script::Request rq(scriptInterface);
     268           0 :     if (!PathRestrictionMet<restriction>(filePath))
     269             :         return;
     270             : 
     271             :     // TODO: This is a workaround because we need to pass a MutableHandle to StringifyJSON.
     272           0 :     JS::RootedValue val(rq.cx, val1);
     273             : 
     274           0 :     std::string str(Script::StringifyJSON(rq, &val, false));
     275             : 
     276           0 :     VfsPath path(filePath);
     277           0 :     WriteBuffer buf;
     278           0 :     buf.Append(str.c_str(), str.length());
     279           0 :     if (g_VFS->CreateFile(path, {buf.Data().get(), buf.Size()}) == INFO::OK)
     280             :     {
     281           0 :         OsPath realPath;
     282           0 :         g_VFS->GetRealPath(path, realPath, false);
     283           0 :         debug_printf("JSON data written to '%s'\n", realPath.string8().c_str());
     284           0 :     }
     285             :     else
     286           0 :         debug_printf("Failed to write JSON data to '%s'\n", path.string8().c_str());
     287           0 : }
     288             : 
     289           0 : bool DeleteCampaignSave(const CStrW& filePath)
     290             : {
     291           0 :     OsPath realPath;
     292           0 :     if (!filePath.starts_with(L"saves/campaigns/") || !filePath.ends_with(L".0adcampaign"))
     293           0 :         return false;
     294           0 :     if (!VfsFileExists(filePath))
     295             :         return false;
     296           0 :     if (g_VFS->GetRealPath(filePath, realPath) != INFO::OK)
     297             :         return false;
     298           0 :     if (g_VFS->RemoveFile(filePath) != INFO::OK)
     299             :         return false;
     300           0 :     std::error_code ec;
     301           0 :     std::filesystem::remove(realPath.string(), ec);
     302           0 :     return !ec;
     303           0 : }
     304             : 
     305          26 : void RegisterScriptFunctions_ReadWriteAnywhere(const Script::Request& rq,
     306             :     const std::uint16_t flags /*= JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT */)
     307             : {
     308          26 :     Script::Function::Register<&BuildDirEntList<PathRestriction::GUI>>(rq, "ListDirectoryFiles", flags);
     309          26 :     Script::Function::Register<&FileExists<PathRestriction::GUI>>(rq, "FileExists", flags);
     310          26 :     Script::Function::Register<&GetFileSize>(rq, "GetFileSize", flags);
     311          26 :     Script::Function::Register<&ReadFile<PathRestriction::GUI>>(rq, "ReadFile", flags);
     312          26 :     Script::Function::Register<&ReadFileLines<PathRestriction::GUI>>(rq, "ReadFileLines", flags);
     313          26 :     Script::Function::Register<&ReadJSONFile<PathRestriction::GUI>>(rq, "ReadJSONFile", flags);
     314          26 :     Script::Function::Register<&WriteJSONFile<PathRestriction::GUI>>(rq, "WriteJSONFile", flags);
     315          26 :     Script::Function::Register<&DeleteCampaignSave>(rq, "DeleteCampaignSave", flags);
     316          26 : }
     317             : 
     318          82 : void RegisterScriptFunctions_ReadOnlySimulation(const Script::Request& rq,
     319             :     const std::uint16_t flags /*= JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT */)
     320             : {
     321          82 :     Script::Function::Register<&BuildDirEntList<PathRestriction::SIMULATION>>(rq, "ListDirectoryFiles", flags);
     322          82 :     Script::Function::Register<&FileExists<PathRestriction::SIMULATION>>(rq, "FileExists", flags);
     323          82 :     Script::Function::Register<&ReadJSONFile<PathRestriction::SIMULATION>>(rq, "ReadJSONFile", flags);
     324          82 : }
     325             : 
     326           8 : void RegisterScriptFunctions_ReadOnlySimulationMaps(const Script::Request& rq,
     327             :     const std::uint16_t flags /*= JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT */)
     328             : {
     329           8 :     Script::Function::Register<&BuildDirEntList<PathRestriction::MAPS>>(rq, "ListDirectoryFiles", flags);
     330           8 :     Script::Function::Register<&FileExists<PathRestriction::MAPS>>(rq, "FileExists", flags);
     331           8 :     Script::Function::Register<&ReadJSONFile<PathRestriction::MAPS>>(rq, "ReadJSONFile", flags);
     332           8 : }
     333             : }

Generated by: LCOV version 1.16