diff --git a/src/CoreLoader.cpp b/src/CoreLoader.cpp index 85c5b35..64327a0 100644 --- a/src/CoreLoader.cpp +++ b/src/CoreLoader.cpp @@ -1,43 +1,114 @@ +#include "echoion/host/CoreLoader.hpp" #include #include #include -#include "echoion/host/CoreLoader.hpp" +#include #include #include #include #include #include +#include + +#ifndef _WIN32 +#include +#include +#endif namespace Echoion::Host { + namespace + { + bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath) + { + const auto directory = libraryPath.parent_path(); +#ifdef _WIN32 + std::error_code error; + const auto status = std::filesystem::status(directory, error); + if (error || !std::filesystem::is_directory(status)) { + return false; + } + constexpr auto writable = std::filesystem::perms::owner_write | + std::filesystem::perms::group_write | + std::filesystem::perms::others_write; + return (status.permissions() & writable) != + std::filesystem::perms::none; +#else + struct stat metadata{}; + if (::stat(directory.c_str(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + return false; + } + + const auto effectiveUser = ::geteuid(); + const auto effectiveGroup = ::getegid(); + bool usesDirectoryGroup = effectiveGroup == metadata.st_gid; + if (!usesDirectoryGroup) { + const int count = ::getgroups(0, nullptr); + if (count > 0) { + std::vector groups(static_cast(count)); + if (::getgroups(count, groups.data()) == count) { + usesDirectoryGroup = + std::ranges::contains(groups, metadata.st_gid); + } + } + } + + mode_t required{}; + if (effectiveUser == metadata.st_uid) { + required = S_IWUSR | S_IXUSR; + } else if (usesDirectoryGroup) { + required = S_IWGRP | S_IXGRP; + } else { + required = S_IWOTH | S_IXOTH; + } + return (metadata.st_mode & required) == required && + ::access(directory.c_str(), W_OK | X_OK) == 0; +#endif + } + } // namespace CoreLoader::CoreLoader() : pluginManager_(Void::Plugin::PluginManager::Options{ .dlclose_on_swap = false, - .copy_on_load = true, - .config_provider = [this](std::string_view) { - return configPath_.string(); - }, - .instance_validator = [](Void::Plugin::IPlugin& plugin, - const Void::Plugin::PluginInfo&) { - return dynamic_cast(&plugin) != nullptr; - }}) + // Packaged Core libraries live in an immutable, service-readable + // directory. Initial load must never create a hotswap sibling + // there. + .copy_on_load = false, + .config_provider = + [this](std::string_view) { return configPath_.string(); }, + .instance_validator = + [](Void::Plugin::IPlugin& plugin, + const Void::Plugin::PluginInfo&) { + return dynamic_cast(&plugin) != + nullptr; + }}) { } void CoreLoader::enableAutoReload() { - if (autoReloadEnabled_.exchange(true)) { - return; // Already enabled - } - std::lock_guard lock(mutex_); + if (autoReloadEnabled_.load()) { + return; + } if (!currentLibraryPath_.empty() && std::filesystem::exists(currentLibraryPath_)) { - Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}", - currentLibraryPath_.string())); + if (!canCreateHotReloadCopy(currentLibraryPath_)) { + Void::Log::info( + "CoreLoader", "{}", + std::format( + "Auto-reload disabled for read-only Core directory: {}", + currentLibraryPath_.parent_path().string())); + return; + } + autoReloadEnabled_ = true; + Void::Log::info("CoreLoader", "{}", + std::format("Enabling auto-reload for: {}", + currentLibraryPath_.string())); - fileWatcher_.watch(currentLibraryPath_, + fileWatcher_.watch( + currentLibraryPath_, [this](const Void::FileSystem::FileWatcher::Event& event) { if (event.exists) { onCoreFileChanged(); @@ -66,7 +137,8 @@ namespace Echoion::Host return; } - Void::Log::info("CoreLoader", "{}", + Void::Log::info( + "CoreLoader", "{}", "Core file changed, scheduling hot reload after current track..."); // Small delay to ensure file write is complete @@ -88,7 +160,8 @@ namespace Echoion::Host } } - Void::Log::info("CoreLoader", "{}", + Void::Log::info( + "CoreLoader", "{}", std::format("Playback active (track: {}), deferring reload " "until track finishes", currentTrackId)); @@ -104,10 +177,12 @@ namespace Echoion::Host // No playback, reload immediately auto result = hotReload(currentLibraryPath_); if (!result) { - Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}", - result.error().message)); + Void::Log::error("CoreLoader", "{}", + std::format("Auto hot-reload failed: {}", + result.error().message)); } else { - Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully"); + Void::Log::info("CoreLoader", "{}", + "Auto hot-reload completed successfully"); } } } @@ -144,8 +219,10 @@ namespace Echoion::Host void CoreLoader::waitForTrackAndReload( const std::filesystem::path& targetPath, const std::string& trackId) { - Void::Log::info("CoreLoader", "{}", std::format( - "Waiting for track {} to finish before reload...", trackId)); + Void::Log::info( + "CoreLoader", "{}", + std::format("Waiting for track {} to finish before reload...", + trackId)); // Poll every 500ms to check if the specific track finished // (playback may continue with next track, but we only care about THIS @@ -157,7 +234,8 @@ namespace Echoion::Host if (deferredReloadCv_.wait_for( lock, std::chrono::milliseconds(500), [this] { return stopDeferredReload_.load(); })) { - Void::Log::info("CoreLoader", "{}", + Void::Log::info( + "CoreLoader", "{}", "Deferred hot-reload cancelled (loader shutting down)"); return; } @@ -167,7 +245,8 @@ namespace Echoion::Host return; } - Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload"); + Void::Log::info("CoreLoader", "{}", + "Track finished, starting hot reload"); // Clear pending flag { @@ -179,10 +258,12 @@ namespace Echoion::Host // Now do the reload auto result = hotReload(targetPath); if (!result) { - Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}", - result.error().message)); + Void::Log::error("CoreLoader", "{}", + std::format("Deferred hot-reload failed: {}", + result.error().message)); } else { - Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully"); + Void::Log::info("CoreLoader", "{}", + "Deferred hot-reload completed successfully"); } } @@ -211,7 +292,7 @@ namespace Echoion::Host if (loaded_) { return Api::fail(Api::ErrorCode::AlreadyExists, - "Core already loaded"); + "Core already loaded"); } if (!std::filesystem::exists(libraryPath)) { @@ -236,13 +317,13 @@ namespace Echoion::Host } Api::Result - CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) + CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { std::unique_lock lock(mutex_); if (!loaded_) { return Api::fail(Api::ErrorCode::NotFound, - "No core loaded to reload"); + "No core loaded to reload"); } auto targetPath = @@ -254,13 +335,22 @@ namespace Echoion::Host std::format("New library not found: {}", targetPath.string())); } if (targetPath != currentLibraryPath_) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "in-process Core reload must use the loaded path; release bundles " + return Api::fail( + Api::ErrorCode::InvalidArgument, + "in-process Core reload must use the loaded path; release " + "bundles " "with a new path are applied through daemon re-exec"); } + if (!canCreateHotReloadCopy(targetPath)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "in-process Core reload requires a writable library directory; " + "immutable releases are applied through daemon re-exec"); + } hotReloading_ = true; - Void::Log::info("CoreLoader", "{}", "Starting transactional hot reload..."); + Void::Log::info("CoreLoader", "{}", + "Starting transactional hot reload..."); // No callback may execute code from the old shared object after this // barrier returns. State capture and dlclose are safe only after event @@ -289,13 +379,15 @@ namespace Echoion::Host const auto reloadResult = pluginManager_.reload(pluginName_); if (!reloadResult) { hotReloading_ = false; - auto message = std::format( - "new Core rejected; running Core retained: {}", - Void::Plugin::to_string(reloadResult.error())); + auto message = + std::format("new Core rejected; running Core retained: {}", + Void::Plugin::to_string(reloadResult.error())); if (core_) { - if (auto initialized = core_->initialize(configPath_); !initialized) { - message += std::format("; retained Core reactivation failed: {}", - initialized.error().message); + if (auto initialized = core_->initialize(configPath_); + !initialized) { + message += + std::format("; retained Core reactivation failed: {}", + initialized.error().message); } else if (!state.empty()) { if (auto restored = core_->restoreState(state); !restored) { message += std::format( @@ -320,8 +412,9 @@ namespace Echoion::Host } if (!state.empty()) { if (auto restored = core_->restoreState(state); !restored) { - Void::Log::warn("CoreLoader", "new Core state restore failed: {}", - restored.error().message); + Void::Log::warn("CoreLoader", + "new Core state restore failed: {}", + restored.error().message); } } hotReloading_ = false; @@ -360,12 +453,12 @@ namespace Echoion::Host } Api::Result - CoreLoader::checkpoint(const std::filesystem::path& destination) + CoreLoader::checkpoint(const std::filesystem::path& destination) { std::lock_guard lock(mutex_); if (!core_) { return Api::fail(Api::ErrorCode::NotInitialized, - "cannot checkpoint without a loaded Core"); + "cannot checkpoint without a loaded Core"); } const auto state = core_->saveState(); std::string bytes; @@ -379,37 +472,37 @@ namespace Echoion::Host appendU32(static_cast(state.timestamp.size())); bytes.append(state.timestamp); bytes.append(reinterpret_cast(state.data.data()), - state.data.size()); + state.data.size()); if (auto result = Void::FileSystem::atomic_write(destination, bytes); !result) { return Api::fail(Api::ErrorCode::PluginError, - result.error().message()); + result.error().message()); } return {}; } Api::Result - CoreLoader::restoreCheckpoint(const std::filesystem::path& source) + CoreLoader::restoreCheckpoint(const std::filesystem::path& source) { std::lock_guard lock(mutex_); if (!core_) { return Api::fail(Api::ErrorCode::NotInitialized, - "cannot restore without a loaded Core"); + "cannot restore without a loaded Core"); } auto contents = Void::FileSystem::read_file(source); if (!contents) { return Api::fail(Api::ErrorCode::NotFound, - contents.error().message()); + contents.error().message()); } if (contents->size() < 8) { return Api::fail(Api::ErrorCode::ParseError, - "checkpoint header is truncated"); + "checkpoint header is truncated"); } auto readU32 = [&contents](std::size_t offset) { uint32_t value = 0; for (std::size_t index = 0; index < 4; ++index) { value = (value << 8U) | - static_cast((*contents)[offset + index]); + static_cast((*contents)[offset + index]); } return value; }; @@ -418,12 +511,13 @@ namespace Echoion::Host const auto timestampSize = readU32(4); if (timestampSize > contents->size() - 8) { return Api::fail(Api::ErrorCode::ParseError, - "checkpoint timestamp is truncated"); + "checkpoint timestamp is truncated"); } state.timestamp = contents->substr(8, timestampSize); const auto dataOffset = 8 + timestampSize; state.data.assign(contents->begin() + - static_cast(dataOffset), contents->end()); + static_cast(dataOffset), + contents->end()); return core_->restoreState(state); } @@ -432,9 +526,10 @@ namespace Echoion::Host { auto result = pluginManager_.load(path); if (!result) { - return Api::fail(Api::ErrorCode::PluginError, + return Api::fail( + Api::ErrorCode::PluginError, std::format("failed to load Core plugin: {}", - Void::Plugin::to_string(result.error()))); + Void::Plugin::to_string(result.error()))); } pluginName_ = std::move(*result); if (auto refreshed = refreshCoreHandle(); !refreshed) { @@ -453,11 +548,12 @@ namespace Echoion::Host pluginManager_.acquire(pluginName_)); if (!*pin) { return Api::fail(Api::ErrorCode::PluginError, - "Core plugin disappeared from the registry"); + "Core plugin disappeared from the registry"); } auto* interface = dynamic_cast(pin->get()); if (interface == nullptr) { - return Api::fail(Api::ErrorCode::InvalidArgument, + return Api::fail( + Api::ErrorCode::InvalidArgument, "Void plugin does not implement Echoion Core interface"); } core_ = Api::CoreInterfacePtr{std::move(pin), interface}; @@ -475,9 +571,10 @@ namespace Echoion::Host core_.reset(); if (!pluginName_.empty()) { if (auto result = pluginManager_.unload(pluginName_); !result) { - return Api::fail(Api::ErrorCode::PluginError, + return Api::fail( + Api::ErrorCode::PluginError, std::format("failed to unload Core plugin: {}", - Void::Plugin::to_string(result.error()))); + Void::Plugin::to_string(result.error()))); } pluginName_.clear(); }