diff --git a/source/gameanalytics/GALogger.cpp b/source/gameanalytics/GALogger.cpp index 6821bcc..e547d47 100644 --- a/source/gameanalytics/GALogger.cpp +++ b/source/gameanalytics/GALogger.cpp @@ -90,13 +90,14 @@ namespace gameanalytics return; } - std::string logFilePath = writablepath + "/" + LOG_FILE_NAME; + std::filesystem::path logFilePath = std::filesystem::u8path(writablepath); + logFilePath /= LOG_FILE_NAME; logFile.open(logFilePath, std::ios::out | std::ios::trunc); if (!logFile.is_open()) { - ZF_LOGW("Failed to open log file %s", logFilePath.c_str()); + std::cerr << "Failed to open log file:" << logFilePath << std::endl; return; } @@ -105,10 +106,9 @@ namespace gameanalytics logInitialized = true; currentLogCount = 0; - GALogger::i("Log file added under: %s", logFilePath.c_str()); + GALogger::i("Log file added under: %s", logFilePath.string().c_str()); } - void GALogger::sendNotificationMessage(std::string const& message, EGALoggerMessageType type) { if(customLogHandler) diff --git a/source/gameanalytics/GAStore.cpp b/source/gameanalytics/GAStore.cpp index 2a2c5e0..5201ce1 100644 --- a/source/gameanalytics/GAStore.cpp +++ b/source/gameanalytics/GAStore.cpp @@ -211,14 +211,16 @@ namespace gameanalytics { constexpr const char* DATABASE_NAME = "ga.sqlite3"; - std::filesystem::path p = device::GADevice::getWritablePath(); + std::filesystem::path p = std::filesystem::u8path(device::GADevice::getWritablePath()); p /= state::GAState::getGameKey(); - dbPath = (p / DATABASE_NAME).string(); - if(!std::filesystem::exists(p)) + dbPath = (p / DATABASE_NAME).u8string(); + std::error_code ec; + if(!std::filesystem::exists(p, ec)) { - if(!std::filesystem::create_directory(p)) + std::filesystem::create_directories(p, ec); + if(ec) return false; } diff --git a/source/gameanalytics/Platform/GALinux.cpp b/source/gameanalytics/Platform/GALinux.cpp index 8558f25..29ade77 100644 --- a/source/gameanalytics/Platform/GALinux.cpp +++ b/source/gameanalytics/Platform/GALinux.cpp @@ -117,19 +117,28 @@ std::string gameanalytics::GAPlatformLinux::getBuildPlatform() std::string gameanalytics::GAPlatformLinux::getPersistentPath() { - std::string path = std::getenv("HOME"); - path += "/GameAnalytics"; - - mode_t nMode = 0733; - int result = mkdir(path.c_str(), nMode); - if (result == 0 || errno == EEXIST) + std::string path = "GameAnalytics"; + std::error_code ec; + + const char* homeDir = std::getenv("HOME"); + if(homeDir && strlen(homeDir)) { - return path; + if(std::filesystem::exists(homeDir, ec) && !ec) + { + path = std::string(homeDir) + "/" + path; + } } - else + + if(!std::filesystem::exists(path, ec)) { - return ""; + std::filesystem::create_directories(path, ec); + if(ec) + { + return ""; + } } + + return path; } std::string gameanalytics::GAPlatformLinux::getDeviceModel() diff --git a/source/gameanalytics/Platform/GAMacOS.cpp b/source/gameanalytics/Platform/GAMacOS.cpp index 860a6a8..a8a41b0 100644 --- a/source/gameanalytics/Platform/GAMacOS.cpp +++ b/source/gameanalytics/Platform/GAMacOS.cpp @@ -41,19 +41,24 @@ std::string gameanalytics::GAPlatformMacOS::getConnectionType() std::string gameanalytics::GAPlatformMacOS::getPersistentPath() { std::string path = "GameAnalytics"; + std::error_code ec; const char* homeDir = std::getenv("HOME"); if(homeDir && strlen(homeDir)) { - if(std::filesystem::exists(homeDir)) + if(std::filesystem::exists(homeDir, ec) && !ec) { path = std::string(homeDir) + "/" + path; } } - if(!std::filesystem::exists(path)) + if(!std::filesystem::exists(path, ec)) { - std::filesystem::create_directory(path); + std::filesystem::create_directories(path, ec); + if(ec) + { + return ""; + } } return path; diff --git a/source/gameanalytics/Platform/GAWin32.cpp b/source/gameanalytics/Platform/GAWin32.cpp index cf06281..b0afe09 100644 --- a/source/gameanalytics/Platform/GAWin32.cpp +++ b/source/gameanalytics/Platform/GAWin32.cpp @@ -149,20 +149,25 @@ std::string GAPlatformWin32::getBuildPlatform() std::string GAPlatformWin32::getPersistentPath() { - std::string path = "GameAnalytics"; + namespace fs = std::filesystem; - char* appData = std::getenv("LOCALAPPDATA"); - if (appData && strlen(appData)) + fs::path path = L"GameAnalytics"; + + wchar_t* appData = nullptr; + size_t length = 0; + if (_wdupenv_s(&appData, &length, L"LOCALAPPDATA") == 0 && appData && *appData) { - path = std::string(appData) + '\\' + path; + path = fs::path(appData) / path; } + free(appData); - if(!std::filesystem::exists(path)) + std::error_code ec; + if (!fs::exists(path, ec)) { - std::filesystem::create_directories(path); + fs::create_directories(path, ec); } - return path; + return ec ? "" : path.u8string(); } std::string getRegistryKey(HKEY key, const TCHAR* subkey, const TCHAR* value) diff --git a/test/GAEventsTests.cpp b/test/GAEventsTests.cpp index 0edf1c8..ef8dc7e 100644 --- a/test/GAEventsTests.cpp +++ b/test/GAEventsTests.cpp @@ -16,8 +16,8 @@ using namespace gameanalytics; namespace { - constexpr const char* kGameKey = "bd624ee6f8e6efb32a054f8d7ba11618"; - constexpr const char* kGameSecret = "7f5c3f682cbd217841efba92e92ffb1b3b6612bc"; + constexpr const char* kGameKey = "0123456789abcdef0123456789abcdef"; + constexpr const char* kGameSecret = "0123456789abcdef0123456789abcdef01234567"; class MockHttpClient : public GAHttpClient { diff --git a/test/GAPersistentPathTests.cpp b/test/GAPersistentPathTests.cpp new file mode 100644 index 0000000..5574f0f --- /dev/null +++ b/test/GAPersistentPathTests.cpp @@ -0,0 +1,408 @@ +// +// GA-SDK-CPP +// Tests for how the SDK resolves and creates its persistent (writable) path: +// the platform default under the user's home / local app data folder, and +// custom paths supplied through GameAnalytics::configureWritablePath(). +// +// Non-ASCII path components are spelled as explicit UTF-8 bytes so the file +// stays ASCII and the literal is identical under every compiler, language +// standard and source charset. +// + +#include + +#include "GameAnalytics/GameAnalytics.h" + +#include +#include +#include +#include + +#include "helpers/GAStateTestAccessor.h" +#include "helpers/GATestHelpers.h" + +#include +#include +#include +#include + +#if IS_WIN32 + #include +#else + #include +#endif + +using namespace gameanalytics; + +namespace fs = std::filesystem; + +namespace +{ + constexpr const char* kGameKey = "0123456789abcdef0123456789abcdef"; + constexpr const char* kGameSecret = "0123456789abcdef0123456789abcdef01234567"; + constexpr const char* kDatabaseName = "ga.sqlite3"; + constexpr const char* kFolderName = "GameAnalytics"; + + // "héllo-测试-Дмитрий": Latin-1 supplement, CJK and Cyrillic in one component + constexpr const char* kUnicodeName = "h" "\xc3\xa9" "llo-" "\xe6\xb5\x8b" "\xe8\xaf\x95" "-" "\xd0\x94" "\xd0\xbc" "\xd0\xb8" "\xd1\x82" "\xd1\x80" "\xd0\xb8" "\xd0\xb9"; + +#if IS_WIN32 + constexpr const wchar_t* kHomeVariable = L"LOCALAPPDATA"; +#else + constexpr const char* kHomeVariable = "HOME"; +#endif + + // the SDK carries paths as UTF-8 std::string; these convert to and from + // std::filesystem::path without going through the ANSI code page on Windows + fs::path fromUtf8(std::string const& utf8) + { +#if defined(__cpp_lib_char8_t) + return fs::path(std::u8string(utf8.begin(), utf8.end())); +#else + return fs::u8path(utf8); +#endif + } + + std::string toUtf8(fs::path const& path) + { +#if defined(__cpp_lib_char8_t) + const std::u8string utf8 = path.u8string(); + return std::string(utf8.begin(), utf8.end()); +#else + return path.u8string(); +#endif + } + + // true when `utf8Path` names an existing directory that is the same + // directory as `expected` (tolerates symlinked temp dirs and 8.3 names) + bool sameDirectory(std::string const& utf8Path, fs::path const& expected) + { + std::error_code ec; + const fs::path actual = fromUtf8(utf8Path); + return fs::is_directory(actual, ec) && fs::equivalent(actual, expected, ec); + } + + // overrides the environment variable the platform derives its persistent + // path from, restoring the previous value on destruction. An empty value + // unsets the variable. + class ScopedHomeVariable + { + public: + explicit ScopedHomeVariable(fs::path const& value) + { + _hadPrevious = read(_previous); + write(value); + } + + ~ScopedHomeVariable() + { + write(_hadPrevious ? _previous : fs::path()); + } + + private: +#if IS_WIN32 + static bool read(fs::path& out) + { + const DWORD size = GetEnvironmentVariableW(kHomeVariable, nullptr, 0); + if (size == 0) + { + return false; + } + std::wstring value(size, L'\0'); + value.resize(GetEnvironmentVariableW(kHomeVariable, value.data(), size)); + out = value; + return true; + } + + static void write(fs::path const& value) + { + // the SDK reads the variable through the CRT, so update both views + SetEnvironmentVariableW(kHomeVariable, value.empty() ? nullptr : value.c_str()); + _wputenv_s(kHomeVariable, value.empty() ? L"" : value.c_str()); + } +#else + static bool read(fs::path& out) + { + const char* value = std::getenv(kHomeVariable); + if (!value) + { + return false; + } + out = value; + return true; + } + + static void write(fs::path const& value) + { + if (value.empty()) + { + unsetenv(kHomeVariable); + } + else + { + setenv(kHomeVariable, value.c_str(), 1); + } + } +#endif + + fs::path _previous; + bool _hadPrevious = false; + }; + + class GAPersistentPathTest : public ::testing::Test + { + protected: + void SetUp() override + { + // configureWritablePath() is rejected once the SDK is initialized + state::GAStateTestAccessor::forceUninitialized(); + + // the store places the database in a per-game-key subfolder and reads + // the key from GAState, so pin it rather than depend on test order + state::GAState::setKeys(kGameKey, kGameSecret); + + // remembered before any test touches HOME, so TearDown can put the + // shared test database back where the other suites expect it + _originalWritablePath = device::GADevice::getWritablePath(); + + std::error_code ec; + fs::path base = fs::temp_directory_path(ec); + if (ec) + { + base = fs::current_path(); + } + _root = base / ("ga-sdk-path-test-" + GATestHelpers::getRandomString(12)); + ASSERT_TRUE(fs::create_directories(_root)) << toUtf8(_root); + } + + void TearDown() override + { + device::GADevice::setWritablePath(_originalWritablePath); + EXPECT_TRUE(store::GAStore::ensureDatabase(false, kGameKey)); + + std::error_code ec; + fs::remove_all(_root, ec); + } + + static std::string platformPath() + { + return device::GADevice::getPlatform()->getPersistentPath(); + } + + static fs::path databaseFile(fs::path const& writablePath) + { + return writablePath / kGameKey / kDatabaseName; + } + + fs::path _root; + std::string _originalWritablePath; + }; +} + +// ---- platform default path ---- + +TEST_F(GAPersistentPathTest, PlatformPathIsCreatedUnderAsciiHome) +{ + const fs::path home = _root / "ascii-home"; + ASSERT_TRUE(fs::create_directories(home)); + ScopedHomeVariable scopedHome(home); + + const std::string path = platformPath(); + + ASSERT_FALSE(path.empty()); + EXPECT_EQ(kFolderName, fromUtf8(path).filename().string()); + EXPECT_TRUE(sameDirectory(path, home / kFolderName)) << path; +} + +TEST_F(GAPersistentPathTest, PlatformPathPreservesUnicodeHome) +{ + const fs::path home = _root / fromUtf8(kUnicodeName); + ASSERT_TRUE(fs::create_directories(home)); + ScopedHomeVariable scopedHome(home); + + const std::string path = platformPath(); + + ASSERT_FALSE(path.empty()); + // the string is handed to sqlite and the logger, so it has to be UTF-8 + EXPECT_NE(std::string::npos, path.find(kUnicodeName)) << path; + EXPECT_TRUE(sameDirectory(path, home / kFolderName)) << path; +} + +// a home directory that does not exist is an environment problem, not the +// SDK's: macOS and Linux fall back to a relative folder rather than creating +// it. Windows has no such guard and creates the missing tree. +TEST_F(GAPersistentPathTest, PlatformPathFallsBackWhenHomeIsMissing) +{ + const fs::path home = _root / "missing" / "nested" / "home"; + ASSERT_FALSE(fs::exists(home)); + ScopedHomeVariable scopedHome(home); + +#if IS_WIN32 + const fs::path expected = home / kFolderName; +#else + const fs::path expected = fs::current_path() / kFolderName; + const bool existedBefore = fs::exists(expected); +#endif + + const std::string path = platformPath(); + + ASSERT_FALSE(path.empty()); + EXPECT_TRUE(sameDirectory(path, expected)) << path; + +#if !IS_WIN32 + EXPECT_EQ(kFolderName, path); + if (!existedBefore) + { + std::error_code ec; + fs::remove_all(expected, ec); + } +#endif +} + +TEST_F(GAPersistentPathTest, PlatformPathFallsBackToRelativeDirectoryWithoutHome) +{ +#if IS_LINUX + // cannot be asserted in-process: the current Linux implementation builds a + // std::string from the null getenv() result, which would take the whole + // test binary down rather than fail this one test + GTEST_SKIP() << "Linux getPersistentPath() dereferences a null HOME"; +#endif + + const fs::path fallback = fs::current_path() / kFolderName; + const bool existedBefore = fs::exists(fallback); + ScopedHomeVariable scopedHome{fs::path()}; + + const std::string path = platformPath(); + + EXPECT_EQ(kFolderName, path); + EXPECT_TRUE(sameDirectory(path, fallback)) << path; + + if (!existedBefore) + { + std::error_code ec; + fs::remove_all(fallback, ec); + } +} + +#if !IS_WIN32 +TEST_F(GAPersistentPathTest, PlatformPathIsEmptyWhenHomeIsUnwritable) +{ + if (geteuid() == 0) + { + GTEST_SKIP() << "root is not subject to directory permissions"; + } + + const fs::path home = _root / "locked"; + ASSERT_TRUE(fs::create_directories(home)); + fs::permissions(home, fs::perms::owner_read | fs::perms::owner_exec); + ScopedHomeVariable scopedHome(home); + + std::string path; + ASSERT_NO_THROW(path = platformPath()); + + EXPECT_TRUE(path.empty()) << path; + EXPECT_FALSE(fs::exists(home / kFolderName)); + + fs::permissions(home, fs::perms::owner_all); +} +#endif + +// ---- device-level resolution ---- + +TEST_F(GAPersistentPathTest, DeviceResolvesPlatformPathWhenNoneConfigured) +{ + const fs::path home = _root / "device-home"; + ASSERT_TRUE(fs::create_directories(home)); + ScopedHomeVariable scopedHome(home); + + device::GADevice::setWritablePath(""); + EXPECT_FALSE(device::GADevice::getWritablePathStatus()); + + const std::string path = device::GADevice::getWritablePath(); + + EXPECT_TRUE(device::GADevice::getWritablePathStatus()); + EXPECT_TRUE(sameDirectory(path, home / kFolderName)) << path; +} + +// ---- custom path through the public API ---- + +TEST_F(GAPersistentPathTest, CustomPathIsUsedForDatabase) +{ + const fs::path custom = _root / "custom"; + ASSERT_TRUE(fs::create_directories(custom)); + + GameAnalytics::configureWritablePath(toUtf8(custom)); + ASSERT_EQ(toUtf8(custom), device::GADevice::getWritablePath()); + EXPECT_TRUE(device::GADevice::getWritablePathStatus()); + + ASSERT_TRUE(store::GAStore::ensureDatabase(false, kGameKey)); + EXPECT_TRUE(fs::is_regular_file(databaseFile(custom))); +} + +TEST_F(GAPersistentPathTest, CustomUnicodePathIsUsedForDatabase) +{ + const fs::path custom = _root / fromUtf8(kUnicodeName) / "custom"; + ASSERT_TRUE(fs::create_directories(custom)); + + GameAnalytics::configureWritablePath(toUtf8(custom)); + ASSERT_EQ(toUtf8(custom), device::GADevice::getWritablePath()); + + ASSERT_TRUE(store::GAStore::ensureDatabase(false, kGameKey)); + ASSERT_TRUE(fs::is_regular_file(databaseFile(custom))); + + // the database is not just created but usable at that location + store::GAStore::setState("persistent_path_test", "ok"); + json rows; + store::GAStore::executeQuerySync("SELECT value FROM ga_state WHERE key='persistent_path_test';", rows); + ASSERT_TRUE(rows.is_array()); + ASSERT_EQ(1u, rows.size()); + EXPECT_EQ("ok", rows[0]["value"].get()); +} + +TEST_F(GAPersistentPathTest, CustomPathIsCreatedWhenMissing) +{ + const fs::path custom = _root / "not" / "yet" / "there"; + ASSERT_FALSE(fs::exists(custom)); + + GameAnalytics::configureWritablePath(toUtf8(custom)); + + bool opened = false; + ASSERT_NO_THROW(opened = store::GAStore::ensureDatabase(false, kGameKey)); + EXPECT_TRUE(opened); + EXPECT_TRUE(fs::is_regular_file(databaseFile(custom))); +} + +TEST_F(GAPersistentPathTest, CustomPathToleratesTrailingSeparator) +{ + const fs::path custom = _root / "trailing"; + ASSERT_TRUE(fs::create_directories(custom)); + + GameAnalytics::configureWritablePath(toUtf8(custom) + "/"); + ASSERT_TRUE(store::GAStore::ensureDatabase(false, kGameKey)); + + EXPECT_TRUE(fs::is_regular_file(databaseFile(custom))); +} + +#if !IS_WIN32 +TEST_F(GAPersistentPathTest, UnwritableCustomPathFailsWithoutThrowing) +{ + if (geteuid() == 0) + { + GTEST_SKIP() << "root is not subject to directory permissions"; + } + + const fs::path locked = _root / "locked"; + ASSERT_TRUE(fs::create_directories(locked)); + fs::permissions(locked, fs::perms::owner_read | fs::perms::owner_exec); + const fs::path custom = locked / "custom"; + + GameAnalytics::configureWritablePath(toUtf8(custom)); + + bool opened = false; + ASSERT_NO_THROW(opened = store::GAStore::ensureDatabase(false, kGameKey)); + EXPECT_FALSE(opened); + EXPECT_FALSE(fs::exists(custom)); + + fs::permissions(locked, fs::perms::owner_all); +} +#endif diff --git a/test/GAStateTests.cpp b/test/GAStateTests.cpp index 60a1394..6aa0882 100644 --- a/test/GAStateTests.cpp +++ b/test/GAStateTests.cpp @@ -15,7 +15,7 @@ using namespace gameanalytics; namespace { - constexpr const char* kGameKey = "bd624ee6f8e6efb32a054f8d7ba11618"; + constexpr const char* kGameKey = "0123456789abcdef0123456789abcdef"; void seedCachedConfig(std::string const& lastUsedIdentifier, std::string const& configsHash) { diff --git a/test/GATests.cpp b/test/GATests.cpp index 795b520..4c42c4b 100644 --- a/test/GATests.cpp +++ b/test/GATests.cpp @@ -27,9 +27,9 @@ gameanalytics::logging::GALogger::setVerboseInfoLog(true); gameanalytics::logging::GALogger::i("Verbose logging enabled"); - gameanalytics::state::GAState::setKeys("bd624ee6f8e6efb32a054f8d7ba11618", "7f5c3f682cbd217841efba92e92ffb1b3b6612bc"); + gameanalytics::state::GAState::setKeys("0123456789abcdef0123456789abcdef", "0123456789abcdef0123456789abcdef01234567"); - ASSERT_TRUE(gameanalytics::store::GAStore::ensureDatabase(false, "bd624ee6f8e6efb32a054f8d7ba11618")); + ASSERT_TRUE(gameanalytics::store::GAStore::ensureDatabase(false, "0123456789abcdef0123456789abcdef")); gameanalytics::state::GAState::internalInitialize(); } diff --git a/test/GAValidatorTests.cpp b/test/GAValidatorTests.cpp index d238ab1..788d72c 100644 --- a/test/GAValidatorTests.cpp +++ b/test/GAValidatorTests.cpp @@ -460,7 +460,7 @@ TEST(GAValidator, testValidateResourceCurrencies) isValid = validationResult.result; ASSERT_TRUE(isValid) << "Error event should allow empty message"; } - isValid = gameanalytics::validators::GAValidator::validateSdkErrorEvent("c6cfc80ff69d1e7316bf1e0c8194eda6", "e0ae4809f70e2fa96916c7060f417ae53895f18d", gameanalytics::http::EventValidation, gameanalytics::http::ResourceEvent, gameanalytics::http::InvalidFlowType); + isValid = gameanalytics::validators::GAValidator::validateSdkErrorEvent("fedcba9876543210fedcba9876543210", "fedcba9876543210fedcba9876543210fedcba98", gameanalytics::http::EventValidation, gameanalytics::http::ResourceEvent, gameanalytics::http::InvalidFlowType); ASSERT_TRUE(isValid) << "Error event should validate"; } diff --git a/test/GameAnalyticsApiTests.cpp b/test/GameAnalyticsApiTests.cpp index df83f90..4b45125 100644 --- a/test/GameAnalyticsApiTests.cpp +++ b/test/GameAnalyticsApiTests.cpp @@ -31,8 +31,8 @@ using namespace gameanalytics; namespace { - constexpr const char* kGameKey = "bd624ee6f8e6efb32a054f8d7ba11618"; - constexpr const char* kGameSecret = "7f5c3f682cbd217841efba92e92ffb1b3b6612bc"; + constexpr const char* kGameKey = "0123456789abcdef0123456789abcdef"; + constexpr const char* kGameSecret = "0123456789abcdef0123456789abcdef01234567"; // shared handle so the client installed through the public // configureHttpClient() template stays inspectable from the test