Show system_info.txt, console.txt, json file, userreport_hw.txt paths in the terminal...
[0ad.git] / source / ps / scripting / JSInterface_VFS.cpp
blob87880a90cdbd4ffbd50b4c21f45e41db4d4422f8
1 /* Copyright (C) 2022 Wildfire Games.
2 * This file is part of 0 A.D.
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.
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.
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/>.
18 #include "precompiled.h"
20 #include "JSInterface_VFS.h"
22 #include "lib/file/vfs/vfs_util.h"
23 #include "ps/CLogger.h"
24 #include "ps/CStr.h"
25 #include "ps/Filesystem.h"
26 #include "scriptinterface/FunctionWrapper.h"
27 #include "scriptinterface/JSON.h"
29 #include <sstream>
31 namespace JSI_VFS
33 // Only allow engine compartments to read files they may be concerned about.
34 #define PathRestriction_GUI {L""}
35 #define PathRestriction_Simulation {L"simulation/"}
36 #define PathRestriction_Maps {L"simulation/", L"maps/"}
38 // shared error handling code
39 #define JS_CHECK_FILE_ERR(err)\
40 /* this is liable to happen often, so don't complain */\
41 if (err == ERR::VFS_FILE_NOT_FOUND)\
43 return 0; \
45 /* unknown failure. We output an error message. */\
46 else if (err < 0)\
47 LOGERROR("Unknown failure in VFS %i", err );
48 /* else: success */
51 // Tests whether the current script context is allowed to read from the given directory
52 bool PathRestrictionMet(const ScriptRequest& rq, const std::vector<CStrW>& validPaths, const CStrW& filePath)
54 for (const CStrW& validPath : validPaths)
55 if (filePath.find(validPath) == 0)
56 return true;
58 CStrW allowedPaths;
59 for (std::size_t i = 0; i < validPaths.size(); ++i)
61 if (i != 0)
62 allowedPaths += L", ";
64 allowedPaths += L"\"" + validPaths[i] + L"\"";
67 ScriptException::Raise(rq, "This part of the engine may only read from %s!", utf8_from_wstring(allowedPaths).c_str());
69 return false;
73 // state held across multiple BuildDirEntListCB calls; init by BuildDirEntList.
74 struct BuildDirEntListState
76 const ScriptRequest& rq;
77 JS::PersistentRootedObject filename_array;
78 int cur_idx;
80 BuildDirEntListState(const ScriptRequest& rq)
81 : rq(rq),
82 filename_array(rq.cx),
83 cur_idx(0)
85 filename_array = JS::NewArrayObject(rq.cx, JS::HandleValueArray::empty());
89 // called for each matching directory entry; add its full pathname to array.
90 static Status BuildDirEntListCB(const VfsPath& pathname, const CFileInfo& UNUSED(fileINfo), uintptr_t cbData)
92 BuildDirEntListState* s = (BuildDirEntListState*)cbData;
94 JS::RootedObject filenameArrayObj(s->rq.cx, s->filename_array);
95 JS::RootedValue val(s->rq.cx);
96 Script::ToJSVal(s->rq, &val, CStrW(pathname.string()) );
97 JS_SetElement(s->rq.cx, filenameArrayObj, s->cur_idx++, val);
98 return INFO::OK;
102 // Return an array of pathname strings, one for each matching entry in the
103 // specified directory.
104 // filter_string: default "" matches everything; otherwise, see vfs_next_dirent.
105 // recurse: should subdirectories be included in the search? default false.
106 JS::Value BuildDirEntList(const ScriptRequest& rq, const std::vector<CStrW>& validPaths, const std::wstring& path, const std::wstring& filterStr, bool recurse)
108 if (!PathRestrictionMet(rq, validPaths, path))
109 return JS::NullValue();
111 // convert to const wchar_t*; if there's no filter, pass 0 for speed
112 // (interpreted as: "accept all files without comparing").
113 const wchar_t* filter = 0;
114 if (!filterStr.empty())
115 filter = filterStr.c_str();
117 int flags = recurse ? vfs::DIR_RECURSIVE : 0;
119 // build array in the callback function
120 BuildDirEntListState state(rq);
121 vfs::ForEachFile(g_VFS, path, BuildDirEntListCB, (uintptr_t)&state, filter, flags);
123 return JS::ObjectValue(*state.filename_array);
126 // Return true iff the file exits
127 bool FileExists(const ScriptRequest& rq, const std::vector<CStrW>& validPaths, const CStrW& filename)
129 return PathRestrictionMet(rq, validPaths, filename) && g_VFS->GetFileInfo(filename, 0) == INFO::OK;
132 // Return time [seconds since 1970] of the last modification to the specified file.
133 double GetFileMTime(const std::wstring& filename)
135 CFileInfo fileInfo;
136 Status err = g_VFS->GetFileInfo(filename, &fileInfo);
137 JS_CHECK_FILE_ERR(err);
139 return (double)fileInfo.MTime();
142 // Return current size of file.
143 unsigned int GetFileSize(const std::wstring& filename)
145 CFileInfo fileInfo;
146 Status err = g_VFS->GetFileInfo(filename, &fileInfo);
147 JS_CHECK_FILE_ERR(err);
149 return (unsigned int)fileInfo.Size();
152 // Return file contents in a string. Assume file is UTF-8 encoded text.
153 JS::Value ReadFile(const ScriptRequest& rq, const std::wstring& filename)
155 CVFSFile file;
156 if (file.Load(g_VFS, filename) != PSRETURN_OK)
157 return JS::NullValue();
159 CStr contents = file.DecodeUTF8(); // assume it's UTF-8
161 // Fix CRLF line endings. (This function will only ever be used on text files.)
162 contents.Replace("\r\n", "\n");
164 // Decode as UTF-8
165 JS::RootedValue ret(rq.cx);
166 Script::ToJSVal(rq, &ret, contents.FromUTF8());
167 return ret;
170 // Return file contents as an array of lines. Assume file is UTF-8 encoded text.
171 JS::Value ReadFileLines(const ScriptRequest& rq, const std::wstring& filename)
173 CVFSFile file;
174 if (file.Load(g_VFS, filename) != PSRETURN_OK)
175 return JS::NullValue();
177 CStr contents = file.DecodeUTF8(); // assume it's UTF-8
179 // Fix CRLF line endings. (This function will only ever be used on text files.)
180 contents.Replace("\r\n", "\n");
182 // split into array of strings (one per line)
183 std::stringstream ss(contents);
185 JS::RootedValue line_array(rq.cx);
186 Script::CreateArray(rq, &line_array);
188 std::string line;
189 int cur_line = 0;
191 while (std::getline(ss, line))
193 // Decode each line as UTF-8
194 JS::RootedValue val(rq.cx);
195 Script::ToJSVal(rq, &val, CStr(line).FromUTF8());
196 Script::SetPropertyInt(rq, line_array, cur_line++, val);
199 return line_array;
202 // Return file contents parsed as a JS Object
203 JS::Value ReadJSONFile(const ScriptInterface& scriptInterface, const std::vector<CStrW>& validPaths, const CStrW& filePath)
205 ScriptRequest rq(scriptInterface);
206 if (!PathRestrictionMet(rq, validPaths, filePath))
207 return JS::NullValue();
209 JS::RootedValue out(rq.cx);
210 Script::ReadJSONFile(rq, filePath, &out);
211 return out;
214 // Save given JS Object to a JSON file
215 void WriteJSONFile(const ScriptInterface& scriptInterface, const std::wstring& filePath, JS::HandleValue val1)
217 ScriptRequest rq(scriptInterface);
219 // TODO: This is a workaround because we need to pass a MutableHandle to StringifyJSON.
220 JS::RootedValue val(rq.cx, val1);
222 std::string str(Script::StringifyJSON(rq, &val, false));
224 VfsPath path(filePath);
225 WriteBuffer buf;
226 buf.Append(str.c_str(), str.length());
227 OsPath realPath;
228 g_VFS->GetRealPath(path, realPath, false);
229 if (g_VFS->CreateFile(path, buf.Data(), buf.Size()) == INFO::OK)
230 debug_printf("FILES| JSON data written to %s\n", realPath.string8().c_str());
231 else
232 debug_printf("FILES| Failed to write JSON data to %s\n", realPath.string8().c_str());
235 bool DeleteCampaignSave(const CStrW& filePath)
237 OsPath realPath;
238 if (filePath.Left(16) != L"saves/campaigns/" || filePath.Right(12) != L".0adcampaign")
239 return false;
241 return VfsFileExists(filePath) &&
242 g_VFS->GetRealPath(filePath, realPath) == INFO::OK &&
243 g_VFS->RemoveFile(filePath) == INFO::OK &&
244 wunlink(realPath) == 0;
247 #define VFS_ScriptFunctions(context)\
248 JS::Value Script_ReadJSONFile_##context(const ScriptInterface& scriptInterface, const std::wstring& filePath)\
250 return ReadJSONFile(scriptInterface, PathRestriction_##context, filePath);\
252 JS::Value Script_ListDirectoryFiles_##context(const ScriptInterface& scriptInterface, const std::wstring& path, const std::wstring& filterStr, bool recurse)\
254 return BuildDirEntList(scriptInterface, PathRestriction_##context, path, filterStr, recurse);\
256 bool Script_FileExists_##context(const ScriptInterface& scriptInterface, const std::wstring& filePath)\
258 return FileExists(scriptInterface, PathRestriction_##context, filePath);\
261 VFS_ScriptFunctions(GUI);
262 VFS_ScriptFunctions(Simulation);
263 VFS_ScriptFunctions(Maps);
264 #undef VFS_ScriptFunctions
266 void RegisterScriptFunctions_GUI(const ScriptRequest& rq)
268 ScriptFunction::Register<&Script_ListDirectoryFiles_GUI>(rq, "ListDirectoryFiles");
269 ScriptFunction::Register<&Script_FileExists_GUI>(rq, "FileExists");
270 ScriptFunction::Register<&GetFileMTime>(rq, "GetFileMTime");
271 ScriptFunction::Register<&GetFileSize>(rq, "GetFileSize");
272 ScriptFunction::Register<&ReadFile>(rq, "ReadFile");
273 ScriptFunction::Register<&ReadFileLines>(rq, "ReadFileLines");
274 ScriptFunction::Register<&Script_ReadJSONFile_GUI>(rq, "ReadJSONFile");
275 ScriptFunction::Register<&WriteJSONFile>(rq, "WriteJSONFile");
276 ScriptFunction::Register<&DeleteCampaignSave>(rq, "DeleteCampaignSave");
279 void RegisterScriptFunctions_Simulation(const ScriptRequest& rq)
281 ScriptFunction::Register<&Script_ListDirectoryFiles_Simulation>(rq, "ListDirectoryFiles");
282 ScriptFunction::Register<&Script_FileExists_Simulation>(rq, "FileExists");
283 ScriptFunction::Register<&Script_ReadJSONFile_Simulation>(rq, "ReadJSONFile");
286 void RegisterScriptFunctions_Maps(const ScriptRequest& rq)
288 ScriptFunction::Register<&Script_ListDirectoryFiles_Maps>(rq, "ListDirectoryFiles");
289 ScriptFunction::Register<&Script_FileExists_Maps>(rq, "FileExists");
290 ScriptFunction::Register<&Script_ReadJSONFile_Maps>(rq, "ReadJSONFile");