Play your Steam library's Windows games on a jailbroken PS5.
C++
Open and save UTF-16 files in the web editor
Leonardo Lobato797e0c487aaa
diff --git a/src/web/file_policy.cpp b/src/web/file_policy.cppindex b917946..f213300 100644--- a/src/web/file_policy.cpp+++ b/src/web/file_policy.cpp@@ -44,6 +44,57 @@ bool ValidUtf8(std::string_view text) {return true;}+bool DecodeText(std::string_view bytes, std::string* text, std::string* encoding, bool* bom) {+ const auto starts = [&](std::string_view mark) { return bytes.substr(0, mark.size()) == mark; };+ const bool little = starts("\xff\xfe");+ if (!little && !starts("\xfe\xff")) {+ *bom = starts("\xef\xbb\xbf");+ *encoding = "utf-8";+ if (*bom) bytes.remove_prefix(3);+ if (!ValidUtf8(bytes) || bytes.find('\0') != std::string_view::npos) return false;+ *text = std::string(bytes);+ return true;+ }+ *bom = true;+ *encoding = little ? "utf-16le" : "utf-16be";+ bytes.remove_prefix(2);+ if (bytes.size() % 2 != 0) return false;+ const auto unit = [&](std::size_t at) -> unsigned {+ const auto first = static_cast<unsigned char>(bytes[at]), second = static_cast<unsigned char>(bytes[at + 1]);+ return little ? first | (second << 8) : (first << 8) | second;+ };+ std::string out;+ out.reserve(bytes.size());+ for (std::size_t at = 0; at < bytes.size(); at += 2) {+ unsigned value = unit(at);+ if (value == 0 || (value >= 0xdc00 && value <= 0xdfff)) return false;+ if (value >= 0xd800 && value <= 0xdbff) {+ at += 2;+ if (at >= bytes.size()) return false;+ const unsigned low = unit(at);+ if (low < 0xdc00 || low > 0xdfff) return false;+ value = 0x10000 + ((value - 0xd800) << 10) + (low - 0xdc00);+ }+ if (value < 0x80) {+ out += static_cast<char>(value);+ } else if (value < 0x800) {+ out += static_cast<char>(0xc0 | (value >> 6));+ out += static_cast<char>(0x80 | (value & 0x3f));+ } else if (value < 0x10000) {+ out += static_cast<char>(0xe0 | (value >> 12));+ out += static_cast<char>(0x80 | ((value >> 6) & 0x3f));+ out += static_cast<char>(0x80 | (value & 0x3f));+ } else {+ out += static_cast<char>(0xf0 | (value >> 18));+ out += static_cast<char>(0x80 | ((value >> 12) & 0x3f));+ out += static_cast<char>(0x80 | ((value >> 6) & 0x3f));+ out += static_cast<char>(0x80 | (value & 0x3f));+ }+ }+ *text = std::move(out);+ return true;+}+bool HiddenName(std::string_view name) {const auto lower = LowerAscii(name);if (lower.rfind(".playden", 0) == 0) return true;diff --git a/src/web/file_policy.h b/src/web/file_policy.hindex ee9fb3c..9454110 100644--- a/src/web/file_policy.h+++ b/src/web/file_policy.h@@ -23,6 +23,9 @@ inline constexpr const char* kRestorePrefix = ".playden-restore-";std::string LowerAscii(std::string_view text);bool ValidUtf8(std::string_view text);+// A text file's bytes as UTF-8 for the editor. UTF-8, or UTF-16 with a byte order mark; encoding is "utf-8", "utf-16le"+// or "utf-16be", and bom says whether the file starts with one. False for anything else, or for text holding a NUL.+bool DecodeText(std::string_view bytes, std::string* text, std::string* encoding, bool* bom);// Hidden and refused: Playden's own files and secrets kept in a game's folder.bool HiddenName(std::string_view name);// Readable, never changed: Playden writes these folders each time it prepares the game.diff --git a/src/web/file_store.cpp b/src/web/file_store.cppindex ad47234..1e87e30 100644--- a/src/web/file_store.cpp+++ b/src/web/file_store.cpp@@ -288,10 +288,10 @@ FileError FileStore::ReadText(const FileRoot& root, const std::string& path, Filif (count <= 0) return FromErrno(errno, "This file can't be read");done += static_cast<std::size_t>(count);}- if (!ValidUtf8(text) || text.find('\0') != std::string::npos) return {415, "This isn't a text file. Download it instead."};+ if (!DecodeText(text, &out->text, &out->encoding, &out->bom)) return {415, "This file uses an encoding the editor can't show. Download it instead."};+ // Of the bytes on disk, not the decoded text: the save compares it with the file as it is then.const auto hash = runtime::HashArtifactBytes(text);if (!hash) return {500, "This file can't be read."};- out->text = std::move(text);out->sha256 = *hash;return kOk;}diff --git a/src/web/file_store.h b/src/web/file_store.hindex a52d152..0abed9b 100644--- a/src/web/file_store.h+++ b/src/web/file_store.h@@ -72,7 +72,9 @@ struct OpenedFile {// A file read and hashed for the editor.struct FileText {- std::string text;+ std::string text; // as UTF-8, with any byte order mark left out+ std::string encoding = "utf-8";+ bool bom = false;std::string sha256;};inline constexpr std::size_t kMaxTextBytes = 1024 * 1024;diff --git a/src/web/files_api.cpp b/src/web/files_api.cppindex a04d4ca..f4fca07 100644--- a/src/web/files_api.cpp+++ b/src/web/files_api.cpp@@ -377,7 +377,7 @@ void FilesApi::Register(Router& router) {FileText text;const auto error = store_.ReadText(root, QueryValue(request.query, "path").value_or(std::string()), &text);if (!error.ok()) return Fail(response, error);- SendJson(response, 200, "{" + Field("sha256", text.sha256) + "," + Field("text", text.text) + "}");+ SendJson(response, 200, "{" + Field("sha256", text.sha256) + "," + Field("encoding", text.encoding) + "," + Field("bom", text.bom) + "," + Field("text", text.text) + "}");});router.Post("/api/files/upload", [this](const Request& request, const std::string&, Response& response) {diff --git a/src/web/page/index.html b/src/web/page/index.htmlindex d58d5b7..02c8d99 100644--- a/src/web/page/index.html+++ b/src/web/page/index.html@@ -281,6 +281,7 @@ main.dragging { outline: 2px dashed var(--accent); outline-offset: 8px; }const fail = (message) => {$("problem-text").textContent = message;+ $("retry").hidden = false;$("problem").hidden = false;};@@ -464,6 +465,8 @@ main.dragging { outline: 2px dashed var(--accent); outline-offset: 8px; }const report = (error) => {if (error.status === 401) return;fail(error.message);+ // The same file gives the same refusal.+ if (error.status === 415) $("retry").hidden = true;};// Pairing@@ -1160,6 +1163,31 @@ main.dragging { outline: 2px dashed var(--accent); outline-offset: 8px; }readTree(entries).then((tree) => addTree(target, tree)).catch(report);});+ // A save goes back the way the file came: its encoding, its byte order mark, its usual line ending.+ const encodeText = (value, original) => {+ const count = (pattern) => (original.text.match(pattern) || []).length;+ const crlf = count(/\r\n/g), lf = count(/(?<!\r)\n/g), cr = count(/\r(?!\n)/g);+ const ending = crlf > lf && crlf >= cr ? "\r\n" : cr > lf ? "\r" : "\n";+ const lines = ending === "\n" ? value : value.replace(/\n/g, ending);+ if (original.encoding === "utf-8") {+ const body = new TextEncoder().encode(lines);+ if (!original.bom) return body;+ const marked = new Uint8Array(body.length + 3);+ marked.set([0xef, 0xbb, 0xbf]);+ marked.set(body, 3);+ return marked;+ }+ const little = original.encoding === "utf-16le";+ const bytes = new Uint8Array((lines.length + 1) * 2);+ const put = (at, unit) => {+ bytes[at] = little ? unit & 0xff : unit >> 8;+ bytes[at + 1] = little ? unit >> 8 : unit & 0xff;+ };+ put(0, 0xfeff);+ for (let i = 0; i < lines.length; ++i) put((i + 1) * 2, lines.charCodeAt(i));+ return bytes;+ };+// The config editor: small text files, saved only if the file is still what was opened.const showEditor = async (id, root, path) => {const token = ++files.route;@@ -1175,12 +1203,15 @@ main.dragging { outline: 2px dashed var(--accent); outline-offset: 8px; }const folder = parts.join("/");const area = element("textarea", { class: "editor", spellcheck: "false", "aria-label": `Contents of ${name}` });area.value = text.text;+ // The text area turns every line break into LF. Compared with this, an unchanged file isn't written at all.+ const opened = area.value;const back = () => { location.hash = folderHash(id, root, folder); };const save = async () => {$("problem").hidden = true;+ if (area.value === opened) return back();try {await api(`/api/files/upload?${q({ game: id, root, path, if_sha256: text.sha256 })}`,- { method: "POST", headers: { "X-Playden-Action": "files" }, body: new Blob([area.value]) });+ { method: "POST", headers: { "X-Playden-Action": "files" }, body: new Blob([encodeText(area.value, text)]) });back();} catch (error) { report(error); }};diff --git a/tests/test_web_files_smoke.py b/tests/test_web_files_smoke.pyindex 29e0059..e3873c9 100644--- a/tests/test_web_files_smoke.py+++ b/tests/test_web_files_smoke.py@@ -118,6 +118,13 @@ def run(port, server):# PhysX for a game playing from USB: a new _Redist folder, then the installer; the page now names it.wolverine_place = dict(game="local-3fa9c1", root="game")ok(call("POST", "/api/files/mkdir", path="_Redist", **wolverine_place))+ # A UTF-16 file opens as text, says how it is stored, and is saved against the hash of its bytes.+ utf16 = "\ufeffversion=1\r\n".encode("utf-16-le")+ ok(call("POST", "/api/files/upload", body=utf16, path="version.txt", **wolverine_place))+ opened = ok(call("GET", "/api/files/text", path="version.txt", **wolverine_place))+ assert (opened["text"], opened["encoding"], opened["bom"]) == ("version=1\r\n", "utf-16le", True)+ ok(call("POST", "/api/files/upload", body="\ufeffversion=2\r\n".encode("utf-16-le"), path="version.txt", if_sha256=opened["sha256"], **wolverine_place))+ assert call("POST", "/api/files/upload", body=utf16, path="version.txt", if_sha256=opened["sha256"], **wolverine_place)[0] == 409# A folder upload: each folder, then its files. Sending it again finds them there.for _ in range(2):ok(call("POST", "/api/files/mkdir", path="Mods/Big/textures", parents=1, **wolverine_place))diff --git a/tests/web_file_store_test.cpp b/tests/web_file_store_test.cppindex bbf7b58..fd6c28f 100644--- a/tests/web_file_store_test.cpp+++ b/tests/web_file_store_test.cpp@@ -518,6 +518,43 @@ int main() {CHECK(Send(store, root, "conf.ini", "a=4\n", true, nullptr, hash).status == 409 && !fs::exists(folder / "conf.ini"));Put(folder / "binary.dat", std::string("\xff\xfe\0", 3));CHECK(store.ReadText(root, "binary.dat", &text).status == 415);+ // Encodings: the text comes back as UTF-8, and the hash is still of the bytes on disk.+ const auto reads_as = [&](const std::string& bytes, const std::string& expected, const std::string& encoding, bool bom) {+ Put(folder / "coded.txt", bytes);+ FileText coded;+ return store.ReadText(root, "coded.txt", &coded).ok() && coded.text == expected && coded.encoding == encoding && coded.bom == bom &&+ coded.sha256 == *playden::runtime::HashArtifactBytes(bytes);+ };+ const auto refused = [&](const std::string& bytes) {+ Put(folder / "coded.txt", bytes);+ FileText coded;+ return store.ReadText(root, "coded.txt", &coded).status == 415;+ };+ CHECK(reads_as("plain\r\n", "plain\r\n", "utf-8", false));+ CHECK(reads_as("\xef\xbb\xbf" "caf\xc3\xa9", "caf\xc3\xa9", "utf-8", true));+ CHECK(reads_as(std::string("\xff\xfe" "1\0.\0" "\xe9\0" "\x20\x20", 10), "1.\xc3\xa9\xe2\x80\xa0", "utf-16le", true));+ CHECK(reads_as(std::string("\xfe\xff\0" "1\0" "\xe9", 6), "1\xc3\xa9", "utf-16be", true));+ CHECK(reads_as(std::string("\xff\xfe\x3d\xd8\x00\xde", 6), "\xf0\x9f\x98\x80", "utf-16le", true));+ CHECK(reads_as("\xff\xfe", "", "utf-16le", true));+ CHECK(refused(std::string("\xff\xfe" "a", 3))); // odd length+ CHECK(refused(std::string("\xff\xfe\x3d\xd8", 4))); // a surrogate cut off+ CHECK(refused(std::string("\xff\xfe\x00\xde" "a\0", 6))); // a low surrogate alone+ CHECK(refused(std::string("\xff\xfe\x3d\xd8" "a\0", 6))); // a high surrogate alone+ CHECK(refused(std::string("\xff\xfe\0\0" "a\0", 6))); // UTF-32, or a NUL+ CHECK(refused("caf\xe9")); // Windows-1252+ CHECK(refused(std::string("a\0b\0", 4))); // UTF-16 with no mark+ // The save's check on a UTF-16 file compares the bytes on disk.+ {+ const std::string utf16("\xff\xfe" "a\0=\0" "1\0", 8);+ Put(folder / "coded.txt", utf16);+ FileText coded;+ CHECK(store.ReadText(root, "coded.txt", &coded).ok() && coded.text == "a=1");+ const std::string saved("\xff\xfe" "a\0=\0" "2\0", 8);+ CHECK(Send(store, root, "coded.txt", saved, true, nullptr, coded.sha256).ok() && Text(folder / "coded.txt") == saved);+ CHECK(Send(store, root, "coded.txt", utf16, true, nullptr, coded.sha256).status == 409 && Text(folder / "coded.txt") == saved);+ fs::remove(folder / "coded.txt");+ fs::remove(folder / ".playden-bak.coded.txt");+ }Put(folder / "large.txt", std::string(kMaxTextBytes + 1, 'a'));CHECK(store.ReadText(root, "large.txt", &text).status == 413);fs::remove(folder / "binary.dat");