diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d998f4..bc53bae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,7 @@ set(SOURCES_LIST src/partition/partitions.cpp src/filesystem/help.cpp src/filesystem/hash.cpp + src/filesystem/codepage.cpp src/filesystem/structure/attributes.cpp src/filesystem/structure/file.cpp src/filesystem/structure/directory.cpp diff --git a/README.md b/README.md index a54b57f..bb99b6b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ - EGOLD с Card-Explorer \ Требует тестирования. Только чтение -На SGOLD имена записываемых файлов и каталогов могут содержать только символы ASCII. +SGOLD хранит имена в 8-битной кодировке языка телефона — CP1252 для западноевропейских языков, CP1251 для кириллических, CP1250 для центральноевропейских, — а имена с символами, которых в ней нет, в UTF-8. Кодировку задаёт `set_codepage()`, по умолчанию CP1252; по ней имена и читаются, и записываются. ## Тесты Тесты используют GoogleTest (`libgtest-dev`) и собираются с `-DBUILD_TESTS=ON`: diff --git a/inc/ffshit/filesystem/platform/base.h b/inc/ffshit/filesystem/platform/base.h index 2d32494..7876300 100644 --- a/inc/ffshit/filesystem/platform/base.h +++ b/inc/ffshit/filesystem/platform/base.h @@ -21,13 +21,19 @@ class Base { Base() : verbose_processing(false), verbose_headers(false), - verbose_data(false) + verbose_data(false), + codepage("CP1252") { } void log_verbose_processing(bool enabled) { this->verbose_processing = enabled; } void log_verbose_headers(bool enabled) { this->verbose_headers = enabled; } void log_verbose_data(bool enabled) { this->verbose_data = enabled; } + // The 8-bit codepage SGOLD keeps file names in, which is the one of the phone's language: + // CP1252 (the default) for Western European languages, CP1251 for Cyrillic ones, CP1250 + // for Central European ones, or any other iconv knows. Set it before load(). + void set_codepage(const std::string &codepage); + virtual void load(bool skip_broken = false, bool skip_dup = false, std::vector parts_to_extract = {}) = 0; virtual const Directory::Ptr get_root() const = 0; @@ -49,6 +55,8 @@ class Base { bool verbose_headers; bool verbose_data; + std::string codepage; + // Built on the first write Write::Session & write_session(Platform::Type platform, Partitions::Partitions::Ptr partitions, Directory::Ptr root); diff --git a/src/filesystem/codepage.cpp b/src/filesystem/codepage.cpp new file mode 100644 index 0000000..45c51c7 --- /dev/null +++ b/src/filesystem/codepage.cpp @@ -0,0 +1,102 @@ +#include "filesystem/codepage.h" + +#include "ffshit/filesystem/ex.h" + +#include +#include +#include + +#include + +namespace FULLFLASH { +namespace Filesystem { + +static constexpr char UTF8_NAME_PREFIX = 0x1F; + +static iconv_t open_iconv(const std::string &to_code, const std::string &from_code) { + iconv_t iccd = iconv_open(to_code.c_str(), from_code.c_str()); + + if (iccd == ((iconv_t)-1)) { + throw Exception("Can't convert from {} to {}: {}", from_code, to_code, strerror(errno)); + } + + return iccd; +} + +// Whether the whole input converts, and what to +static bool convert(const std::string &to_code, const std::string &from_code, const std::string &input, std::string &output) { + iconv_t iccd = open_iconv(to_code, from_code); + std::string buffer(input.size() * 4 + 4, '\0'); + +#ifdef __MINGW32__ + const char *inptr = input.data(); +#else + char * inptr = const_cast(input.data()); +#endif + char * outptr = &buffer[0]; + size_t in_left = input.size(); + size_t out_left = buffer.size(); + + size_t result = iconv(iccd, &inptr, &in_left, &outptr, &out_left); + + iconv_close(iccd); + + // glibc fails on a character the other side lacks, musl puts in '*' and counts it + if (result != 0 || in_left != 0) { + return false; + } + + output = buffer.substr(0, buffer.size() - out_left); + + return true; +} + +static bool is_ascii(const std::string &name) { + return std::all_of(name.begin(), name.end(), [](char c) { + return static_cast(c) < 0x80; + }); +} + +void check_codepage(const std::string &codepage) { + try { + iconv_close(open_iconv(codepage, "UTF-8")); + iconv_close(open_iconv("UTF-8", codepage)); + } catch (const Exception &) { + throw Exception("Unknown codepage {}", codepage); + } +} + +std::string sgold_name_from_utf8(const std::string &name, const std::string &codepage) { + std::string stored; + + if (is_ascii(name)) { + return name; + } + + if (convert(codepage, "UTF-8", name, stored)) { + return stored; + } + + if (!convert("UTF-16LE", "UTF-8", name, stored)) { + throw Exception("'{}' is not UTF-8", name); + } + + return UTF8_NAME_PREFIX + name; +} + +std::string sgold_name_to_utf8(const std::string &stored, const std::string &codepage) { + std::string name; + + if (stored.size() >= 2 && stored[0] == UTF8_NAME_PREFIX) { + return stored.substr(1); + } + + if (is_ascii(stored) || !convert("UTF-8", codepage, stored, name)) { + return stored; + } + + return name; +} + +}; +}; diff --git a/src/filesystem/codepage.h b/src/filesystem/codepage.h new file mode 100644 index 0000000..d61babd --- /dev/null +++ b/src/filesystem/codepage.h @@ -0,0 +1,22 @@ +#ifndef LIBFFSHIT_FULLFLASH_FILESYSTEM_CODEPAGE_H +#define LIBFFSHIT_FULLFLASH_FILESYSTEM_CODEPAGE_H + +#include + +namespace FULLFLASH { +namespace Filesystem { + +// SGOLD keeps a name in the 8-bit codepage of the phone's language when the codepage has all of its +// characters, and else as 0x1F followed by the name in UTF-8 + +// Throws when the codepage is unknown +void check_codepage(const std::string &codepage); +// The name as an SGOLD header keeps it. Throws when the name is not UTF-8. +std::string sgold_name_from_utf8(const std::string &name, const std::string &codepage); +// The name in UTF-8. A name the codepage cannot decode stays as it is. +std::string sgold_name_to_utf8(const std::string &stored, const std::string &codepage); + +}; +}; + +#endif diff --git a/src/filesystem/platform/base.cpp b/src/filesystem/platform/base.cpp index 4369f1d..359afad 100644 --- a/src/filesystem/platform/base.cpp +++ b/src/filesystem/platform/base.cpp @@ -1,11 +1,19 @@ #include "ffshit/filesystem/platform/base.h" #include "ffshit/filesystem/ex.h" +#include "filesystem/codepage.h" #include "filesystem/write/session.h" namespace FULLFLASH { namespace Filesystem { +void Base::set_codepage(const std::string &codepage) { + check_codepage(codepage); + + this->codepage = codepage; + session.reset(); +} + void Base::write_file(const std::string &path, const RawData &data, const TimePoint ×tamp) { throw Exception("Writing is not supported on this platform"); } @@ -20,7 +28,7 @@ void Base::remove(const std::string &path) { Write::Session &Base::write_session(Platform::Type platform, Partitions::Partitions::Ptr partitions, Directory::Ptr root) { if (!session) { - session = std::make_shared(platform, partitions, root); + session = std::make_shared(platform, partitions, root, codepage); } return *session; diff --git a/src/filesystem/platform/sgold.cpp b/src/filesystem/platform/sgold.cpp index 16f1211..86ab905 100644 --- a/src/filesystem/platform/sgold.cpp +++ b/src/filesystem/platform/sgold.cpp @@ -1,4 +1,5 @@ #include "ffshit/filesystem/platform/sgold.h" +#include "filesystem/codepage.h" #include "filesystem/write/session.h" #include "ffshit/filesystem/ex.h" @@ -163,10 +164,6 @@ SGOLD::FileHeader SGOLD::read_file_header(const RawData &data) { data.read(offset, reinterpret_cast(&header.attributes), 1); data.read(offset, reinterpret_cast(&header.next_part), 1); data.read_string(offset, header.name); - - if (header.name.size() >= 2 && header.name.at(0) == 0x1F) { - header.name.erase(header.name.begin(), header.name.begin() + 1); - } return header; } @@ -400,6 +397,8 @@ void SGOLD::scan(const std::string &block_name, FSBlocksMap &ffs_map, Directory: FileHeader file_header = read_file_header(tmp.data); auto timestamp = fat_timestamp_to_unix(file_header.fat_timestamp); + file_header.name = sgold_name_to_utf8(file_header.name, codepage); + Attributes attributes(file_header.attributes); if (verbose_processing) { diff --git a/src/filesystem/write/session.cpp b/src/filesystem/write/session.cpp index a2d46d8..37b2235 100644 --- a/src/filesystem/write/session.cpp +++ b/src/filesystem/write/session.cpp @@ -9,10 +9,11 @@ namespace FULLFLASH { namespace Filesystem { namespace Write { -Session::Session(Platform::Type platform, Partitions::Partitions::Ptr partitions, Directory::Ptr root) : +Session::Session(Platform::Type platform, Partitions::Partitions::Ptr partitions, Directory::Ptr root, const std::string &codepage) : platform(platform), partitions(partitions), - root(root) { + root(root), + codepage(codepage) { } Session::Path Session::parse(const std::string &path) const { @@ -41,7 +42,7 @@ Writer &Session::writer(const std::string &partition) { auto it = writers.find(partition); if (it == writers.end()) { - it = writers.emplace(partition, Writer::build(platform, partitions, partition)).first; + it = writers.emplace(partition, Writer::build(platform, partitions, partition, codepage)).first; } return *it->second; diff --git a/src/filesystem/write/session.h b/src/filesystem/write/session.h index bbe452c..b06170f 100644 --- a/src/filesystem/write/session.h +++ b/src/filesystem/write/session.h @@ -16,7 +16,7 @@ namespace Write { // the loaded directory tree and in the partitions' block data afterwards class Session { public: - Session(Platform::Type platform, Partitions::Partitions::Ptr partitions, Directory::Ptr root); + Session(Platform::Type platform, Partitions::Partitions::Ptr partitions, Directory::Ptr root, const std::string &codepage); // The paths start with the partition's name void write_file(const std::string &path, const RawData &data, const TimePoint ×tamp); @@ -33,6 +33,7 @@ class Session { Platform::Type platform; Partitions::Partitions::Ptr partitions; Directory::Ptr root; + std::string codepage; std::map writers; Path parse(const std::string &path) const; diff --git a/src/filesystem/write/writer.cpp b/src/filesystem/write/writer.cpp index 59263a2..2145059 100644 --- a/src/filesystem/write/writer.cpp +++ b/src/filesystem/write/writer.cpp @@ -3,6 +3,8 @@ #include "ffshit/filesystem/ex.h" #include "ffshit/filesystem/hash.h" +#include "filesystem/codepage.h" + #include #include @@ -586,7 +588,7 @@ class NewSgoldWriter : public Writer { } }; -// SGOLD: 16-bit ids, 8-bit names +// SGOLD: 16-bit ids, 8-bit names in the phone's codepage, or 0x1F and UTF-8 // // Header: id, parent id (16 bits), FAT time (32), data id (16), attributes with the upper 16 bits // set (32), next part (16), the name ending in a 0 @@ -595,13 +597,15 @@ class NewSgoldWriter : public Writer { // Directory entry: id, name hash (16 bits each), in records of 128 bytes class SgoldWriter : public Writer { public: - SgoldWriter(Records::Ptr records) : Writer(std::move(records)) { + SgoldWriter(Records::Ptr records, const std::string &codepage) : Writer(std::move(records)), codepage(codepage) { init(); } protected: static constexpr size_t HEADER_SIZE = 16; - static constexpr size_t NAME_LENGTH_MAX = 255; + static constexpr size_t NAME_SIZE_MAX = 255; + + std::string codepage; uint32_t root_id() const override final { return 6; @@ -722,24 +726,18 @@ class SgoldWriter : public Writer { } std::string to_stored(const std::string &name) const override final { - return name; + return sgold_name_from_utf8(name, codepage); } void check_new_name(const std::string &stored) const override final { - for (char c : stored) { - if (static_cast(c) >= 0x80) { - throw Exception("'{}': SGOLD names can only be ASCII", stored); - } - } - - if (stored.size() > NAME_LENGTH_MAX) { - throw Exception("Names are up to {} characters long", NAME_LENGTH_MAX); + if (stored.size() > NAME_SIZE_MAX) { + throw Exception("Names are up to {} bytes long", NAME_SIZE_MAX); } } + // The firmware folds ASCII letters only: "Ärger" and "ärger" are two names to it std::string folded(const std::string &stored) const override final { - // A name can start with 0x1F, which the readers drop - std::string name = stored.size() >= 2 && stored[0] == 0x1F ? stored.substr(1) : stored; + std::string name = stored; for (auto &c : name) { c = fold_case_8bit(c); @@ -749,11 +747,11 @@ class SgoldWriter : public Writer { } }; -Writer::Ptr Writer::build(Platform::Type platform, Partitions::Partitions::Ptr partitions, const std::string &partition_name) { +Writer::Ptr Writer::build(Platform::Type platform, Partitions::Partitions::Ptr partitions, const std::string &partition_name, const std::string &codepage) { Records::Ptr records = Records::build(platform, partitions, partition_name); switch (platform) { - case Platform::Type::SGOLD: return std::make_unique(std::move(records)); + case Platform::Type::SGOLD: return std::make_unique(std::move(records), codepage); case Platform::Type::SGOLD2: case Platform::Type::SGOLD2_ELKA: return std::make_unique(std::move(records)); default: { diff --git a/src/filesystem/write/writer.h b/src/filesystem/write/writer.h index 530c3f0..b68f99b 100644 --- a/src/filesystem/write/writer.h +++ b/src/filesystem/write/writer.h @@ -43,7 +43,8 @@ class Writer { public: using Ptr = std::unique_ptr; - static Ptr build(Platform::Type platform, Partitions::Partitions::Ptr partitions, const std::string &partition_name); + // SGOLD keeps names in the codepage + static Ptr build(Platform::Type platform, Partitions::Partitions::Ptr partitions, const std::string &partition_name, const std::string &codepage); virtual ~Writer() = default; diff --git a/tests/fullflash_fixture.cpp b/tests/fullflash_fixture.cpp index 69bd845..ecfdde4 100644 --- a/tests/fullflash_fixture.cpp +++ b/tests/fullflash_fixture.cpp @@ -31,7 +31,7 @@ std::filesystem::path find_fullflash(const std::string &file_name) { return {}; } -Loaded load(const std::filesystem::path &path) { +Loaded load(const std::filesystem::path &path, const std::string &codepage) { Loaded loaded; loaded.fullflash = FULLFLASH::FULLFLASH::build(path); @@ -40,6 +40,7 @@ Loaded load(const std::filesystem::path &path) { auto partitions = loaded.fullflash->get_partitions(); loaded.filesystem = FULLFLASH::Filesystem::build(partitions->get_fs_platform(), partitions); + loaded.filesystem->set_codepage(codepage); loaded.filesystem->load(); return loaded; @@ -218,12 +219,12 @@ void FullflashTest::TearDown() { } } -Loaded FullflashTest::save_and_reload(const Loaded &loaded, const std::string &file_name) { - std::filesystem::path path = temp_dir / file_name; +Loaded FullflashTest::save_and_reload(const Loaded &loaded, const std::string &codepage) { + std::filesystem::path path = temp_dir / "saved.bin"; loaded.fullflash->save(path); - return load(path); + return load(path, codepage); } std::string FullflashTest::dir_path(const std::string &name) const { diff --git a/tests/fullflash_fixture.h b/tests/fullflash_fixture.h index 4a64d8e..5af1a05 100644 --- a/tests/fullflash_fixture.h +++ b/tests/fullflash_fixture.h @@ -32,7 +32,8 @@ struct Loaded { FULLFLASH::Filesystem::Base::Ptr filesystem; }; -Loaded load(const std::filesystem::path &path); +// SGOLD file names are read in the codepage +Loaded load(const std::filesystem::path &path, const std::string &codepage = "CP1252"); // What a file or directory looked like: its content (empty for a directory) and timestamp struct Entry { @@ -72,7 +73,7 @@ class FullflashTest : public ::testing::TestWithParam { void TearDown() override; // Saves the fullflash and reads it back from the file - Loaded save_and_reload(const Loaded &loaded, const std::string &file_name = "saved.bin"); + Loaded save_and_reload(const Loaded &loaded, const std::string &codepage = "CP1252"); std::string dir_path(const std::string &name = "") const; }; diff --git a/tests/hash_test.cpp b/tests/hash_test.cpp index 164bf7c..29e1bd5 100644 --- a/tests/hash_test.cpp +++ b/tests/hash_test.cpp @@ -41,6 +41,18 @@ TEST(NameHashTest, HashesEightBitNamesLikeTheSgoldFirmware) { EXPECT_EQ(name_hash_8bit("s2200.bin"), 0xABDE); } +// As the emulated CX70 v56 stored names made over OBEX: in its codepage, CP1252, and else as 0x1F +// and the name in UTF-8. The hash is of the stored bytes. +TEST(NameHashTest, HashesEightBitNamesAsTheyAreStored) { + EXPECT_EQ(name_hash_8bit("\xC4rger"), 0x98DC); + EXPECT_EQ(name_hash_8bit("\xE4rger"), 0xA456); + EXPECT_EQ(name_hash_8bit("a\xE9\x80"), 0x9462); + EXPECT_EQ(name_hash_8bit("\x1F" "Файл"), 0x3152); + EXPECT_EQ(name_hash_8bit("\x1F" "файл"), 0x92E3); + EXPECT_EQ(name_hash_8bit("\x1F" "Ωμέγα"), 0x6F37); + EXPECT_EQ(name_hash_8bit("\x1F" "中文"), 0x35D3); +} + TEST(NameHashTest, FoldsTheCaseOfEightBitNames) { EXPECT_EQ(name_hash_8bit("MISC"), name_hash_8bit("misc")); EXPECT_EQ(name_hash_8bit("Misc"), name_hash_8bit("mIsC")); diff --git a/tests/write_test.cpp b/tests/write_test.cpp index 9327413..c0bd160 100644 --- a/tests/write_test.cpp +++ b/tests/write_test.cpp @@ -290,25 +290,60 @@ TEST_P(WriteTest, RejectsBadPaths) { } TEST_P(WriteTest, WritesNamesBeyondAscii) { - std::string path = dir_path("ffshit-файл.bin"); - - if (GetParam().platform == Type::SGOLD) { - // The 8-bit names of SGOLD have no known encoding beyond ASCII - EXPECT_THROW(write(path, pattern(100, 1)), FULLFLASH::BaseException); - - expect_unchanged_on_disk(); - - return; - } - Tree expected = snapshot(*original.filesystem); - write(path, pattern(100, 1)); - expected[path] = file_entry(pattern(100, 1)); + // On SGOLD in the codepage, and in UTF-8 when the codepage lacks a character + for (const std::string name : { "ffshit-Ärger.bin", "ffshit-файл.bin", "ffshit-中文.bin" }) { + write(dir_path(name), pattern(100, name.size())); + expected[dir_path(name)] = file_entry(pattern(100, name.size())); + } expect_tree(snapshot(*save_and_reload(original).filesystem), expected); } +TEST_P(WriteTest, FoldsTheCaseOfWhatTheFirmwareFolds) { + Tree expected = snapshot(*original.filesystem); + + write(dir_path("ffshit-ärger.bin"), pattern(100, 1)); + write(dir_path("ffshit-Ärger.bin"), pattern(200, 2)); + + // SGOLD folds ASCII letters only: both files are there + if (GetParam().platform == Type::SGOLD) { + expected[dir_path("ffshit-ärger.bin")] = file_entry(pattern(100, 1)); + } + + expected[dir_path("ffshit-Ärger.bin")] = file_entry(pattern(200, 2)); + + expect_tree(snapshot(*save_and_reload(original).filesystem), expected); +} + +TEST_P(WriteTest, KeepsSgoldNamesInThePhonesCodepage) { + if (GetParam().platform != Type::SGOLD) { + GTEST_SKIP() << "only SGOLD names are 8-bit"; + } + + original.filesystem->set_codepage("CP1251"); + + write(dir_path("ffshit-файл.bin"), pattern(100, 1)); + // CP1251 has no Ä + write(dir_path("ffshit-Ärger.bin"), pattern(100, 2)); + + Loaded cp1251 = save_and_reload(original, "CP1251"); + + EXPECT_NE(find_file(*cp1251.filesystem, dir_path("ffshit-файл.bin")), nullptr); + EXPECT_NE(find_file(*cp1251.filesystem, dir_path("ffshit-Ärger.bin")), nullptr); + + // The bytes of "файл" in CP1251 are "ôàéë" in CP1252, a name in UTF-8 reads the same in both + Loaded cp1252 = save_and_reload(original, "CP1252"); + + EXPECT_NE(find_file(*cp1252.filesystem, dir_path("ffshit-ôàéë.bin")), nullptr); + EXPECT_NE(find_file(*cp1252.filesystem, dir_path("ffshit-Ärger.bin")), nullptr); +} + +TEST_P(WriteTest, RejectsAnUnknownCodepage) { + EXPECT_THROW(original.filesystem->set_codepage("NO-SUCH-CODEPAGE"), FULLFLASH::BaseException); +} + TEST_P(WriteTest, ShowsTheChangesBeforeTheyAreSaved) { Tree expected = snapshot(*original.filesystem);