diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index b5c2f0e866..17a2efc9e9 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -372,6 +372,7 @@ src/slic3r/Utils/MoonrakerPrinterAgent.cpp src/slic3r/Utils/BBLNetworkPlugin.cpp src/slic3r/Utils/OrcaCloudServiceAgent.cpp src/slic3r/plugin/PluginAuditManager.cpp +src/slic3r/plugin/PluginBrowserProfile.cpp src/slic3r/plugin/PluginConfig.cpp src/slic3r/plugin/PluginResolver.cpp src/slic3r/plugin/CloudPluginService.cpp diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index ef017ffb41..7706ab4425 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -709,6 +709,8 @@ set(SLIC3R_GUI_SOURCES plugin/host/PluginResourceTextures.hpp plugin/CloudPluginService.cpp plugin/CloudPluginService.hpp + plugin/PluginBrowserProfile.cpp + plugin/PluginBrowserProfile.hpp plugin/PluginFsUtils.cpp plugin/PluginFsUtils.hpp plugin/PluginJsonPy.hpp diff --git a/src/slic3r/GUI/Lazy.hpp b/src/slic3r/GUI/Lazy.hpp index 7f36f00d9e..07d0f98f55 100644 --- a/src/slic3r/GUI/Lazy.hpp +++ b/src/slic3r/GUI/Lazy.hpp @@ -114,6 +114,15 @@ public: bool pending() const override { return !built() && !m_failed; } int prebuild_order() const override { return m_order; } + // A null factory result marks the object failed. LazyPage lets the next explicit show retry + // a transient failure (for example a plugin profile lease held by another instance). + bool failed() const { return m_failed; } + void reset_failed() + { + if (!built()) + m_failed = false; + } + // The factory is the first unit, then one StagedBuild step each. A unit that pumps the // event loop cannot re-enter; a nested call does nothing. bool build_step() override diff --git a/src/slic3r/GUI/LazyPage.hpp b/src/slic3r/GUI/LazyPage.hpp index 5ef2c4320a..f98f5e2bb4 100644 --- a/src/slic3r/GUI/LazyPage.hpp +++ b/src/slic3r/GUI/LazyPage.hpp @@ -28,10 +28,12 @@ public: LazyPage(wxWindow* parent, std::string name, int order, Factory make = [](wxWindow* parent) { return new Panel(parent); }) : wxPanel(parent), Lazy(std::move(name), order, [this, make = std::move(make)] { Panel* panel = make(this); - GetSizer()->Add(panel, 1, wxEXPAND); - // Hidden while its page is, as an inserted page would be. - if (!IsShown()) - panel->Hide(); + if (panel != nullptr) { + GetSizer()->Add(panel, 1, wxEXPAND); + // Hidden while its page is, as an inserted page would be. + if (!IsShown()) + panel->Hide(); + } return panel; }) { @@ -61,8 +63,11 @@ public: // Built before this page is shown, as an idle prebuild builds it. On MSW every control // created or moved inside a shown window re-clips and repaints its shown siblings, so // building a large panel into a shown page took seconds. - if (show && wxGetTopLevelParent(this)->IsShown()) + if (show && wxGetTopLevelParent(this)->IsShown()) { + if (!this->built() && this->failed()) + this->reset_failed(); this->ensure(); + } const bool changed = wxPanel::Show(show); if (show) { // The book shows its first page as it is inserted, before startup has chosen the diff --git a/src/slic3r/GUI/Widgets/WebView.cpp b/src/slic3r/GUI/Widgets/WebView.cpp index 6acde27da0..072f771875 100644 --- a/src/slic3r/GUI/Widgets/WebView.cpp +++ b/src/slic3r/GUI/Widgets/WebView.cpp @@ -110,9 +110,15 @@ static wxString isolated_profile_path(const wxString& profile) // WebKitWebContext on Linux. One configuration per profile is therefore what lets two views of the // same plugin see each other's login; a configuration per view would share only the directory on // disk, not the session in memory. -static const wxWebViewConfiguration& profile_configuration(const wxString& profile) +static std::map& profile_configurations() { static std::map configs; + return configs; +} + +static const wxWebViewConfiguration& profile_configuration(const wxString& profile) +{ + auto& configs = profile_configurations(); const auto existing = configs.find(profile); if (existing != configs.end()) @@ -127,8 +133,26 @@ static const wxWebViewConfiguration& profile_configuration(const wxString& profi config.SetDataPath(isolated_profile_path(profile)); return configs.emplace(profile, config).first->second; } + +// Erase the cached configuration, which owns the WebView2 environment / WebKitWebContext. The +// caller must have destroyed every view of the profile first. +static void release_profile_configuration(const wxString& profile) +{ + profile_configurations().erase(profile); +} #endif // !__WXOSX__ +void WebView::ReleaseProfile(const wxString& profile) +{ +#if !defined(__WXOSX__) + release_profile_configuration(profile); +#else + // Drop the shared in-memory website data store for this profile. Views must already be gone; + // the caller holds the profile lease until the last view is destroyed. + Slic3r::GUI::WKWebViewConfiguration_releaseSharedNonPersistentDataStore(profile); +#endif +} + #ifdef __WIN32__ // Run Download and Install in another thread so we don't block the UI thread DWORD DownloadAndInstallWV2RT() { diff --git a/src/slic3r/GUI/Widgets/WebView.hpp b/src/slic3r/GUI/Widgets/WebView.hpp index effd196648..ea678bda97 100644 --- a/src/slic3r/GUI/Widgets/WebView.hpp +++ b/src/slic3r/GUI/Widgets/WebView.hpp @@ -20,6 +20,10 @@ public: // with the same `profile` share one store, and therefore one live session. Used for // plugin-supplied (untrusted) content. static wxWebView *CreateWebView(wxWindow *parent, wxString const &url, wxString const &profile = wxEmptyString); + + // Drops the cached configuration/environment for an isolated profile. Call on the GUI thread + // after every view of it has been destroyed. Needed before deleting the profile directory. + static void ReleaseProfile(const wxString& profile); #if wxUSE_WEBVIEW_EDGE static bool CheckWebViewRuntime(); static bool DownloadAndInstallWebViewRuntime(); diff --git a/src/slic3r/Utils/MacDarkMode.hpp b/src/slic3r/Utils/MacDarkMode.hpp index fcba824fdc..ee38b20d77 100644 --- a/src/slic3r/Utils/MacDarkMode.hpp +++ b/src/slic3r/Utils/MacDarkMode.hpp @@ -13,6 +13,7 @@ extern void set_miniaturizable(void * window); void WKWebView_evaluateJavaScript(void * web, wxString const & script, void (*callback)(wxString const &)); void WKWebView_setTransparentBackground(void * web); void WKWebViewConfiguration_setSharedNonPersistentDataStore(void * configuration, const wxString & profile); +void WKWebViewConfiguration_releaseSharedNonPersistentDataStore(const wxString & profile); void WKWebView_force_display(void * web); void set_tag_when_enter_full_screen(bool isfullscreen); void set_title_colour_after_set_title(void * window); diff --git a/src/slic3r/Utils/MacDarkMode.mm b/src/slic3r/Utils/MacDarkMode.mm index 0c77193b6f..1f123d0611 100644 --- a/src/slic3r/Utils/MacDarkMode.mm +++ b/src/slic3r/Utils/MacDarkMode.mm @@ -107,14 +107,19 @@ void WKWebView_setTransparentBackground(void * web) // default store. Views share a session only through a common store, and // +nonPersistentDataStore makes a new one on every call, so one store is kept per profile for the // process lifetime. Used to isolate plugin web views. -void WKWebViewConfiguration_setSharedNonPersistentDataStore(void * configuration, const wxString & profile) +static NSMutableDictionary * sharedNonPersistentStores() { static NSMutableDictionary * stores = nil; if (stores == nil) stores = [[NSMutableDictionary alloc] init]; + return stores; +} +void WKWebViewConfiguration_setSharedNonPersistentDataStore(void * configuration, const wxString & profile) +{ wxCFStringRef key_ref(profile); NSString * key = key_ref.AsNSString(); + NSMutableDictionary * stores = sharedNonPersistentStores(); WKWebsiteDataStore * store = [stores objectForKey:key]; if (store == nil) { store = [WKWebsiteDataStore nonPersistentDataStore]; @@ -126,6 +131,15 @@ void WKWebViewConfiguration_setSharedNonPersistentDataStore(void * configuration config.websiteDataStore = store; } +// Drops the profile's in-memory store once every view using it has been destroyed. Without this, +// a deleted/reinstalled plugin's old cookie/session store would stay alive for the process +// lifetime because the profile id is never reused. +void WKWebViewConfiguration_releaseSharedNonPersistentDataStore(const wxString & profile) +{ + wxCFStringRef key_ref(profile); + [sharedNonPersistentStores() removeObjectForKey:key_ref.AsNSString()]; +} + // Force a WKWebView to re-lay-out and repaint. Needed for chrome-less popups: the window is // transparent, so a WKWebView whose layer has no pending frame leaves the whole window invisible // until the user generates input (scroll/arrow). setNeedsDisplay alone does not always reach the diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index cfb284d321..c791b4b02f 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -2290,12 +2291,20 @@ void seed_install_metadata(const PluginDescriptor& descriptor, PluginInstallStat state.enabled = true; } +bool audit_state_belongs_to_loaded_identity(const std::string& plugin_key, const std::string& plugin_root, + const std::string& installation_revision); + // Serialize the sidecar read-modify-write against every other writer. The lock is taken before // the descriptor lookup, keeping the shared install-state -> PluginManager::m_mutex order. bool persist_permission(const std::string& plugin_key, AuditEventCategory category, bool by_event, const std::string& target) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return false; + } PluginDescriptor descriptor; if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) @@ -2307,6 +2316,11 @@ bool persist_permission(const std::string& plugin_key, AuditEventCategory catego // existing sidecar that cannot be read must not be replaced, or its grants would be lost. if (read_install_state_status(root, state) == InstallStateReadStatus::Unreadable) return false; + if (!audit_state_belongs_to_loaded_identity(plugin_key, descriptor.plugin_root, state.installation_revision)) { + BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Refusing to persist a grant for a replaced installation: " + << plugin_key; + return false; + } seed_install_metadata(descriptor, state); std::vector* permission_list = permission_list_for(category, by_event, state.permissions); @@ -2332,7 +2346,12 @@ bool persist_permission(const std::string& plugin_key, AuditEventCategory catego // Threading is a boolean grant, so it has no target list to append to. bool persist_threading_grant(const std::string& plugin_key) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return false; + } PluginDescriptor descriptor; if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) @@ -2343,6 +2362,11 @@ bool persist_threading_grant(const std::string& plugin_key) // Same rule as persist_permission: seed a missing sidecar, never replace an unreadable one. if (read_install_state_status(root, state) == InstallStateReadStatus::Unreadable) return false; + if (!audit_state_belongs_to_loaded_identity(plugin_key, descriptor.plugin_root, state.installation_revision)) { + BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Refusing to persist a threading grant for a replaced installation: " + << plugin_key; + return false; + } seed_install_metadata(descriptor, state); state.permissions.threading = true; return write_install_state(root, state); @@ -2825,6 +2849,16 @@ bool request_recursive_delete_consent(const std::string& plugin_key, const std:: return finish_audit_prompt(nullptr, granted && recursive_delete_generation(plugin_key) == generation); } +// Audit state must belong to the loaded installation, not a replacement installed by another +// process under the same plugin key. A missing identity is a fail-closed denial. +bool audit_state_belongs_to_loaded_identity(const std::string& plugin_key, const std::string& plugin_root, + const std::string& installation_revision) +{ + const PluginBrowserProfileIdentityRef identity = current_plugin_browser_profile_identity(plugin_key); + return identity && !identity->installation_revision.empty() && identity->plugin_root == plugin_root && + identity->installation_revision == installation_revision; +} + // Records a grant in the plugin's sidecar so it is not asked again. Each persist helper re-reads // the sidecar under the shared lock, because the async prompt outlives the caller's copy of it. // Returns true when at least one write succeeded, and only then notifies an existing Plugins @@ -2861,7 +2895,12 @@ bool persist_declared_permissions(const std::string& plugin_key, const std::vect bool persisted = false; { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return false; + } PluginInstallState state; const boost::filesystem::path root(descriptor.plugin_root); @@ -2872,6 +2911,11 @@ bool persist_declared_permissions(const std::string& plugin_key, const std::vect return false; if (status == InstallStateReadStatus::Absent && sidecar_was_readable) return false; + if (!audit_state_belongs_to_loaded_identity(plugin_key, descriptor.plugin_root, state.installation_revision)) { + BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Refusing to persist declared permissions for a replaced installation: " + << plugin_key; + return false; + } seed_install_metadata(descriptor, state); for (const AuditPromptBucket& bucket : buckets) { @@ -3353,7 +3397,12 @@ bool authorize_hardlink_source(PluginAuditManager& mgr, const std::string& event return true; PluginInstallState state; - const bool have_state = PluginManager::instance().get_install_state(mgr.current_plugin(), state); + PluginDescriptor descriptor; + const bool have_state = + PluginManager::instance().get_install_state(mgr.current_plugin(), state) && + PluginManager::instance().try_get_plugin_descriptor(mgr.current_plugin(), descriptor) && + audit_state_belongs_to_loaded_identity(mgr.current_plugin(), descriptor.plugin_root, + state.installation_revision); if (have_state && state.permissions.full_access) return true; if (have_state && @@ -3471,9 +3520,15 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A } PluginInstallState state; - const bool have_install_state = PluginManager::instance().get_install_state(mgr.current_plugin(), state); + PluginDescriptor descriptor; + const bool have_install_state = + PluginManager::instance().get_install_state(mgr.current_plugin(), state) && + PluginManager::instance().try_get_plugin_descriptor(mgr.current_plugin(), descriptor) && + audit_state_belongs_to_loaded_identity(mgr.current_plugin(), descriptor.plugin_root, + state.installation_revision); if (!have_install_state) { - BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << " Failed to get install state for " << mgr.current_plugin(); + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << " Refusing install state for a missing or replaced installation: " + << mgr.current_plugin(); } const std::string plugin_name = state.plugin_name.empty() ? mgr.current_plugin() : state.plugin_name; @@ -3744,7 +3799,12 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons PluginInstallState state; InstallStateReadStatus state_status; { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return false; + } state_status = read_install_state_status(boost::filesystem::path(descriptor.plugin_root), state); } @@ -3753,6 +3813,10 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons // that has not been given one yet and is seeded when the grant is saved. if (state_status == InstallStateReadStatus::Unreadable) return false; + if (!audit_state_belongs_to_loaded_identity(plugin_key, descriptor.plugin_root, state.installation_revision)) { + BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Refusing to read permissions for a replaced installation: " << plugin_key; + return false; + } // Full access is an explicit opt-out of auditing: a declaration neither prompts nor adds a // grant. Only a readable sidecar that stores the flag counts, so a missing file is never diff --git a/src/slic3r/plugin/PluginBrowserProfile.cpp b/src/slic3r/plugin/PluginBrowserProfile.cpp new file mode 100644 index 0000000000..f494d8d8d8 --- /dev/null +++ b/src/slic3r/plugin/PluginBrowserProfile.cpp @@ -0,0 +1,679 @@ +#include "PluginBrowserProfile.hpp" + +#include "PluginDescriptor.hpp" +#include "PluginFsUtils.hpp" +#include "PluginManager.hpp" +#include "libslic3r/Utils.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/NotificationManager.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Widgets/WebView.hpp" +#include "slic3r/GUI/format.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#include +#include +#endif + +#include +#include +#include +#include + +namespace Slic3r { + +namespace { + +namespace fs = boost::filesystem; + +fs::path profiles_root() +{ + return fs::path(Slic3r::data_dir()) / "web_profiles"; +} + +// Same sanitizer the base WebView::isolated_profile_path uses, so the old plugin-key-named +// directory can be reported exactly. +std::string sanitize_profile_name(const std::string& profile) +{ + std::string safe; + safe.reserve(profile.size()); + for (unsigned char ch : profile) { + const bool keep = std::isalnum(ch) != 0 || ch == '.' || ch == '-' || ch == '_'; + safe += keep ? static_cast(ch) : '_'; + } + return safe.empty() ? std::string("default") : safe; +} + +#if !defined(__APPLE__) +fs::path lease_path(const std::string& profile_id) +{ + return profiles_root() / (".lease-" + profile_id); +} +#endif + +// Non-blocking cross-process lock. Deliberately not InstanceLock: a lease is held across UI +// lifetimes and may be released on a different thread. +class ProfileFileLock +{ +public: + ProfileFileLock() = default; + ~ProfileFileLock() { close(); } + ProfileFileLock(const ProfileFileLock&) = delete; + ProfileFileLock& operator=(const ProfileFileLock&) = delete; + + bool open(const std::string& path) + { +#if defined(_WIN32) + const std::wstring wide = boost::nowide::widen(path); + HANDLE handle = ::CreateFileW(wide.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) + return false; + m_handle = handle; +#elif !defined(__APPLE__) + m_fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644); + if (m_fd < 0) + return false; + if (::flock(m_fd, LOCK_EX | LOCK_NB) != 0) { + ::close(m_fd); + m_fd = -1; + return false; + } +#else + (void) path; // in-memory store; no cross-process disk lease +#endif + return true; + } + + void close() + { +#if defined(_WIN32) + if (m_handle != nullptr) { + ::CloseHandle(static_cast(m_handle)); + m_handle = nullptr; + } +#elif !defined(__APPLE__) + if (m_fd >= 0) { + ::close(m_fd); + m_fd = -1; + } +#endif + } + +private: +#if defined(_WIN32) + void* m_handle{nullptr}; +#elif !defined(__APPLE__) + int m_fd{-1}; +#endif +}; + +struct LeaseState +{ + ProfileFileLock lock; +}; + +struct LeaseEntry +{ + std::shared_ptr lease; + unsigned uses{0}; + bool releasing{false}; +}; + +std::mutex& leases_mutex() +{ + static auto* mutex = new std::mutex; + return *mutex; +} + +std::unordered_map& leases() +{ + static auto* map = new std::unordered_map; + return *map; +} + +std::mutex& identities_mutex() +{ + static auto* mutex = new std::mutex; + return *mutex; +} + +std::unordered_map& identities() +{ + static auto* map = new std::unordered_map; + return *map; +} + +void push_warning_notification(const std::string& message) +{ + if (GUI::Plater* plater = GUI::wxGetApp().plater()) + plater->get_notification_manager()->push_notification( + GUI::NotificationType::CustomNotification, + GUI::NotificationManager::NotificationLevel::WarningNotificationLevel, message); +} + +// Startup/reset warnings can be produced before the plater exists. Retry briefly instead of +// dropping the only notification the user would see. +class WarningRetryTimer : public wxTimer +{ +public: + WarningRetryTimer(std::string message, int attempts) : m_message(std::move(message)), m_attempts(attempts) {} + + void Notify() override + { + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) + return; // process is going away; leave the timer to the app teardown + if (GUI::wxGetApp().plater() != nullptr) { + push_warning_notification(m_message); + GUI::wxGetApp().CallAfter([this]() { delete this; }); + } else if (--m_attempts > 0) { + StartOnce(500); + } else { + GUI::wxGetApp().CallAfter([this]() { delete this; }); + } + } + +private: + std::string m_message; + int m_attempts; +}; + +void warn_profile(const std::string& plugin_key, const std::string& message) +{ + static auto* mutex = new std::mutex; + static auto* reported = new std::unordered_set; + { + std::lock_guard lock(*mutex); + if (!reported->insert(plugin_key + '\n' + message).second) + return; + } + BOOST_LOG_TRIVIAL(warning) << message; + if (wxTheApp == nullptr) + return; + GUI::wxGetApp().CallAfter([message]() { + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) + return; + if (GUI::wxGetApp().plater() != nullptr) { + push_warning_notification(message); + return; + } + auto* timer = new WarningRetryTimer(message, 10); + timer->StartOnce(500); + }); +} + +std::string legacy_name(const std::string& plugin_key) +{ + return plugin_key.empty() ? std::string() : sanitize_profile_name(plugin_key); +} + +void delete_profile_on_ui_thread(const std::string& plugin_key, const std::string& profile_id, + const std::string& installation_root, int retries_left); + +void schedule_profile_delete(const std::string& plugin_key, const std::string& profile_id, + const std::string& installation_root, int retries_left) +{ + if (wxTheApp == nullptr) + return; + GUI::wxGetApp().CallAfter([plugin_key, profile_id, installation_root, retries_left]() { + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) + return; + delete_profile_on_ui_thread(plugin_key, profile_id, installation_root, retries_left); + }); +} + +void delete_profile_on_ui_thread(const std::string& plugin_key, const std::string& profile_id, + const std::string& installation_root, int retries_left) +{ + // Never let a hand-edited sidecar turn this into a path traversal outside web_profiles. + if (!is_uuid(profile_id)) + return; + if (!wxIsMainThread()) { + schedule_profile_delete(plugin_key, profile_id, installation_root, retries_left); + return; + } + + // Serialize with every sidecar/package writer across processes. A replacement that appears + // at this root after the package was removed must keep its profile. + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + warn_profile(plugin_key, + GUI::format(_u8L("The plugin was removed, but its browser profile could not be cleaned up: %1%"), + lock_error)); + return; + } + if (!installation_root.empty()) { + boost::system::error_code exists_ec; + const fs::path root(installation_root); + const bool root_exists = fs::exists(root, exists_ec); + if (exists_ec) { + warn_profile(plugin_key, + GUI::format(_u8L("The plugin was removed, but its browser profile could not be checked: %1%"), + exists_ec.message())); + return; + } + if (root_exists) { + warn_profile(plugin_key, + _u8L("The plugin was replaced by another OrcaSlicer instance, so its browser profile " + "was left untouched.")); + return; + } + } + + // If this process still has a closing view, give the GUI queue a few turns to destroy it. + { + std::lock_guard lock(leases_mutex()); + auto it = leases().find(profile_id); + if (it != leases().end()) { + if (it->second.uses > 0 || it->second.releasing) { + if (retries_left > 0) + schedule_profile_delete(plugin_key, profile_id, installation_root, retries_left - 1); + else + warn_profile(plugin_key, + _u8L("The plugin was removed, but its browser profile is still in use by a " + "closing plugin window. The profile was left untouched.")); + return; + } + leases().erase(it); + } + } + +#if defined(__APPLE__) + // The macOS profile store is in-memory and per process; there is no disk profile to delete, + // but an explicit delete/reset must drop its cookie/session store. + WebView::ReleaseProfile(wxString::FromUTF8(profile_id)); + (void) profile_id; + return; +#else + std::shared_ptr lease = std::make_shared(); + boost::system::error_code ec; + fs::create_directories(profiles_root(), ec); + if (ec) { + warn_profile(plugin_key, + GUI::format(_u8L("The plugin was removed, but its browser profile could not be deleted: %1%"), + ec.message())); + return; + } + if (!lease->lock.open(lease_path(profile_id).string())) { + warn_profile(plugin_key, + _u8L("The plugin was removed, but its browser profile is in use by another OrcaSlicer " + "instance. The profile was left untouched.")); + return; + } + + // All views are gone (the lease excludes every process). Release the cached WebView2 + // environment / WebKitWebContext before touching the directory. + WebView::ReleaseProfile(wxString::FromUTF8(profile_id)); + + const fs::path live = profiles_root() / profile_id; + const bool live_exists = fs::exists(live, ec); + if (ec) { + warn_profile(plugin_key, + GUI::format(_u8L("The plugin was removed, but its browser profile could not be checked: %1%"), + ec.message())); + lease->lock.close(); + return; + } + if (!live_exists) { + lease->lock.close(); + return; + } + + const fs::path tombstone = profiles_root() / + ("__deleted-" + profile_id + "-" + fs::unique_path("%%%%-%%%%-%%%%").string()); + ec.clear(); + fs::rename(live, tombstone, ec); + if (ec) { + lease->lock.close(); + // WebView2 can keep the environment's files open for a moment after the configuration is + // dropped; retry on later GUI iterations before giving up. + if (retries_left > 0) { + schedule_profile_delete(plugin_key, profile_id, installation_root, retries_left - 1); + return; + } + warn_profile(plugin_key, + GUI::format(_u8L("The plugin was removed, but its browser profile could not be deleted: %1%"), + ec.message())); + return; + } + + fs::remove_all(tombstone, ec); + if (ec) { + warn_profile(plugin_key, + GUI::format(_u8L("The plugin was removed, but its browser profile tombstone could not be fully " + "deleted: %1%"), + ec.message())); + } + lease->lock.close(); +#endif +} + +} // namespace + +std::string ensure_plugin_browser_profile(const std::string& plugin_key, bool* fresh, std::string* legacy_path, + std::string* installation_revision, const std::string* expected_root, + const std::string* expected_revision) +{ + if (fresh != nullptr) + *fresh = false; + if (legacy_path != nullptr) + legacy_path->clear(); + if (installation_revision != nullptr) + installation_revision->clear(); + + PluginDescriptor descriptor; + if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) + throw std::runtime_error( + GUI::format(_u8L("Cannot resolve the browser profile of an unknown plugin: %1%"), plugin_key)); + + const fs::path root = (expected_root != nullptr && !expected_root->empty()) ? fs::path(*expected_root) + : fs::path(descriptor.plugin_root); + std::string profile_id; + + { + std::lock_guard lock(install_state_mutex()); + + PluginInstallState state; + const InstallStateReadStatus status = read_install_state_status(root, state); + if (status == InstallStateReadStatus::Unreadable) + throw std::runtime_error(GUI::format(_u8L("Cannot read the plugin install state at %1%."), + (root / INSTALL_STATE_FILE).string())); + + // Compare the selected descriptor with the sidecar before binding or writing anything. + // A stale load must not adopt a replacement's identity/revision. + if (expected_revision != nullptr && !expected_revision->empty()) { + if (status != InstallStateReadStatus::Readable || state.installation_revision != *expected_revision) + throw std::runtime_error( + _u8L("The installed plugin changed while it was loading. Refresh the plugin list and try again.")); + } else if (status == InstallStateReadStatus::Readable && !state.installation_revision.empty()) { + // The descriptor has no selected revision, but the sidecar has one: this process's + // view of the installation is stale (or another instance replaced it). + throw std::runtime_error( + _u8L("The installed plugin revision is stale. Refresh the plugin list and try again.")); + } + + if (status == InstallStateReadStatus::Readable && !state.browser_profile_id.empty()) { + if (!is_uuid(state.browser_profile_id)) + throw std::runtime_error(GUI::format( + _u8L("The plugin install state at %1% has an invalid browser profile id. Reinstall the plugin " + "or repair the file; the id was left untouched."), + (root / INSTALL_STATE_FILE).string())); + profile_id = state.browser_profile_id; + // A first load of a pre-identity/pre-revision install must not leave an empty revision: + // delete and audit compare that token against the package on disk. + if (state.installation_revision.empty()) { + state.installation_revision = make_plugin_installation_revision(); + if (!write_install_state(root, state)) + throw std::runtime_error(GUI::format(_u8L("Cannot write the plugin install state at %1%."), + (root / INSTALL_STATE_FILE).string())); + PluginManager::instance().set_plugin_installation_revision(plugin_key, root.string(), + state.installation_revision); + } + } else { + if (status == InstallStateReadStatus::Absent) + seed_install_metadata(state, descriptor); + state.browser_profile_id = make_plugin_browser_profile_id(); + state.installation_revision = make_plugin_installation_revision(); + if (!write_install_state(root, state)) + throw std::runtime_error(GUI::format(_u8L("Cannot write the plugin install state at %1%."), + (root / INSTALL_STATE_FILE).string())); + PluginManager::instance().set_plugin_installation_revision(plugin_key, root.string(), + state.installation_revision); + profile_id = state.browser_profile_id; + } + if (installation_revision != nullptr) + *installation_revision = state.installation_revision; + } + + // The old WebView profile was named by plugin_key. Its data is ambiguous: it may belong to a + // different installation of the same plugin. Never reuse, move or delete it. Check even when + // the installer already wrote the fresh id (a cloud update of a pre-identity install), so the + // user still learns why the old login did not carry over. warn_profile deduplicates. + const std::string legacy = legacy_name(plugin_key); + if (!legacy.empty() && legacy != profile_id) { + const fs::path old = profiles_root() / legacy; + boost::system::error_code ec; + const bool exists = fs::exists(old, ec); + if (ec) { + warn_profile(plugin_key, + GUI::format(_u8L("A previous browser profile at %1% could not be checked: %2%"), + old.string(), ec.message())); + } else if (exists) { + if (fresh != nullptr) + *fresh = true; + if (legacy_path != nullptr) + *legacy_path = old.string(); + warn_profile(plugin_key, + GUI::format(_u8L("A previous browser profile exists at %1%. A new browser profile was " + "created; the old data was left untouched."), + old.string())); + } + } + return profile_id; +} + +static void release_profile_use(const std::string& profile_id) +{ + bool schedule = false; + { + std::lock_guard lock(leases_mutex()); + auto it = leases().find(profile_id); + if (it == leases().end()) + return; + if (it->second.uses > 0) + --it->second.uses; + if (it->second.uses == 0 && !it->second.releasing) { + it->second.releasing = true; + schedule = true; + } + } + if (!schedule || wxTheApp == nullptr) + return; + + // Release the cached WebView environment/context only after the last view's destructor has + // finished, then close the OS lease. Holding the lease until then is what prevents another + // process from deleting a live backend. + GUI::wxGetApp().CallAfter([profile_id]() { + std::shared_ptr lease; + { + std::lock_guard lock(leases_mutex()); + auto it = leases().find(profile_id); + if (it == leases().end() || it->second.uses > 0 || !it->second.releasing) + return; + lease = std::move(it->second.lease); + leases().erase(it); + } + if (lease) { +#if !defined(__APPLE__) + // Disk-backed profiles release the cached backend environment on close. On macOS the + // store itself is the in-memory session, so it must survive closing all views and is + // released only by an explicit delete/reset. + WebView::ReleaseProfile(wxString::FromUTF8(profile_id)); +#endif + lease->lock.close(); + // The lease file is deliberately never unlinked: another process may have opened the + // same inode and not locked it yet. Removing it would let two processes lock different + // inodes for the same profile. + } + }); +} + +BrowserProfileLease acquire_plugin_browser_profile_lease(const PluginBrowserProfileIdentityRef& identity) +{ + if (!identity || !is_uuid(identity->profile_id)) + return nullptr; + const std::string profile_id = identity->profile_id; + if (!plugin_browser_profile_is_current(identity)) + return nullptr; + + { + std::lock_guard lock(leases_mutex()); + auto& entry = leases()[profile_id]; + if (!entry.lease) { +#if defined(__APPLE__) + entry.lease = std::make_shared(); // in-memory store; no disk lease +#else + boost::system::error_code ec; + fs::create_directories(profiles_root(), ec); + entry.lease = std::make_shared(); + if (!entry.lease->lock.open(lease_path(profile_id).string())) { + leases().erase(profile_id); + return nullptr; + } +#endif + } + ++entry.uses; + entry.releasing = false; + } + + // Revalidate after taking the lease: the load instance may have been replaced in between, + // or the sidecar on disk may now describe a different installation/revision. + if (!plugin_browser_profile_is_current(identity) || !plugin_browser_profile_installation_is_current(identity)) { + release_profile_use(profile_id); + return nullptr; + } + return BrowserProfileLease(reinterpret_cast(1), [profile_id](void*) { release_profile_use(profile_id); }); +} + +PluginBrowserProfileIdentityRef begin_plugin_browser_profile(const std::string& plugin_key, + const std::string& expected_plugin_root, + const std::string& expected_revision) +{ + std::string revision; + const std::string profile_id = ensure_plugin_browser_profile(plugin_key, nullptr, nullptr, &revision, + &expected_plugin_root, &expected_revision); + auto identity = std::make_shared( + PluginBrowserProfileIdentity{plugin_key, profile_id, expected_plugin_root, revision}); + { + std::lock_guard lock(identities_mutex()); + identities()[plugin_key] = identity; + } + return identity; +} + +void end_plugin_browser_profile(const std::string& plugin_key) +{ + std::lock_guard lock(identities_mutex()); + identities().erase(plugin_key); +} + +PluginBrowserProfileIdentityRef current_plugin_browser_profile_identity(const std::string& plugin_key) +{ + std::lock_guard lock(identities_mutex()); + auto it = identities().find(plugin_key); + return it == identities().end() ? nullptr : it->second; +} + +bool plugin_browser_profile_is_current(const PluginBrowserProfileIdentityRef& identity) +{ + if (!identity) + return false; + std::lock_guard lock(identities_mutex()); + auto it = identities().find(identity->plugin_key); + return it != identities().end() && it->second == identity; +} + +bool plugin_browser_profile_installation_is_current(const PluginBrowserProfileIdentityRef& identity) +{ + if (!identity || identity->plugin_root.empty() || identity->installation_revision.empty()) + return false; + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) + return false; + PluginInstallState state; + if (read_install_state_status(boost::filesystem::path(identity->plugin_root), state) != + InstallStateReadStatus::Readable) + return false; + return state.browser_profile_id == identity->profile_id && + state.installation_revision == identity->installation_revision; +} + +void warn_plugin_browser_profile_in_use(const std::string& plugin_key) +{ + warn_profile(plugin_key, + _u8L("The plugin's browser profile is in use by another OrcaSlicer instance. Its plugin UI " + "was not opened.")); +} + +void warn_plugin_browser_profile_reset(const std::string& plugin_key) +{ + warn_profile(plugin_key, + _u8L("The plugin was reinstalled, so its browser profile and sign-in session were reset.")); +} + +void warn_plugin_browser_profile_cleanup_unknown(const std::string& plugin_key) +{ + warn_profile(plugin_key, + _u8L("The plugin was removed, but its browser profile could not be identified and may have been " + "left on disk.")); +} + +void warn_legacy_plugin_browser_profile(const std::string& plugin_key, const std::string& current_profile_id) +{ + const std::string legacy = legacy_name(plugin_key); + if (legacy.empty() || legacy == current_profile_id) + return; + const fs::path old = profiles_root() / legacy; + boost::system::error_code ec; + const bool exists = fs::exists(old, ec); + if (ec) { + warn_profile(plugin_key, + GUI::format(_u8L("A previous browser profile at %1% could not be checked: %2%"), + old.string(), ec.message())); + return; + } + if (exists) + warn_profile(plugin_key, + GUI::format(_u8L("A previous browser profile exists at %1%. A new browser profile was " + "created; the old data was left untouched."), + old.string())); +} + +void delete_plugin_browser_profile(const std::string& plugin_key, const std::string& profile_id, + const std::string& installation_root) +{ + if (profile_id.empty()) { +#if defined(__APPLE__) + // The pre-identity macOS store was keyed by the plugin key; drop it on delete/reset too. + const std::string legacy = legacy_name(plugin_key); + if (wxTheApp != nullptr && !legacy.empty()) + WebView::ReleaseProfile(wxString::FromUTF8(legacy)); +#endif + return; + } + if (!is_uuid(profile_id)) { + BOOST_LOG_TRIVIAL(warning) << "Refusing to delete an invalid browser profile id for " << plugin_key; + return; + } + if (wxTheApp == nullptr) + return; + if (wxIsMainThread()) + delete_profile_on_ui_thread(plugin_key, profile_id, installation_root, 20); + else + schedule_profile_delete(plugin_key, profile_id, installation_root, 20); +} + +} // namespace Slic3r diff --git a/src/slic3r/plugin/PluginBrowserProfile.hpp b/src/slic3r/plugin/PluginBrowserProfile.hpp new file mode 100644 index 0000000000..cc477c26a7 --- /dev/null +++ b/src/slic3r/plugin/PluginBrowserProfile.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include +#include + +namespace Slic3r { + +// A shared, process-local lease on one installation's browser profile. The lease owns the +// non-blocking cross-process lock on the profile's data directory; it lives as long as a webview +// that uses the profile. `std::shared_ptr` keeps this type out of UI headers. +using BrowserProfileLease = std::shared_ptr; + +// One loaded instance's browser-profile identity. Refreshing this object binds UI and callbacks +// to a particular load: a reload creates a new object even when the profile id is unchanged, so +// callbacks captured from the old instance cannot run against the replacement. +struct PluginBrowserProfileIdentity +{ + std::string plugin_key; + std::string profile_id; + std::string plugin_root; // package root this load instance was bound to + std::string installation_revision; // sidecar revision of that package +}; +using PluginBrowserProfileIdentityRef = std::shared_ptr; + +// Returns the installation-scoped browser profile id for `plugin_key`, creating and persisting a +// random id before any plugin code runs when the sidecar has none. A pre-identity directory found +// under the old plugin-key name is never reused, moved or deleted; fresh=true reports that a fresh +// profile was started because of it. Throws std::runtime_error when the sidecar cannot be read or +// written. +std::string ensure_plugin_browser_profile(const std::string& plugin_key, bool* fresh = nullptr, + std::string* legacy_path = nullptr, + std::string* installation_revision = nullptr, + const std::string* expected_root = nullptr, + const std::string* expected_revision = nullptr); + +// Binds one load instance to its profile id. Call before plugin code runs; an existing binding +// for the key is replaced, so callbacks from the previous load become stale. Compares the +// descriptor's selected root/revision with the sidecar before binding: a stale load of a +// replaced installation throws instead of adopting the replacement's identity. +PluginBrowserProfileIdentityRef begin_plugin_browser_profile(const std::string& plugin_key, + const std::string& expected_plugin_root, + const std::string& expected_revision); + +// Drops the binding for a key on unload or a failed load. +void end_plugin_browser_profile(const std::string& plugin_key); + +// The binding for the loaded instance, or null when the plugin is not bound. +PluginBrowserProfileIdentityRef current_plugin_browser_profile_identity(const std::string& plugin_key); + +// True when `identity` is still the current binding for its key. A reload, keep-local rekey or +// unload invalidates every previous identity, even when the underlying profile id is unchanged. +bool plugin_browser_profile_is_current(const PluginBrowserProfileIdentityRef& identity); + +// Re-reads the identity's own package root and requires the same profile id and installation +// revision. Use at UI creation and before persisting audit state, not on every message callback. +bool plugin_browser_profile_installation_is_current(const PluginBrowserProfileIdentityRef& identity); + +// Acquires a non-blocking lease on the identity's profile id. Returns null when another process +// owns the profile or the load instance was already replaced; callers must not create a webview +// then. +BrowserProfileLease acquire_plugin_browser_profile_lease(const PluginBrowserProfileIdentityRef& identity); + +// Reports (once) that this process could not take the profile lease, so plugin UI was not opened. +void warn_plugin_browser_profile_in_use(const std::string& plugin_key); + +// Reports (once) that a reinstall replaced the old profile with a fresh identity. +void warn_plugin_browser_profile_reset(const std::string& plugin_key); + +// Reports (once) that uninstall could not identify a profile to delete, so old profile data may +// remain on disk. +void warn_plugin_browser_profile_cleanup_unknown(const std::string& plugin_key); + +// Reports (once) that an old plugin-key-named profile exists and is not used by this installation. +// Used when the identity is created outside the normal load path (keep-local rekeying). +void warn_legacy_plugin_browser_profile(const std::string& plugin_key, const std::string& current_profile_id); + +// Attempts to delete the profile after the plugin package has been removed. Non-blocking: +// another process's lease means the cleanup is skipped and a warning is shown. When this process +// still has a closing view, the attempt is retried on the GUI thread. A tombstone rename ensures +// the live directory is removed before recursive deletion. `installation_root` is checked under +// the cross-process install-state lock on every attempt: if a replacement package exists there, +// its profile is left untouched. Pass an empty root when the caller has just installed a new +// package at a known root (the local reinstall path). +void delete_plugin_browser_profile(const std::string& plugin_key, const std::string& profile_id, + const std::string& installation_root = std::string()); + +} // namespace Slic3r diff --git a/src/slic3r/plugin/PluginDescriptor.hpp b/src/slic3r/plugin/PluginDescriptor.hpp index 9e55a89e59..7ac1181ba4 100644 --- a/src/slic3r/plugin/PluginDescriptor.hpp +++ b/src/slic3r/plugin/PluginDescriptor.hpp @@ -58,6 +58,7 @@ struct PluginDescriptor std::string version; // Selected plugin version std::string latest_version; // Authoritative latest available cloud version. std::string installed_version; // Locally installed package version. Preserved across cloud merges, which overwrite `version` with the latest cloud version. Empty when not installed. + std::string installation_revision; // Sidecar revision of the selected installed package; compare-and-delete token. std::vector display_types; // Display-only "compatibility" labels (cloud: raw service labels; local: from real capabilities). Never used for dispatch. std::string plugin_root; // Installed plugin directory, even when entry_path is invalid or ambiguous. std::string entry_path; // Full path to the installed plugin entry file diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index 480fc3f2e7..15835d7552 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -12,7 +12,11 @@ #include #include #include +#include #include +#include +#include +#include #include #include @@ -21,6 +25,10 @@ #define NOMINMAX #endif #include +#else +#include +#include +#include #endif #include "PluginAuditManager.hpp" @@ -36,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -45,7 +54,11 @@ #include #include #include +#include +#include #include +#include +#include #include #include @@ -53,13 +66,314 @@ namespace Slic3r { const char* const INSTALL_STATE_FILE = ".install_state.json"; -std::mutex& install_state_mutex() +namespace { + +// Cross-process half of install_state_mutex(). The lock file lives in the host-managed profile +// directory and is never unlinked: deleting it would let two processes lock different inodes and +// both believe they hold the sidecar lock. +class InstallStateFileLock +{ +public: + // Fails closed: returns false with an actionable reason. There is deliberately no + // process-local-only fallback, because that would let two OrcaSlicer instances mutate the + // same package/sidecar without isolation. + bool lock(std::string& error) + { + error.clear(); + const std::string base = data_dir(); + if (base.empty()) { + error = _u8L("The OrcaSlicer data directory is not initialized, so the plugin install-state lock " + "cannot be acquired."); + return false; + } + boost::system::error_code ec; + const boost::filesystem::path lock_dir = boost::filesystem::path(base) / "web_profiles"; + boost::filesystem::create_directories(lock_dir, ec); + if (ec) { + // TRN %1% is the lock folder, %2% the system error. + error = GUI::format(_u8L("Cannot create the plugin install-state lock directory %1%: %2%. " + "Check that the OrcaSlicer data directory is writable."), + lock_dir.string(), ec.message()); + return false; + } +#if defined(_WIN32) + if (m_handle != nullptr) + return true; + const std::string narrow_path = (boost::filesystem::path(base) / "web_profiles" / + ".install_state.lock").string(); + const std::wstring path = boost::nowide::widen(narrow_path); + HANDLE handle = ::CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) { + // TRN %1% is the lock file, %2% the numeric Windows error. + error = GUI::format(_u8L("Cannot open the plugin install-state lock file %1% (error %2%). " + "Check that the file and its folder are writable."), + narrow_path, std::to_string(::GetLastError())); + return false; + } + // Bounded wait: never hold the GUI indefinitely behind another instance. + constexpr auto deadline = std::chrono::milliseconds(1500); + const auto start = std::chrono::steady_clock::now(); + OVERLAPPED overlapped{}; + for (;;) { + overlapped = OVERLAPPED{}; + if (::LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, + &overlapped)) + break; + const DWORD code = ::GetLastError(); + if (code == ERROR_LOCK_VIOLATION && std::chrono::steady_clock::now() - start < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(25)); + continue; + } + ::CloseHandle(handle); + // TRN %1% is the lock file, %2% the numeric Windows error. + error = GUI::format(_u8L("Cannot lock the plugin install-state lock file %1% (error %2%). " + "Another OrcaSlicer instance is holding it; close it and retry."), + narrow_path, std::to_string(code)); + return false; + } + m_overlapped = overlapped; + m_handle = handle; +#else + if (m_fd >= 0) + return true; + const std::string path = + (boost::filesystem::path(base) / "web_profiles" / ".install_state.lock").string(); + m_fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644); + if (m_fd < 0) { + // TRN %1% is the lock file, %2% the system error. + error = GUI::format(_u8L("Cannot open the plugin install-state lock file %1%: %2%. " + "Check that the file and its folder are writable."), + path, std::string(std::strerror(errno))); + return false; + } + constexpr auto deadline = std::chrono::milliseconds(1500); + const auto start = std::chrono::steady_clock::now(); + for (;;) { + if (::flock(m_fd, LOCK_EX | LOCK_NB) == 0) + break; + const int code = errno; + if ((code == EWOULDBLOCK || code == EAGAIN) && std::chrono::steady_clock::now() - start < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(25)); + continue; + } + ::close(m_fd); + m_fd = -1; + // TRN %1% is the lock file, %2% the system error. + error = GUI::format(_u8L("Cannot lock the plugin install-state lock file %1%: %2%. " + "Another OrcaSlicer instance is holding it; close it and retry."), + path, std::string(std::strerror(code))); + return false; + } +#endif + return true; + } + + void unlock() + { +#if defined(_WIN32) + if (m_handle != nullptr) { + ::UnlockFileEx(m_handle, 0, MAXDWORD, MAXDWORD, &m_overlapped); + ::CloseHandle(m_handle); + m_handle = nullptr; + } +#else + if (m_fd >= 0) { + ::flock(m_fd, LOCK_UN); + ::close(m_fd); + m_fd = -1; + } +#endif + } + +private: +#if defined(_WIN32) + void* m_handle{nullptr}; + OVERLAPPED m_overlapped{}; +#else + int m_fd{-1}; +#endif +}; + +InstallStateFileLock& install_state_file_lock() +{ + static auto* lock = new InstallStateFileLock; + return *lock; +} + +// Reentrancy is per thread: a nested read-modify-write must not try to take the OS lock again. +thread_local unsigned t_install_state_depth = 0; + +// One non-blocking exclusive lock per package key, independent of the sidecar lock. Holding it +// across Python import prevents a concurrent install/delete from swapping the package files under +// a module that was selected under the old identity. +class PackageLeaseLock +{ +public: + bool open(const std::string& path, std::string& error) + { +#if defined(_WIN32) + const std::wstring wide = boost::nowide::widen(path); + HANDLE handle = ::CreateFileW(wide.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) { + // TRN %1% is the lease file, %2% the numeric Windows error. + error = GUI::format(_u8L("The plugin package is being loaded, installed, or removed by another " + "OrcaSlicer instance (lease %1%, error %2%). Retry after that operation finishes."), + path, std::to_string(::GetLastError())); + return false; + } + m_handle = handle; +#else + m_fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644); + if (m_fd < 0) { + // TRN %1% is the lease file, %2% the system error. + error = GUI::format(_u8L("Cannot open the plugin package lease %1%: %2%."), path, + std::string(std::strerror(errno))); + return false; + } + if (::flock(m_fd, LOCK_EX | LOCK_NB) != 0) { + const int code = errno; + ::close(m_fd); + m_fd = -1; + // TRN %1% is the lease file, %2% the system error. + error = GUI::format(_u8L("The plugin package is being loaded, installed, or removed by another " + "OrcaSlicer instance (lease %1%, error %2%). Retry after that operation finishes."), + path, std::string(std::strerror(code))); + return false; + } +#endif + return true; + } + + ~PackageLeaseLock() { close(); } + PackageLeaseLock(const PackageLeaseLock&) = delete; + PackageLeaseLock& operator=(const PackageLeaseLock&) = delete; + +private: + void close() + { +#if defined(_WIN32) + if (m_handle != nullptr) { + ::CloseHandle(static_cast(m_handle)); + m_handle = nullptr; + } +#else + if (m_fd >= 0) { + ::flock(m_fd, LOCK_UN); + ::close(m_fd); + m_fd = -1; + } +#endif + } + +#if defined(_WIN32) + void* m_handle{nullptr}; +#else + int m_fd{-1}; +#endif +}; + +uint64_t plugin_package_lease_hash(const std::string& plugin_key) +{ + uint64_t hash = 1469598103934665603ull; + for (unsigned char ch : plugin_key) { + hash ^= ch; + hash *= 1099511628211ull; + } + return hash; +} + +struct PackageLeaseState +{ + PackageLeaseLock lock; +}; + +} // namespace + +void PluginInstallStateMutex::lock() +{ + if (t_install_state_depth != 0) { + ++t_install_state_depth; + return; + } + + m_mutex.lock(); + std::string error; + bool locked = false; + try { + locked = install_state_file_lock().lock(error); + } catch (...) { + m_mutex.unlock(); + throw; + } + if (!locked) { + m_mutex.unlock(); + throw std::runtime_error(error.empty() ? std::string(_u8L("The plugin install-state lock is unavailable.")) : error); + } + t_install_state_depth = 1; +} + +void PluginInstallStateMutex::unlock() +{ + if (t_install_state_depth == 0) + return; + if (--t_install_state_depth == 0) { + install_state_file_lock().unlock(); + m_mutex.unlock(); + } +} + +PluginInstallStateMutex& install_state_mutex() { // Function-local static: safe to use from any writer regardless of static initialization order. - static std::mutex mutex; + static PluginInstallStateMutex mutex; return mutex; } +bool try_lock_plugin_install_state(std::unique_lock& lock, std::string& error) +{ + error.clear(); + try { + lock = std::unique_lock(install_state_mutex()); + return true; + } catch (const std::exception& ex) { + error = ex.what(); + return false; + } +} + +PluginPackageLease acquire_plugin_package_lease(const std::string& plugin_key, std::string& error) +{ + error.clear(); + if (plugin_key.empty()) { + error = _u8L("Cannot lease a plugin package without a plugin key."); + return nullptr; + } + const std::string base = data_dir(); + if (base.empty()) { + error = _u8L("The OrcaSlicer data directory is not initialized, so the plugin package lease cannot be acquired."); + return nullptr; + } + boost::system::error_code ec; + const boost::filesystem::path dir = boost::filesystem::path(base) / "web_profiles"; + boost::filesystem::create_directories(dir, ec); + if (ec) { + // TRN %1% is the lease folder, %2% the system error. + error = GUI::format(_u8L("Cannot create the plugin package lease directory %1%: %2%."), dir.string(), + ec.message()); + return nullptr; + } + std::ostringstream name; + name << ".package-" << std::hex << std::setw(16) << std::setfill('0') << plugin_package_lease_hash(plugin_key) + << ".lease"; + auto state = std::make_unique(); + if (!state->lock.open((dir / name.str()).string(), error)) + return nullptr; + return PluginPackageLease(state.release(), [](void* p) { delete static_cast(p); }); +} + std::string get_orca_plugins_dir() { namespace fs = boost::filesystem; @@ -305,7 +619,7 @@ void scan_plugin_directory(const std::string& dir_path, std::vector state_lock(install_state_mutex()); + std::lock_guard state_lock(install_state_mutex()); descriptor.install_state_valid = read_install_state(plugin_dir, descriptor); } assign_discovered_plugin_key(descriptor, plugin_dir); @@ -321,7 +635,7 @@ void scan_plugin_directory(const std::string& dir_path, std::vector state_lock(install_state_mutex()); + std::lock_guard state_lock(install_state_mutex()); descriptor.install_state_valid = read_install_state(plugin_dir, descriptor); } assign_discovered_plugin_key(descriptor, entry_path); @@ -338,7 +652,7 @@ void scan_plugin_directory(const std::string& dir_path, std::vector state_lock(install_state_mutex()); + std::lock_guard state_lock(install_state_mutex()); descriptor.install_state_valid = read_install_state(plugin_dir, descriptor); } assign_discovered_plugin_key(descriptor, entry_path); @@ -893,6 +1207,7 @@ bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescrip entry.installed_version = state.installed_version; if (!state.cloud_uuid.empty()) entry.cloud = CloudPluginState{state.cloud_uuid, true, false, false}; + entry.installation_revision = state.installation_revision; // Package-level auto-load flag only. The per-capability enable flags stay in the sidecar: a // capability has no existence — and so no state — until it is materialized, at which point the @@ -957,6 +1272,10 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& parsed.plugin_name = state["plugin_name"].get(); if (state.contains("cloud_uuid") && state["cloud_uuid"].is_string()) parsed.cloud_uuid = state["cloud_uuid"].get(); + if (state.contains("browser_profile_id") && state["browser_profile_id"].is_string()) + parsed.browser_profile_id = state["browser_profile_id"].get(); + if (state.contains("installation_revision") && state["installation_revision"].is_string()) + parsed.installation_revision = state["installation_revision"].get(); if (state.contains("permissions") && state["permissions"].is_object()) { const auto& permissions = state["permissions"]; @@ -1128,6 +1447,16 @@ void seed_install_metadata(PluginInstallState& state, const PluginDescriptor& en state.enabled = true; } +std::string make_plugin_browser_profile_id() +{ + return boost::uuids::to_string(boost::uuids::random_generator()()); +} + +std::string make_plugin_installation_revision() +{ + return boost::uuids::to_string(boost::uuids::random_generator()()); +} + bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginInstallState& state) { namespace fs = boost::filesystem; @@ -1140,6 +1469,10 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin json["enabled"] = state.enabled; if (!state.cloud_uuid.empty()) json["cloud_uuid"] = state.cloud_uuid; + if (!state.browser_profile_id.empty()) + json["browser_profile_id"] = state.browser_profile_id; + if (!state.installation_revision.empty()) + json["installation_revision"] = state.installation_revision; json["permissions"] = { {"fs_read", state.permissions.fs_read}, diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index 5845aa3acf..396c4c431d 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -4,6 +4,7 @@ #include +#include #include #include #include @@ -59,6 +60,13 @@ struct PluginInstallState { std::string installed_version; std::string plugin_name; std::string cloud_uuid; // empty for local + // Random installation-scoped browser profile identity. Persisted before plugin code runs. + // Empty on sidecars written before this field existed; the loader assigns one before import. + std::string browser_profile_id; + // Changes on every package install/replacement. Delete uses it as a compare-and-delete token + // so a replacement with the same profile id and version is still detected. Empty on older + // sidecars, where the field comparisons and entry mtime are the fallback. + std::string installation_revision; PluginPermissions permissions; @@ -137,15 +145,44 @@ std::vector collect_resource_texture_files(const std::string& dir, const std::string& plugin_root, std::string& error); -// Process-wide mutex serializing every in-process read and read-modify-write of a plugin's -// .install_state.json sidecar. Hold it across the read and the matching write so two writers -// cannot overwrite each other's grants, and around standalone reads so a reader cannot observe a -// state while another thread is replacing it. It is not a file lock: another OrcaSlicer process -// writing the same sidecar is not serialized. +// Serializes every read and read-modify-write of a plugin's .install_state.json sidecar, across +// processes and across threads in this process. Hold it across the read and the matching write so +// two writers cannot overwrite each other's grants or browser-profile identity, and around +// standalone reads so a reader cannot observe a state while another process is replacing it. +// The cross-process part is a blocking OS file lock in the host-managed web_profiles directory; +// the per-thread lock is reentrant so a writer may take it again around an inner read. +// lock() fails closed: if the OS lock cannot be created or acquired it throws std::runtime_error +// with a user-actionable reason after releasing the process mutex. Callers must let that failure +// abort the sidecar operation instead of proceeding unlocked. // -// Lock order: install-state mutex -> PluginManager::m_mutex. Code that already holds the manager +// Lock order: install-state lock -> PluginManager::m_mutex. Code that already holds the manager // lock must not acquire this one. -std::mutex& install_state_mutex(); +class PluginInstallStateMutex +{ +public: + PluginInstallStateMutex() = default; + PluginInstallStateMutex(const PluginInstallStateMutex&) = delete; + PluginInstallStateMutex& operator=(const PluginInstallStateMutex&) = delete; + + void lock(); + void unlock(); + +private: + std::mutex m_mutex; +}; + +PluginInstallStateMutex& install_state_mutex(); + +// Non-throwing acquisition for callers that must report an actionable error instead of +// propagating. On failure `lock` stays unlocked and `error` holds the reason. +bool try_lock_plugin_install_state(std::unique_lock& lock, std::string& error); + +// A non-blocking cross-process lease on one plugin package. Load holds it across selected +// identity verification, Python import and on_load; install/delete/keep-local hold it across +// package mutation. It is separate from the install-state lock, so Python callbacks can still +// read/write audit sidecars while it is held. +using PluginPackageLease = std::shared_ptr; +PluginPackageLease acquire_plugin_package_lease(const std::string& plugin_key, std::string& error); // Canonical writer: emits the .install_state.json schema for the given state. // The file is replaced strictly atomically: the payload is written to a uniquely named temporary @@ -171,6 +208,12 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin // that creates a sidecar on demand. void seed_install_metadata(PluginInstallState& state, const PluginDescriptor& entry); +// A random UUID used as the installation-scoped browser profile identity. +std::string make_plugin_browser_profile_id(); + +// A random UUID that changes on every installed-package revision. +std::string make_plugin_installation_revision(); + // Outcome of a sidecar read. Callers that may write a sidecar must distinguish Absent from // Unreadable: a missing file is a new install whose metadata may be seeded, while an existing file // that cannot be parsed -- or that cannot be examined because of a filesystem error -- holds state @@ -192,8 +235,8 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& // Reads install state back into the descriptor; plugin_key is always derived. Returns whether the // sidecar was present and valid. -// Caller must hold install_state_mutex(); it is not recursive, so a caller already holding the -// lock must call this raw overload, not PluginManager::get_install_state(). +// Caller must hold install_state_mutex(); prefer this raw overload over +// PluginManager::get_install_state() inside a locked read-modify-write. bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescriptor& entry); // Full read of the sidecar; returns false if there is no/invalid sidecar. // Caller must hold install_state_mutex(); see the note above. diff --git a/src/slic3r/plugin/PluginLoader.cpp b/src/slic3r/plugin/PluginLoader.cpp index a324f389aa..1e8d9c1e51 100644 --- a/src/slic3r/plugin/PluginLoader.cpp +++ b/src/slic3r/plugin/PluginLoader.cpp @@ -5,6 +5,7 @@ // service header stays free of the manager. #include "PluginManager.hpp" +#include "PluginBrowserProfile.hpp" #include "PluginConfig.hpp" #include "PluginFsUtils.hpp" #include "PythonInterpreter.hpp" @@ -261,6 +262,19 @@ bool load(const PluginDescriptor& descriptor, static std::mutex load_serializer; std::lock_guard load_lock(load_serializer); + // Hold the package lease across selected-identity verification, Python import and on_load. + // Install/delete/keep-local take the same lease non-blocking, so the package cannot be swapped + // under the module while it is being selected/imported. + PluginPackageLease package_lease; + if (!descriptor.plugin_root.empty()) { + std::string lease_error; + package_lease = acquire_plugin_package_lease(descriptor.plugin_key, lease_error); + if (!package_lease) { + error = GUI::format(_u8L("Cannot load the plugin while its package is being updated: %1%"), lease_error); + return false; + } + } + // A sidecar whose contents do not parse (cut short by a crash, or broken by a hand edit) would // make every writer refuse it, so a plugin that declares permissions could never load and no // grant or capability choice could be saved. Set it aside before any plugin code runs, so this @@ -270,7 +284,12 @@ bool load(const PluginDescriptor& descriptor, // Anything else at the sidecar path (a link, a directory, a file that cannot be opened or read // in full) is left alone, so its writers keep refusing. if (!descriptor.plugin_root.empty()) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + error = GUI::format(_u8L("Cannot inspect the plugin install state: %1%"), lock_error); + return false; + } const boost::filesystem::path plugin_root(descriptor.plugin_root); PluginInstallState unused_state; bool malformed = false; @@ -287,6 +306,31 @@ bool load(const PluginDescriptor& descriptor, } } + // Persist a random installation browser-profile id and bind this load instance to it before + // any plugin code runs. A failed load unbinds it so callbacks from an abandoned attempt cannot + // run against a later replacement. + struct ProfileBinding + { + explicit ProfileBinding(const std::string& plugin_key) : key(plugin_key) {} + ~ProfileBinding() + { + if (active) + end_plugin_browser_profile(key); + } + std::string key; + bool active{false}; + } profile_binding(descriptor.plugin_key); + if (!descriptor.plugin_root.empty()) { + try { + (void) begin_plugin_browser_profile(descriptor.plugin_key, descriptor.plugin_root, + descriptor.installation_revision); + profile_binding.active = true; + } catch (const std::exception& ex) { + error = GUI::format(_u8L("Failed to prepare the plugin browser profile: %1%"), ex.what()); + return false; + } + } + Plugin plugin; plugin.descriptor = descriptor; plugin.module_name = plugin_module_name(descriptor); @@ -345,7 +389,12 @@ bool load(const PluginDescriptor& descriptor, PluginInstallState install_state; bool have_install_state = false; { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + error = GUI::format(_u8L("Cannot read the plugin install state: %1%"), lock_error); + return false; + } have_install_state = !descriptor.plugin_root.empty() && read_install_state(boost::filesystem::path(descriptor.plugin_root), install_state); } @@ -500,6 +549,9 @@ bool load(const PluginDescriptor& descriptor, out = std::move(plugin); + // The load owns the binding from here on; PluginManager::unload_plugin ends it. + profile_binding.active = false; + BOOST_LOG_TRIVIAL(info) << "[plugin_loader::load] SUCCESS plugin=" << descriptor.plugin_key << " thread=" << std::this_thread::get_id(); return true; @@ -661,29 +713,58 @@ bool install_plugin(const boost::filesystem::path& filepath, const std::string& return install_plugin(filepath, cloud_user_id, descriptor, error); } +std::string local_plugin_package_key(const boost::filesystem::path& filepath) +{ + return make_local_plugin_key(canonical_or_absolute(filepath).filename().stem().string()); +} + bool install_plugin(const boost::filesystem::path& filepath, const std::string& cloud_user_id, PluginDescriptor& plugin_descriptor, std::string& error, bool* install_target_intact, - const PluginInstallState* preserved_state) + const PluginInstallState* preserved_state, + std::shared_ptr package_lease) { namespace fs = boost::filesystem; if (install_target_intact != nullptr) *install_target_intact = true; + auto fail = [&error](const std::string& message) { + error = GUI::format(_u8L("Plugin installation failed: %1%"), message); + return false; + }; + + // Package lease first, then the sidecar lock. The loader uses the same order, so a package + // cannot be replaced or deleted between its identity check and Python import. A caller that + // unloaded the old package first passes its lease in, so the lease failure cannot happen + // after the unload. + if (!package_lease) { + const std::string lease_key = !plugin_descriptor.cloud_uuid().empty() + ? plugin_descriptor.cloud_uuid() + : local_plugin_package_key(filepath); + std::string lease_error; + package_lease = acquire_plugin_package_lease(lease_key, lease_error); + if (!package_lease) + return fail(_u8L("Cannot install the plugin while its package is being loaded or updated: ") + lease_error); + } + + // Serialize the package and sidecar mutation with other processes. The sidecar writes below + // take the same lock again and are reentrant on this thread. + std::unique_lock install_lock; + std::string install_lock_error; + if (!try_lock_plugin_install_state(install_lock, install_lock_error)) { + return fail(_u8L("Cannot install the plugin because its install-state lock is unavailable: ") + + install_lock_error); + } + const std::string cloud_uuid = plugin_descriptor.cloud_uuid(); const bool is_cloud_install = !cloud_uuid.empty(); fs::path backup_dir; bool backup_created = false; - auto fail = [&error](const std::string& message) { - error = GUI::format(_u8L("Plugin installation failed: %1%"), message); - return false; - }; - boost::system::error_code ec; const fs::path source_path = canonical_or_absolute(filepath); @@ -796,9 +877,11 @@ bool install_plugin(const boost::filesystem::path& filepath, plugin_descriptor.clear_error(); // Write install state sidecar before removing the backup. The write takes the shared - // install-state mutex so it cannot interleave with an in-process read-modify-write writer. + // install-state lock so it cannot interleave with a reader or writer in any process. + std::string previous_profile_id; + std::string installed_profile_id; { - std::lock_guard state_lock(install_state_mutex()); + std::lock_guard state_lock(install_state_mutex()); // Seed the metadata of the package being installed. An update supplies the previous // activation and capability choices; permissions are always reset because the new @@ -810,6 +893,38 @@ bool install_plugin(const boost::filesystem::path& filepath, state.capabilities = preserved_state->capabilities; } + // Installation browser-profile id. A same-target cloud update of the same UUID keeps it, + // so an installed plugin stays signed in across updates and restarts. A local install or + // reinstallation gets a fresh id, and the previous profile is removed after the commit. + PluginInstallState previous_state; + const bool had_previous_state = backup_created && read_install_state(backup_dir, previous_state); + std::string profile_id; + if (had_previous_state && !previous_state.browser_profile_id.empty() && + !is_uuid(previous_state.browser_profile_id)) + BOOST_LOG_TRIVIAL(warning) << "Ignoring an invalid browser profile id in " << backup_dir.string() + << "; the replacement starts with a fresh profile"; + if (is_cloud_install && had_previous_state && previous_state.cloud_uuid == cloud_uuid && + is_uuid(previous_state.browser_profile_id)) + profile_id = previous_state.browser_profile_id; + try { + if (profile_id.empty()) + profile_id = make_plugin_browser_profile_id(); + state.installation_revision = make_plugin_installation_revision(); + } catch (const std::exception& ex) { + // The backup is already in place; do not let a throwing UUID generator escape without + // restoring the package this call replaced. + restore_backup(); + return fail(GUI::format(_u8L("Cannot create a plugin installation identity: %1%"), ex.what())); + } catch (...) { + restore_backup(); + return fail(_u8L("Cannot create a plugin installation identity.")); + } + state.browser_profile_id = profile_id; + plugin_descriptor.installation_revision = state.installation_revision; + installed_profile_id = profile_id; + if (had_previous_state && is_uuid(previous_state.browser_profile_id)) + previous_profile_id = previous_state.browser_profile_id; + if (!write_install_state(final_dir, state)) { // Roll back: remove new files and restore backup. restore_backup(); @@ -829,6 +944,17 @@ bool install_plugin(const boost::filesystem::path& filepath, BOOST_LOG_TRIVIAL(warning) << "Failed to remove plugin backup " << backup_dir.string() << ": " << remove_ec.message(); } + // A replacement with a fresh id must not leave the old installation's profile behind. A + // same-id cloud update does not reach here. Best effort: a live lease warns and skips. + if (!previous_profile_id.empty() && previous_profile_id != installed_profile_id) { + warn_plugin_browser_profile_reset(plugin_descriptor.plugin_key); + delete_plugin_browser_profile(plugin_descriptor.plugin_key, previous_profile_id); + } else if (backup_created && previous_profile_id.empty()) { + // The replaced package had no usable identity (legacy/missing sidecar), so this install + // starts a fresh profile. Report the reset rather than dropping the old session silently. + warn_plugin_browser_profile_reset(plugin_descriptor.plugin_key); + } + BOOST_LOG_TRIVIAL(info) << "Installed plugin " << plugin_descriptor.name << " to " << final_dir.string(); if (is_cloud_install) { diff --git a/src/slic3r/plugin/PluginLoader.hpp b/src/slic3r/plugin/PluginLoader.hpp index 2dc86283af..cd91effb20 100644 --- a/src/slic3r/plugin/PluginLoader.hpp +++ b/src/slic3r/plugin/PluginLoader.hpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -59,7 +60,12 @@ bool install_plugin(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor, std::string& error, bool* install_target_intact = nullptr, - const PluginInstallState* preserved_state = nullptr); + const PluginInstallState* preserved_state = nullptr, + std::shared_ptr package_lease = {}); bool install_plugin(const boost::filesystem::path& filepath, const std::string& cloud_user_id, std::string& error); +// Canonical local plugin key for a source path, used both for the installed key and for the +// package lease. Symlink names therefore cannot select a different lease. +std::string local_plugin_package_key(const boost::filesystem::path& filepath); + } // namespace Slic3r::plugin_loader diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index 4a802c1c59..93185bcfc2 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -12,6 +12,7 @@ #include #include +#include "PluginBrowserProfile.hpp" #include "PluginFsUtils.hpp" #include "PluginHooks.hpp" #include "PluginAuditManager.hpp" @@ -34,6 +35,7 @@ #include #include +#include #include #include "slic3r/plugin/CloudPluginService.hpp" #include @@ -60,6 +62,46 @@ namespace { // A cancelled load records no error and fires no failure path — it just unwinds. const char* const LOAD_CANCELLED = "__plugin_load_cancelled__"; +// A fail-closed sidecar lock can prevent a persistence-only follow-up (capability toggle, unload +// flag, permission revoke) from being written. Report it instead of silently keeping only the +// in-memory change. +void report_plugin_state_persist_failure(const std::string& message) +{ + BOOST_LOG_TRIVIAL(error) << message; + if (wxTheApp == nullptr) + return; + GUI::wxGetApp().CallAfter([message]() { + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) + return; + if (GUI::Plater* plater = GUI::wxGetApp().plater()) + plater->get_notification_manager()->push_notification( + GUI::NotificationType::CustomNotification, + GUI::NotificationManager::NotificationLevel::WarningNotificationLevel, message); + }); +} + +// A sidecar write for a loaded plugin must target the installation the process actually loaded. +// Prefer the loaded identity; fall back to the selected descriptor revision for paths that run +// before binding (a failed load or an install's immediate revoke). No baseline allows legacy. +bool install_state_matches_selected(const std::string& plugin_key, const std::string& plugin_root, + const PluginInstallState& state, bool prefer_descriptor) +{ + const PluginBrowserProfileIdentityRef identity = current_plugin_browser_profile_identity(plugin_key); + if (identity && !prefer_descriptor) + return identity->plugin_root == plugin_root && identity->installation_revision == state.installation_revision; + + PluginDescriptor descriptor; + if (PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor)) { + if (!descriptor.installation_revision.empty()) + return descriptor.plugin_root == plugin_root && + descriptor.installation_revision == state.installation_revision; + // No selected revision: only a revision-less legacy sidecar is safe to touch. + return state.installation_revision.empty(); + } + + return !identity; // no identity and no descriptor: legacy path, allow +} + std::vector* permission_bucket(PluginPermissions& permissions, PluginPermissionCategory category) { switch (category) { @@ -308,7 +350,12 @@ void PluginManager::run_discovery_task(bool clear) const std::vector dirs = get_plugin_directories(cloud_user_id); std::vector discovered = discover_plugin_packages(dirs, error); - merge_discovered_plugins(std::move(discovered), clear); + // A failed scan may be partial (for example the install-state lock is unavailable). Do not + // merge a partial list, which would make unscanned plugins look removed. + if (error.empty()) + merge_discovered_plugins(std::move(discovered), clear); + else + BOOST_LOG_TRIVIAL(error) << "Plugin discovery is incomplete; keeping the previous registry: " << error; } catch (const std::exception& ex) { error = std::string("Plugin discovery failed: ") + ex.what(); BOOST_LOG_TRIVIAL(error) << error; @@ -361,6 +408,11 @@ void PluginManager::merge_discovered_plugins(std::vector disco continue; } + // A loaded plugin's descriptor describes the live package and revision. A manifest + // rescan may be from a different package or a partial scan; never replace it while the + // module is loaded, or audit/delete would point at a replacement under the same key. + if (existing->is_loaded()) + continue; // A manifest-only rescan has nothing to say about capabilities, so the live module and // instances are left alone. if (!descriptor.install_state_valid) @@ -525,6 +577,19 @@ bool PluginManager::try_get_plugin_descriptor(const std::string& plugin_key, Plu return true; } +void PluginManager::set_plugin_installation_revision(const std::string& plugin_key, const std::string& plugin_root, + const std::string& revision) +{ + if (revision.empty()) + return; + std::lock_guard lock(m_mutex); + Plugin* plugin = find_plugin_locked(plugin_key); + if (plugin == nullptr || plugin->descriptor.plugin_root != plugin_root) + return; + if (plugin->descriptor.installation_revision.empty() || plugin->descriptor.installation_revision == revision) + plugin->descriptor.installation_revision = revision; +} + bool PluginManager::try_get_valid_plugin_descriptor(const std::string& plugin_key, PluginDescriptor& out) const { std::lock_guard lock(m_mutex); @@ -689,9 +754,14 @@ std::shared_ptr PluginManager::get_plugin_capability( bool PluginManager::get_install_state(const std::string& plugin_key, PluginInstallState& install_state) { - // Serialize the read against every in-process sidecar writer. Lock order stays + // Serialize the read against every sidecar writer in this and other processes. Lock order stays // install-state -> m_mutex, matching the writers. - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return false; + } PluginDescriptor descriptor; if (!try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) { @@ -1077,11 +1147,17 @@ void PluginManager::load_plugin_impl(const std::string& plugin_key, bool skip_de } if (error == LOAD_CANCELLED || load_cancelled) { BOOST_LOG_TRIVIAL(info) << "[load_plugin_impl] CANCELLED plugin=" << plugin_key; - return; // cancelled: nothing materialized survives, and no error is recorded + // The unload that cancelled it also ran cleanup, but the load may have created UI + // after that point. Callbacks are idempotent, so close anything still around. + run_on_unload_callbacks(plugin_key); + return; } if (registration_failed) mark_plugin_install_state_disabled(plugin_key); fail(std::move(error)); + // on_load may already have created plugin UI before failing. It is not committed, so + // close it and drop any partially registered subscribers after the error is visible. + run_on_unload_callbacks(plugin_key); return; } @@ -1123,10 +1199,15 @@ void PluginManager::load_plugin_impl(const std::string& plugin_key, bool skip_de } if (!committed) { + // The loader bound this instance before on_load; it is not being committed. + end_plugin_browser_profile(plugin_key); // Outside the lock: this runs on_unload() and DECREFs the module. plugin_loader::unload(plugin); if (!cancelled) fail(std::move(registry_error)); + // Idempotent: closes UI that on_load created after an unload's own cleanup, and handles + // the ordinary commit-failure case. + run_on_unload_callbacks(plugin_key); return; } @@ -1185,6 +1266,9 @@ bool PluginManager::unload_plugin(const std::string& plugin_key) PluginAuditManager::discard_pending_permission_prompts_for(plugin_key); if (!found) { + // A failed load may have left UI behind even though no live plugin was committed. + end_plugin_browser_profile(plugin_key); + notify_unload_complete(); notify_plugin_load_state_changed(cancelled); return true; } @@ -1197,6 +1281,9 @@ bool PluginManager::unload_plugin(const std::string& plugin_key) if (!m_shutting_down.load(std::memory_order_acquire)) mark_plugin_install_state_disabled(plugin_key); + // Invalidate this load instance before teardown callbacks run. mark_* above still needed the + // identity to prove it was writing the loaded installation's sidecar. + end_plugin_browser_profile(plugin_key); notify_unload_complete(); cancel_and_wait_for_capabilities(removed.capabilities); @@ -1236,6 +1323,7 @@ void PluginManager::unload_all_plugins() // Bulk shutdown intentionally skips the normal unload notification path, but resources owned // by GUI subscribers still need to be torn down before the interpreter is finalized. for (const std::string& key : removed_keys) { + end_plugin_browser_profile(key); PluginAuditManager::discard_pending_permission_prompts_for(key); run_on_unload_callbacks(key); } @@ -1304,7 +1392,13 @@ void PluginManager::set_capability_enabled(const PluginCapabilityId& id, bool en void PluginManager::write_loaded_plugin_install_state(const std::string& plugin_key) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + report_plugin_state_persist_failure(GUI::format( + _u8L("The plugin capability change for %1% could not be saved: %2%"), plugin_key, lock_error)); + return; + } PluginDescriptor descriptor; std::vector> capabilities; @@ -1324,12 +1418,27 @@ void PluginManager::write_loaded_plugin_install_state(const std::string& plugin_ if (descriptor.plugin_root.empty()) return; + PluginInstallState current; + if (read_install_state_status(boost::filesystem::path(descriptor.plugin_root), current) != + InstallStateReadStatus::Readable || + !install_state_matches_selected(plugin_key, descriptor.plugin_root, current, /*prefer_descriptor=*/false)) { + report_plugin_state_persist_failure(GUI::format( + _u8L("The plugin capability change for %1% was not saved because the installed plugin changed."), plugin_key)); + return; + } + write_install_state(boost::filesystem::path(descriptor.plugin_root), descriptor, /*enabled=*/true, capabilities); } void PluginManager::mark_plugin_install_state_disabled(const std::string& plugin_key) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + report_plugin_state_persist_failure(GUI::format( + _u8L("The disabled state of %1% could not be saved: %2%"), plugin_key, lock_error)); + return; + } PluginDescriptor descriptor; if (!try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) @@ -1346,6 +1455,11 @@ void PluginManager::mark_plugin_install_state_disabled(const std::string& plugin << "; leaving the sidecar untouched"; return; } + if (!install_state_matches_selected(plugin_key, descriptor.plugin_root, state, /*prefer_descriptor=*/false)) { + report_plugin_state_persist_failure(GUI::format( + _u8L("The disabled state of %1% was not saved because the installed plugin changed."), plugin_key)); + return; + } if (status == InstallStateReadStatus::Absent) seed_install_metadata(state, descriptor); state.enabled = false; @@ -1360,7 +1474,12 @@ void PluginManager::mark_plugin_install_state_disabled(const std::string& plugin bool PluginManager::mutate_plugin_permissions(const std::string& plugin_key, const PluginPermissionMutation& mutation, PluginPermissions* applied) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return false; + } if (plugin_key.empty()) { BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": No plugin key supplied"; @@ -1384,6 +1503,11 @@ bool PluginManager::mutate_plugin_permissions(const std::string& plugin_key, con BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to read install state for " << plugin_key; return false; } + if (!install_state_matches_selected(plugin_key, descriptor.plugin_root, state, /*prefer_descriptor=*/false)) { + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Refusing to edit permissions of a replaced installation: " + << plugin_key; + return false; + } // Apply against the latest state read under the lock, so a grant another writer added since // the caller last looked is kept. Removals run first: a value named in both lists ends present. @@ -1425,27 +1549,41 @@ bool PluginManager::mutate_plugin_permissions(const std::string& plugin_key, con return true; } -void PluginManager::revoke_plugin_permissions(const std::string& plugin_key) +bool PluginManager::revoke_plugin_permissions(const std::string& plugin_key) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + report_plugin_state_persist_failure(GUI::format( + _u8L("The permission reset of %1% could not be saved: %2%"), plugin_key, lock_error)); + return false; + } PluginDescriptor descriptor; if (!try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) - return; + return true; // nothing installed to reset const boost::filesystem::path root(descriptor.plugin_root); PluginInstallState state; if (!read_install_state(root, state)) { BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to read install state for " << plugin_key; - return; + return false; + } + if (!install_state_matches_selected(plugin_key, descriptor.plugin_root, state, /*prefer_descriptor=*/true)) { + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Refusing to revoke permissions of a replaced installation: " + << plugin_key; + return false; } state.permissions = {}; - if (!write_install_state(root, state)) + if (!write_install_state(root, state)) { BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to revoke permissions for " << plugin_key; + return false; + } // A revoke or reinstall invalidates transient recursive-delete consents and queued callbacks. PluginAuditManager::instance().invalidate_recursive_delete_state(plugin_key); + return true; } // ── Callbacks ─────────────────────────────────────────────────────────────────────────────── @@ -1651,7 +1789,7 @@ bool PluginManager::install_plugin(const boost::filesystem::path& filepath, Plug bool PluginManager::install_plugin_impl(const boost::filesystem::path& filepath, PluginDescriptor& plugin_descriptor, const std::string* cloud_user_id_override, std::string& error, bool* install_target_intact, const PluginInstallState* preserved_state, - bool mark_error_on_failure) + bool mark_error_on_failure, std::shared_ptr package_lease) { error.clear(); @@ -1673,25 +1811,57 @@ bool PluginManager::install_plugin_impl(const boost::filesystem::path& filepath, } // A local overwrite must not leave the old module holding the package file or its Python - // namespace while the installer replaces the package on disk. + // namespace while the installer replaces the package on disk. Take the package lease before + // unloading, so a busy package fails without leaving the old plugin unloaded. + PluginPackageLease held_package_lease = package_lease; if (!plugin_descriptor.is_cloud_plugin()) { - const std::string local_plugin_key = make_local_plugin_key(filepath.stem().string()); + const std::string local_plugin_key = plugin_loader::local_plugin_package_key(filepath); + std::string lease_error; + if (!held_package_lease) + held_package_lease = acquire_plugin_package_lease(local_plugin_key, lease_error); + if (!held_package_lease) { + error = GUI::format(_u8L("Cannot install the plugin while its package is being loaded or updated: %1%"), + lease_error); + if (mark_error_on_failure) + set_plugin_error(local_plugin_key, error); + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error; + return false; + } if (is_plugin_loaded(local_plugin_key)) unload_plugin(local_plugin_key); } if (!plugin_loader::install_plugin(filepath, cloud_user_id, plugin_descriptor, error, install_target_intact, - preserved_state)) { + preserved_state, held_package_lease)) { if (mark_error_on_failure && !plugin_descriptor.plugin_key.empty()) set_plugin_error(plugin_descriptor.plugin_key, error); BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error; return false; } + // Publish the new root/revision before any immediate load: a load compares it with the + // sidecar, and a stale empty revision must not make the just-installed package look replaced. + if (!plugin_descriptor.plugin_key.empty()) { + std::lock_guard lock(m_mutex); + if (Plugin* entry = find_plugin_locked(plugin_descriptor.plugin_key)) { + entry->descriptor.plugin_root = plugin_descriptor.plugin_root; + entry->descriptor.entry_path = plugin_descriptor.entry_path; + entry->descriptor.installation_revision = plugin_descriptor.installation_revision; + entry->descriptor.metadata_valid = plugin_descriptor.metadata_valid; + } + } + // Every successful install may have replaced executable plugin code. Revoke any permissions // associated with the previous package so the newly installed version must request them again. if (!plugin_descriptor.plugin_key.empty()) { { - revoke_plugin_permissions(plugin_descriptor.plugin_key); + // Fail closed: new executable code must never load with the replaced package's grants. + if (!revoke_plugin_permissions(plugin_descriptor.plugin_key)) { + error = _u8L("The plugin was installed, but its previous permissions could not be reset. " + "It was not loaded; restart OrcaSlicer and try again."); + set_plugin_error(plugin_descriptor.plugin_key, error); + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << error; + return false; + } // A prompt queued by the replaced code must not grant a permission the new code never // requested: an installed package starts its lifecycle from a clean failure state. @@ -1769,6 +1939,7 @@ void PluginManager::update_cloud_metadata(const std::vector& c const std::string latest_version = cloud_entry.latest_available_version(); const std::string local_plugin_root = entry.plugin_root; const std::string local_entry_path = entry.entry_path; + const std::string local_revision = entry.installation_revision; const bool local_metadata_ok = entry.is_metadata_valid(); const bool has_local_package = entry.has_local_package(); const std::string previous_error = entry.error; @@ -1776,8 +1947,9 @@ void PluginManager::update_cloud_metadata(const std::vector& c const bool enabled = entry.enabled; entry = cloud_entry; - entry.plugin_root = local_plugin_root; - entry.entry_path = local_entry_path; + entry.plugin_root = local_plugin_root; + entry.entry_path = local_entry_path; + entry.installation_revision = has_local_package ? local_revision : std::string{}; if (has_local_package) apply_plugin_metadata_fallbacks(entry, local_entry); if (entry.plugin_key.empty()) @@ -2001,7 +2173,8 @@ bool PluginManager::install_cloud_plugin_package(const std::string& plugin_key, const std::string* cloud_user_id, std::string& error, CloudUpdateFailure* failure, - const PluginInstallState* preserved_state) + const PluginInstallState* preserved_state, + std::shared_ptr package_lease) { error.clear(); @@ -2022,7 +2195,7 @@ bool PluginManager::install_cloud_plugin_package(const std::string& plugin_key, bool install_target_intact = true; if (!install_plugin_impl(package_path, installed, cloud_user_id, error, &install_target_intact, preserved_state, - /*mark_error_on_failure=*/!caller_owns_failure)) { + /*mark_error_on_failure=*/!caller_owns_failure, std::move(package_lease))) { if (failure != nullptr) *failure = install_target_intact ? CloudUpdateFailure::PreviousPackageUsable : CloudUpdateFailure::RollbackFailed; @@ -2121,7 +2294,12 @@ void PluginManager::restore_plugin_state_after_failed_update(const PluginDescrip } { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ": " << lock_error; + return; + } PluginInstallState state; const InstallStateReadStatus status = read_install_state_status(root, state); @@ -2130,6 +2308,16 @@ void PluginManager::restore_plugin_state_after_failed_update(const PluginDescrip << previous.plugin_key << "; leaving the sidecar untouched"; return; } + // Never write the old grants onto a package that was replaced while the update failed. + const std::string expected_revision = !previous.installation_revision.empty() + ? previous.installation_revision + : previous_state.installation_revision; + if (!expected_revision.empty() && + (status != InstallStateReadStatus::Readable || state.installation_revision != expected_revision)) { + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Not restoring " << previous.plugin_key + << " because its installed revision changed"; + return; + } if (had_previous_state) { // The snapshot also restores permissions and capability choices, which belong to the @@ -2267,15 +2455,52 @@ bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::stri const bool was_loaded = had_local_package && is_plugin_loaded(plugin_key); const bool was_enabled = !had_local_package || was_loaded || previous.enabled; + // Acquire the package lease before reading the selected revision and keep it through + // unload/install/revoke, so the selected installation cannot be swapped under the update. + std::shared_ptr update_package_lease; + if (had_local_package) { + std::string lease_error; + update_package_lease = acquire_plugin_package_lease(plugin_key, lease_error); + if (!update_package_lease) { + error = GUI::format(_u8L("Cannot update the plugin while its package is being loaded or updated: %1%"), + lease_error); + boost::system::error_code ec; + boost::filesystem::remove(download.package_path, ec); + set_plugin_error(plugin_key, error); + return false; + } + } + PluginInstallState previous_state; bool had_previous_state = false; bool previous_state_unreadable = false; if (had_local_package && !previous.plugin_root.empty()) { - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + error = GUI::format(_u8L("Cannot read the installed plugin state: %1%"), lock_error); + boost::system::error_code ec; + boost::filesystem::remove(download.package_path, ec); + set_plugin_error(plugin_key, error); + return false; + } const InstallStateReadStatus status = read_install_state_status(boost::filesystem::path(previous.plugin_root), previous_state); had_previous_state = status == InstallStateReadStatus::Readable; previous_state_unreadable = status == InstallStateReadStatus::Unreadable; + const bool revision_matches = + !previous.installation_revision.empty() + ? status == InstallStateReadStatus::Readable && + previous_state.installation_revision == previous.installation_revision + : status == InstallStateReadStatus::Absent || + (status == InstallStateReadStatus::Readable && previous_state.installation_revision.empty()); + if (!revision_matches) { + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + boost::system::error_code ec; + boost::filesystem::remove(download.package_path, ec); + set_plugin_error(plugin_key, error); + return false; + } } // A sidecar that exists but cannot be read may still hold the user's capability choices and @@ -2344,8 +2569,13 @@ bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::stri preserved_state.capabilities = previous_state.capabilities; } - if (!install_cloud_plugin_package(plugin_key, version, download.package_path, previous, &update_cloud_user, install_error, - &failure, had_local_package ? &preserved_state : nullptr)) { + const bool installed = install_cloud_plugin_package(plugin_key, version, download.package_path, previous, + &update_cloud_user, install_error, &failure, + had_local_package ? &preserved_state : nullptr, + update_package_lease); + if (!installed) { + // Install/revoke are done; release before restoring/reloading the old package. + update_package_lease.reset(); // Restoring the old state and reloading the old package is only meaningful when the // installer left that package in place. A committed replacement must not inherit the old // package's grants. @@ -2426,12 +2656,34 @@ bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::stri boost::system::error_code equivalent_ec; const bool same_root = boost::filesystem::equivalent(resolved_root, installed.plugin_root, equivalent_ec); if (!equivalent_ec && !same_root) { + // Reuse the update lease when we hold it; otherwise take the old package lease so an + // old root is not removed while another process is loading it. + PluginPackageLease old_lease = update_package_lease; + if (!old_lease) { + std::string lease_error; + old_lease = acquire_plugin_package_lease(plugin_key, lease_error); + if (!old_lease) { + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Skipping stale package cleanup for " + << plugin_key << ": " << lease_error; + return; + } + } std::string cleanup_error; + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Skipping stale package cleanup for " + << plugin_key << ": " << lock_error; + return; + } if (!delete_plugin_root(resolved_root, plugin_key, cleanup_error)) BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << cleanup_error; } }; + // Release before reload; cleanup below reacquires if the reload does not still hold it. + update_package_lease.reset(); + if (was_loaded) { // The package is already installed and its state persisted, so a failure here is reported // as a reload failure rather than hiding the successful update. @@ -2449,6 +2701,25 @@ bool PluginManager::update_cloud_plugin(const std::string& plugin_key, std::stri << " updated and kept deactivated"; } + // A root-changing update may not carry the old backup sidecar, so the installer can generate + // a fresh profile without seeing the old id. Detect that here and report the reset. + if (had_previous_state && !previous_state.browser_profile_id.empty() && !installed.plugin_root.empty()) { + PluginInstallState new_state; + bool new_readable = false; + { + std::unique_lock state_lock; + std::string lock_error; + if (try_lock_plugin_install_state(state_lock, lock_error)) + new_readable = read_install_state(boost::filesystem::path(installed.plugin_root), new_state); + else + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": " << lock_error; + } + if (new_readable && new_state.browser_profile_id != previous_state.browser_profile_id) { + warn_plugin_browser_profile_reset(plugin_key); + delete_plugin_browser_profile(plugin_key, previous_state.browser_profile_id); + } + } + remove_stale_old_package(); return true; } @@ -2468,11 +2739,94 @@ bool PluginManager::delete_installed_plugin_package(const PluginDescriptor& plug if (!resolved_allowed_plugin_root) return false; + // Package lease before the sidecar lock. A load in another process fails this delete + // non-blocking instead of letting the package disappear under its import. + std::string package_lease_error; + PluginPackageLease package_lease = acquire_plugin_package_lease(plugin.plugin_key, package_lease_error); + if (!package_lease) { + error = GUI::format(_u8L("Cannot delete the plugin while its package is being loaded or updated: %1%"), + package_lease_error); + return false; + } + + PluginInstallState before_state; + InstallStateReadStatus before_status = InstallStateReadStatus::Absent; + boost::system::error_code entry_time_ec; + const std::time_t before_entry_time = + plugin.entry_path.empty() ? 0 : boost::filesystem::last_write_time(plugin.entry_path, entry_time_ec); + const bool before_entry_time_valid = !plugin.entry_path.empty() && !entry_time_ec; + { + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + error = GUI::format(_u8L("Cannot inspect the plugin before deleting it: %1%"), lock_error); + return false; + } + before_status = read_install_state_status(resolved_root, before_state); + } + const bool before_readable = before_status == InstallStateReadStatus::Readable; + if (before_status == InstallStateReadStatus::Unreadable) + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Cannot read the install state of " << plugin.plugin_key + << "; its browser profile id is unknown and the profile will be left untouched"; + // An empty selected revision is only safe for a revision-less legacy sidecar. If disk has a + // revision the caller did not select, this is a stale descriptor over a replacement. + if (plugin.installation_revision.empty() && before_readable && !before_state.installation_revision.empty()) { + error = _u8L("The plugin revision is stale. Refresh the plugin list and try again."); + return false; + } + const bool profile_unknown = !before_readable || before_state.browser_profile_id.empty(); + unload_plugin(plugin.plugin_key); + // Serialize the package mutation with sidecar writers and other install/delete operations. + // Revalidate after taking the lock: if another instance installed a replacement while this + // process was unloading, deleting it would destroy that replacement's package. + std::unique_lock state_lock; + std::string state_lock_error; + if (!try_lock_plugin_install_state(state_lock, state_lock_error)) { + error = GUI::format(_u8L("Cannot delete the plugin because its install-state lock is unavailable: %1%"), + state_lock_error); + return false; + } + if (before_entry_time_valid) { + boost::system::error_code now_time_ec; + const std::time_t now_time = boost::filesystem::last_write_time(plugin.entry_path, now_time_ec); + if (now_time_ec || now_time != before_entry_time) { + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + return false; + } + } + PluginInstallState now_state; + const bool now_readable = read_install_state(resolved_root, now_state); + // The revision selected by the caller (the descriptor the user acted on) must still be the + // installed revision. This covers a replacement during a long cloud-unsubscribe request, + // where the read inside this call would otherwise already see the replacement. + if (!plugin.installation_revision.empty() && + (!now_readable || now_state.installation_revision != plugin.installation_revision)) { + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + return false; + } + if (before_readable) { + if (!now_readable || now_state.browser_profile_id != before_state.browser_profile_id || + now_state.installed_version != before_state.installed_version || + now_state.cloud_uuid != before_state.cloud_uuid || + now_state.installation_revision != before_state.installation_revision) { + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + return false; + } + } else if (now_readable && (!now_state.browser_profile_id.empty() || !now_state.installation_revision.empty())) { + // This call saw no installation identity, but now there is one: another instance + // installed a replacement while this process was unloading. + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + return false; + } + if (!delete_plugin_root(resolved_root, plugin.plugin_key, error)) return false; + if (profile_unknown) + warn_plugin_browser_profile_cleanup_unknown(plugin.plugin_key); + { std::lock_guard lock(m_mutex); m_plugins.erase(std::remove_if(m_plugins.begin(), m_plugins.end(), @@ -2480,6 +2834,10 @@ bool PluginManager::delete_installed_plugin_package(const PluginDescriptor& plug m_plugins.end()); } + // The package is gone. A profile still leased by another instance is skipped with a warning; + // the new installation will start with a fresh id anyway. Passing the root makes every retry + // skip the profile if another instance installed a replacement there. + delete_plugin_browser_profile(plugin.plugin_key, before_state.browser_profile_id, resolved_root.string()); return true; } @@ -2506,18 +2864,112 @@ bool PluginManager::keep_installed_plugin_as_local(const PluginDescriptor& plugi const std::string entry_stem = fs::path(plugin_descriptor.entry_path).stem().string(); const std::string new_key = make_local_plugin_key(!entry_stem.empty() ? entry_stem : resolved_root.stem().string()); + // Lease both keys before the sidecar lock, in deterministic key order. The old package must + // not be loaded while it is unloaded/moved, and the new local key must not be loaded while its + // target is being prepared. Non-blocking failures release whatever was acquired. + std::vector lease_keys{old_key}; + if (new_key != old_key) + lease_keys.push_back(new_key); + std::sort(lease_keys.begin(), lease_keys.end()); + std::vector package_leases; + package_leases.reserve(lease_keys.size()); + for (const std::string& key : lease_keys) { + std::string lease_error; + PluginPackageLease lease = acquire_plugin_package_lease(key, lease_error); + if (!lease) { + error = GUI::format(_u8L("Cannot keep the plugin local while its package is being loaded or updated: %1%"), + lease_error); + return false; + } + package_leases.push_back(std::move(lease)); + } + PluginDescriptor local_descriptor = plugin_descriptor; local_descriptor.plugin_key = new_key; local_descriptor.cloud = std::nullopt; local_descriptor.clear_error(); - // Re-key the entry in place, carrying the live module/capabilities (if any) with it. The - // capabilities' audit key must follow, since it is what identifies their owning package. - std::vector rekeyed; + const fs::path entry_file = fs::path(plugin_descriptor.entry_path).filename(); + if (entry_file.empty()) { + error = _u8L("Cannot keep plugin local: the installed entry file is unknown."); + return false; + } + const fs::path local_root = fs::path(data_dir()) / "orca_plugins"; + const fs::path target_root = local_root / filesystem_safe_escape(entry_file.string()); + + // Preflight the selected revision before unloading. A replacement during the cloud request + // must fail without leaving the plugin unloaded. + { + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + error = GUI::format(_u8L("Cannot keep the plugin local because its install-state lock is unavailable: %1%"), + lock_error); + return false; + } + PluginInstallState state; + const InstallStateReadStatus status = read_install_state_status(resolved_root, state); + const bool revision_matches = + !plugin_descriptor.installation_revision.empty() + ? status == InstallStateReadStatus::Readable && + state.installation_revision == plugin_descriptor.installation_revision + : status == InstallStateReadStatus::Absent || + (status == InstallStateReadStatus::Readable && state.installation_revision.empty()); + if (!revision_matches) { + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + return false; + } + } + + bool was_loaded = false; + bool was_enabled = plugin_descriptor.enabled; + { + std::lock_guard lock(m_mutex); + if (Plugin* loaded = find_plugin_locked(old_key)) { + was_loaded = loaded->is_loaded(); + was_enabled = loaded->descriptor.enabled; + } + if (find_plugin_locked(new_key) != nullptr && new_key != old_key) { + error = GUI::format(_u8L("Cannot keep plugin local: local plugin key already exists: %1%"), new_key); + BOOST_LOG_TRIVIAL(warning) << error; + return false; + } + } + + // Unload before moving the package. Renaming a loaded package can fail on Windows (open + // native modules) and leaves resources pointing at the old path. The reload below rebuilds + // the live module from the new location. + unload_plugin(old_key); + + // If the conversion fails after the unload, put the old plugin back rather than leaving it + // silently unloaded. The guard is disarmed as soon as the rekey succeeds. + bool restore_old_load = was_loaded; + auto reload_guard = std::unique_ptr>( + this, [this, old_key, was_enabled, &restore_old_load, &package_leases](PluginManager*) { + if (!restore_old_load) + return; + // The reload needs the old package lease; release all conversion leases first. + for (auto& lease : package_leases) + lease.reset(); + { + std::lock_guard lock(m_mutex); + if (Plugin* old = find_plugin_locked(old_key)) + old->descriptor.enabled = was_enabled; + } + load_plugin(old_key); + }); + + std::string old_profile_id; { // Sidecar read-modify-write first, then the registry lock: that is the lock order every // install-state writer uses (install_state_mutex -> m_mutex). - std::lock_guard state_lock(install_state_mutex()); + std::unique_lock state_lock; + std::string lock_error; + if (!try_lock_plugin_install_state(state_lock, lock_error)) { + error = GUI::format(_u8L("Cannot keep the plugin local because its install-state lock is unavailable: %1%"), + lock_error); + return false; + } std::lock_guard lock(m_mutex); Plugin* entry = find_plugin_locked(old_key); @@ -2549,42 +3001,117 @@ bool PluginManager::keep_installed_plugin_as_local(const PluginDescriptor& plugi install_state.installed_version = !local_descriptor.installed_version.empty() ? local_descriptor.installed_version : local_descriptor.version; - install_state.enabled = local_descriptor.enabled; + } + // unload_plugin wrote enabled=false; keep the user's activation intent in the local copy. + install_state.enabled = was_enabled; + // Do not convert a replacement that appeared while a long cloud request was in flight. + const bool revision_matches = + !plugin_descriptor.installation_revision.empty() + ? install_state_status == InstallStateReadStatus::Readable && + install_state.installation_revision == plugin_descriptor.installation_revision + : install_state_status == InstallStateReadStatus::Absent || + (install_state_status == InstallStateReadStatus::Readable && + install_state.installation_revision.empty()); + if (!revision_matches) { + error = _u8L("The plugin was changed by another OrcaSlicer instance. Refresh the plugin list and try again."); + return false; + } + old_profile_id = install_state.browser_profile_id; + try { + install_state.browser_profile_id = make_plugin_browser_profile_id(); + install_state.installation_revision = make_plugin_installation_revision(); + } catch (const std::exception& ex) { + error = GUI::format(_u8L("Cannot create a plugin installation identity: %1%"), ex.what()); + return false; + } catch (...) { + error = _u8L("Cannot create a plugin installation identity."); + return false; } install_state.installed_from = "local"; install_state.plugin_name = local_descriptor.name; install_state.cloud_uuid.clear(); if (install_state.installed_version.empty()) install_state.installed_version = local_descriptor.version; - if (!write_install_state(resolved_root, install_state)) { - error = GUI::format(_u8L("Failed to update plugin install state: %1%"), (resolved_root / INSTALL_STATE_FILE).string()); + + // resolved_root is canonical; compare canonically so an already-local package is rekeyed + // in place instead of being mistaken for an existing destination. + boost::system::error_code canon_ec; + const fs::path canonical_target = fs::weakly_canonical(target_root, canon_ec); + const bool same_root = !canon_ec && canonical_target == resolved_root; + const fs::path state_root = same_root ? resolved_root : target_root; + if (!same_root) { + boost::system::error_code ec; + fs::create_directories(local_root, ec); + if (ec) { + error = GUI::format(_u8L("Failed to create the local plugin directory %1%: %2%"), + local_root.string(), ec.message()); + return false; + } + ec.clear(); + const bool destination_exists = fs::exists(state_root, ec); + if (ec) { + error = GUI::format(_u8L("Cannot keep plugin local: failed to check destination %1%: %2%"), + state_root.string(), ec.message()); + return false; + } + if (destination_exists) { + error = GUI::format(_u8L("Cannot keep plugin local: destination already exists: %1%"), + state_root.string()); + return false; + } + fs::rename(resolved_root, state_root, ec); + if (ec) { + error = GUI::format(_u8L("Failed to move plugin to the local plugin directory %1%: %2%"), + state_root.string(), ec.message()); + return false; + } + } + + if (!write_install_state(state_root, install_state)) { + if (!same_root) { + boost::system::error_code rollback_ec; + fs::rename(state_root, resolved_root, rollback_ec); + if (rollback_ec) + BOOST_LOG_TRIVIAL(warning) + << __FUNCTION__ << ": Failed to move the plugin back to " << resolved_root.string() + << " after a sidecar write error: " << rollback_ec.message(); + } + error = GUI::format(_u8L("Failed to update plugin install state: %1%"), + (state_root / INSTALL_STATE_FILE).string()); return false; } entry->descriptor.plugin_key = new_key; entry->descriptor.cloud.reset(); entry->descriptor.clear_error(); + entry->descriptor.enabled = was_enabled; + entry->descriptor.plugin_root = state_root.string(); + entry->descriptor.entry_path = (state_root / entry_file).string(); + entry->descriptor.installation_revision = install_state.installation_revision; // The package identity changed, so neither key may keep an old failure's prompt alive. m_failed_loads.erase(old_key); m_failed_loads.erase(new_key); - - for (const auto& capability : entry->capabilities) { - if (capability) - capability->set_audit_plugin_key(new_key); - } - - for (const auto& capability : entry->capabilities) { - if (capability && capability->is_enabled()) - rekeyed.push_back(PluginCapabilityId{capability->type(), capability->name(), new_key}); - } } - // Subscribers key their own state by plugin_key. Publish the identity transition after the - // registry update and outside m_mutex so they can safely query the manager. - for (const PluginCapabilityId& id : rekeyed) { - run_on_capability_unload_callbacks(PluginCapabilityId{id.type, id.name, old_key}); - run_on_capability_load_callbacks(id); - } + // The conversion succeeded; a later reload failure must not restore the old key. + restore_old_load = false; + + // The old key's pre-identity profile directory (if any) is not reachable once the package is + // rekeyed; report it so its data is not silently abandoned. + warn_legacy_plugin_browser_profile(old_key, old_profile_id); + + // Drop the old profile after unload released its lease. A replacement is different by id. + // The old package was moved (or rekeyed in place), so no root-existence check here. + delete_plugin_browser_profile(old_key, old_profile_id); + + // Reload from the new local path so the live module, resources and capabilities all point at + // it. The load binds the fresh identity and fires the load callbacks. + // The old package has been rekeyed; release the conversion leases before the new load (which + // acquires its own, including the same-key case). + for (auto& lease : package_leases) + lease.reset(); + if (was_loaded) + load_plugin(new_key); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Transitioned plugin from " << old_key << " to " << new_key; @@ -2668,11 +3195,27 @@ bool PluginManager::unsubscribe_cloud_plugin(const std::string& plugin_key, std: } if (!m_cloud_service.request_cloud_unsubscribe(descriptor, error)) { + if (error.empty()) + error = _u8L("The cloud subscription was not cancelled."); + // A nonzero cloud result can be a timeout, so the server state is unknown. + // TRN %1% is the cloud service error. + error = GUI::format( + _u8L("The cloud subscription status could not be confirmed; the local plugin package was not changed: %1%"), + error); set_plugin_error(plugin_key, error); return false; } - return finalize_cloud_plugin_removal(descriptor, true, error); + if (!finalize_cloud_plugin_removal(descriptor, true, error)) { + if (error.empty()) + error = _u8L("unknown error"); + // TRN %1% is the local conversion error. + error = GUI::format( + _u8L("The cloud unsubscribe request succeeded, but keeping the local plugin copy failed: %1%"), error); + set_plugin_error(plugin_key, error); + return false; + } + return true; } bool PluginManager::delete_and_unsubscribe_cloud_plugin(const std::string& plugin_key, std::string& error) @@ -2703,11 +3246,27 @@ bool PluginManager::delete_and_unsubscribe_cloud_plugin(const std::string& plugi unload_plugin(plugin_key); if (!m_cloud_service.request_cloud_unsubscribe(descriptor, error)) { + if (error.empty()) + error = _u8L("The cloud subscription was not cancelled."); + // A nonzero cloud result can be a timeout, so the server state is unknown. + // TRN %1% is the cloud service error. + error = GUI::format( + _u8L("The cloud subscription status could not be confirmed; the local plugin package was not removed: %1%"), + error); set_plugin_error(plugin_key, error); return false; } - return finalize_cloud_plugin_removal(descriptor, false, error); + if (!finalize_cloud_plugin_removal(descriptor, false, error)) { + if (error.empty()) + error = _u8L("unknown error"); + // TRN %1% is the local package removal error. + error = GUI::format( + _u8L("The cloud unsubscribe request succeeded, but removing the local plugin package failed: %1%"), error); + set_plugin_error(plugin_key, error); + return false; + } + return true; } // ── Async Script runtime ──────────────────────────────────────────────────────────────────── diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index 5775f5021e..f658a5a67d 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -179,6 +179,11 @@ public: // Packages that materialize at least one capability of this type. A package's capability types // are only known once it has been loaded, so a never-loaded package never matches. bool try_get_plugin_descriptor(const std::string& plugin_key, PluginDescriptor& out) const; + + // Records the installation revision the loader just wrote for a package root. Used so a + // later reload compares against the same installation instead of accepting a replacement. + void set_plugin_installation_revision(const std::string& plugin_key, const std::string& plugin_root, + const std::string& revision); // Same, but only for packages that are loadable (i.e. not an invalid package). bool try_get_valid_plugin_descriptor(const std::string& plugin_key, PluginDescriptor& out) const; // Packages that were present in the previous discovery pass but were not found on disk in the @@ -213,7 +218,7 @@ public: // Reads the sidecar under install_state_mutex(), so the result is not interleaved with a // permission write. Returns false when the plugin is unknown or has no readable sidecar. - // Must not be called while already holding install_state_mutex(); the lock is not recursive. + // The lock is reentrant per thread, but new code should still avoid nesting it. bool get_install_state(const std::string& plugin_key, PluginInstallState& install_state); // Applies a granular edit to the plugin's latest sidecar contents in one locked read-modify- @@ -369,7 +374,9 @@ private: // read or written is left untouched. void mark_plugin_install_state_disabled(const std::string& plugin_key); // Revoke permissions after a package replacement so the new package must request them again. - void revoke_plugin_permissions(const std::string& plugin_key); + // Returns false when the sidecar could not be updated, so an install must fail closed instead + // of letting new code inherit the replaced package's grants. + bool revoke_plugin_permissions(const std::string& plugin_key); // Keep the cloud install directory in step with the signed-in agent, as every cloud install // must land in _subscribed//. @@ -394,7 +401,8 @@ private: std::string& error, bool* install_target_intact, const PluginInstallState* preserved_state = nullptr, - bool mark_error_on_failure = true); + bool mark_error_on_failure = true, + std::shared_ptr package_lease = {}); // Installs an already downloaded cloud package and updates the in-memory descriptor. The // caller owns the package file: it is removed here on both success and failure. cloud_user_id, @@ -409,7 +417,8 @@ private: const std::string* cloud_user_id, std::string& error, CloudUpdateFailure* failure = nullptr, - const PluginInstallState* preserved_state = nullptr); + const PluginInstallState* preserved_state = nullptr, + std::shared_ptr package_lease = {}); // Puts back the sidecar (permissions, capability choices and enabled flag) that the unload // step overwrote when a replacement failed and the previous package is still in place. void restore_plugin_state_after_failed_update(const PluginDescriptor& previous, diff --git a/src/slic3r/plugin/host/PluginHostUi.cpp b/src/slic3r/plugin/host/PluginHostUi.cpp index ad35993450..7d819ce2ad 100644 --- a/src/slic3r/plugin/host/PluginHostUi.cpp +++ b/src/slic3r/plugin/host/PluginHostUi.cpp @@ -4,6 +4,7 @@ #include #include #include "slic3r/plugin/PluginAuditManager.hpp" +#include "slic3r/plugin/PluginBrowserProfile.hpp" #include "slic3r/plugin/PythonInterpreter.hpp" // PythonGILState #include "slic3r/plugin/PluginJsonPy.hpp" @@ -93,12 +94,20 @@ CallablePtr make_holder(py::object obj) // The handler runs later, from a wx event with no plugin call on the stack, so it restores the // plugin's audit context captured at registration. Without that scope, audit events raised by // the callback would be unattributed and allowed, like host code. -GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message, std::string plugin_key) +bool browser_profile_callback_allowed(const PluginBrowserProfileIdentityRef& identity) +{ + return plugin_browser_profile_is_current(identity); +} + +GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message, std::string plugin_key, + PluginBrowserProfileIdentityRef identity) { CallablePtr holder = make_holder(std::move(on_message)); if (!holder) return nullptr; - return [holder, plugin_key = std::move(plugin_key)](const json& data) { + return [holder, plugin_key = std::move(plugin_key), identity = std::move(identity)](const json& data) { + if (!browser_profile_callback_allowed(identity)) + return; PythonGILState gil; if (!gil) return; @@ -112,12 +121,15 @@ GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message, std:: }; } -GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit, std::string plugin_key) +GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit, std::string plugin_key, + PluginBrowserProfileIdentityRef identity) { CallablePtr holder = make_holder(std::move(on_submit)); if (!holder) return nullptr; - return [holder, plugin_key = std::move(plugin_key)](const json& data) { + return [holder, plugin_key = std::move(plugin_key), identity = std::move(identity)](const json& data) { + if (!browser_profile_callback_allowed(identity)) + return; PythonGILState gil; if (!gil) return; @@ -133,11 +145,14 @@ GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit, std::str // The plugin's on_close: fired only on a user/JS-initiated close (not forced teardown), while the // window is alive. Empty if the plugin passed None. -std::function make_close_adapter(const CallablePtr& holder, std::string plugin_key) +std::function make_close_adapter(const CallablePtr& holder, std::string plugin_key, + const PluginBrowserProfileIdentityRef& identity) { if (!holder) return nullptr; - return [holder, plugin_key = std::move(plugin_key)]() { + return [holder, plugin_key = std::move(plugin_key), identity]() { + if (!browser_profile_callback_allowed(identity)) + return; PythonGILState gil; if (!gil) return; @@ -162,6 +177,32 @@ std::string plugin_identity_for_ui(const char* api_name) return plugin_key; } +struct UiProfile +{ + std::string plugin_key; + std::string profile_id; + PluginBrowserProfileIdentityRef identity; + BrowserProfileLease lease; +}; + +// Use the identity bound to this load instance, never a freshly read sidecar: a replacement +// installed by another process must not hand its profile/session to an old loaded plugin. +UiProfile ui_profile_for(const char* api_name) +{ + UiProfile ui; + ui.plugin_key = plugin_identity_for_ui(api_name); + ui.identity = current_plugin_browser_profile_identity(ui.plugin_key); + if (!ui.identity) + throw std::runtime_error("The plugin is not loaded; its browser profile is unavailable"); + ui.profile_id = ui.identity->profile_id; + ui.lease = acquire_plugin_browser_profile_lease(ui.identity); + if (!ui.lease) { + warn_plugin_browser_profile_in_use(ui.plugin_key); + throw std::runtime_error("The plugin browser profile is in use by another OrcaSlicer instance"); + } + return ui; +} + // -------------------------------------------------------------------------- // Registry of live plugin UI resources. Keyed by an opaque id; tracks the // owning plugin so all of a plugin's UI can be torn down on unload. @@ -180,17 +221,20 @@ public: std::lock_guard lk(m_mtx); return m_next_id++; } - void bind(int id, wxWindow* window, const std::string& plugin_key) + void bind(int id, wxWindow* window, const std::string& plugin_key, BrowserProfileLease lease = {}) { std::lock_guard lk(m_mtx); m_resources[id] = window; m_owners[id] = plugin_key; + if (lease) + m_leases[id] = std::move(lease); } void remove(int id) { std::lock_guard lk(m_mtx); m_resources.erase(id); m_owners.erase(id); + m_leases.erase(id); } template @@ -216,6 +260,10 @@ public: auto rit = m_resources.find(it->first); if (rit != m_resources.end()) { out.push_back(rit->second); + // A pending (windowless) creation is abandoned now, so its lease must go. + // A live window keeps its lease until the destructor's remove(). + if (rit->second == nullptr) + m_leases.erase(it->first); m_resources.erase(rit); } it = m_owners.erase(it); @@ -250,8 +298,9 @@ public: private: std::mutex m_mtx; - std::unordered_map m_resources; - std::unordered_map m_owners; + std::unordered_map m_resources; + std::unordered_map m_owners; + std::unordered_map m_leases; std::unordered_map>> m_callbacks; int m_next_id{1}; }; @@ -398,12 +447,14 @@ py::object ui_create_window(const std::string& html, const std::string& title, i if (wxTheApp == nullptr) throw std::runtime_error("OrcaSlicer application is not initialized"); - const std::string plugin_key = plugin_identity_for_ui("orca.host.ui.create_window"); + UiProfile ui = ui_profile_for("orca.host.ui.create_window"); + const std::string plugin_key = ui.plugin_key; + const std::string profile_id = ui.profile_id; const int w = width > 0 ? width : 820; const int h = height > 0 ? height : 600; - auto msg_adapter = make_message_adapter(std::move(on_message), plugin_key); - auto submit_adapter = make_submit_adapter(std::move(on_submit), plugin_key); + auto msg_adapter = make_message_adapter(std::move(on_message), plugin_key, ui.identity); + auto submit_adapter = make_submit_adapter(std::move(on_submit), plugin_key, ui.identity); CallablePtr close_holder = make_holder(std::move(on_close)); // The whole wxWindow/webview creation is deferred to a clean main-loop iteration. @@ -424,9 +475,9 @@ py::object ui_create_window(const std::string& html, const std::string& title, i // FIFO-ordered after the creation below, and a plugin teardown claims the pending // id (take_for_plugin), which the creation detects and skips — no orphan window. const int new_id = UiRegistry::instance().reserve_id(); - UiRegistry::instance().bind(new_id, nullptr, plugin_key); + UiRegistry::instance().bind(new_id, nullptr, plugin_key, ui.lease); - GUI::wxGetApp().CallAfter([new_id, plugin_key, html, title, w, h, + GUI::wxGetApp().CallAfter([new_id, plugin_key, profile_id, identity = ui.identity, lease = ui.lease, html, title, w, h, msg_adapter = std::move(msg_adapter), submit_adapter = std::move(submit_adapter), close_holder = std::move(close_holder), modal]() mutable { @@ -434,15 +485,15 @@ py::object ui_create_window(const std::string& html, const std::string& title, i if (!UiRegistry::instance().is_open(new_id)) return; - GUI::WebDialog::CloseHandler on_close = make_close_adapter(close_holder, plugin_key); + GUI::WebDialog::CloseHandler on_close = make_close_adapter(close_holder, plugin_key, identity); // Registry cleanup: GIL-free, runs from the dialog destructor on every path. auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); }; auto* dlg = new GUI::WebDialog(ui_parent(), wxString::FromUTF8(title), html, wxSize(w, h), std::move(msg_adapter), std::move(submit_adapter), std::move(on_close), std::move(on_destroyed), PLUGIN_WX_STYLE, - wxString::FromUTF8(plugin_key)); - UiRegistry::instance().bind(new_id, dlg, plugin_key); + wxString::FromUTF8(profile_id)); + UiRegistry::instance().bind(new_id, dlg, plugin_key, lease); if (modal) { dlg->ShowModal(); // Plugin teardown may already have removed and destroyed this dialog @@ -515,18 +566,20 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl if (wxTheApp == nullptr) throw std::runtime_error("OrcaSlicer application is not initialized"); - const std::string plugin_key = plugin_identity_for_ui("orca.host.ui.create_dock_panel"); + UiProfile ui = ui_profile_for("orca.host.ui.create_dock_panel"); + const std::string plugin_key = ui.plugin_key; + const std::string profile_id = ui.profile_id; const int w = width > 0 ? width : 320; const int h = height > 0 ? height : 480; - auto msg_adapter = make_message_adapter(std::move(on_message), plugin_key); + auto msg_adapter = make_message_adapter(std::move(on_message), plugin_key, ui.identity); CallablePtr close_holder = make_holder(std::move(on_close)); // Deferred and pre-bound for the same reasons as create_window(). const int new_id = UiRegistry::instance().reserve_id(); - UiRegistry::instance().bind(new_id, nullptr, plugin_key); + UiRegistry::instance().bind(new_id, nullptr, plugin_key, ui.lease); - run_when_plater_shown([new_id, plugin_key, html, title, dock, w, h, + run_when_plater_shown([new_id, plugin_key, profile_id, identity = ui.identity, lease = ui.lease, html, title, dock, w, h, msg_adapter = std::move(msg_adapter), close_holder = std::move(close_holder)](GUI::Plater* plater) mutable { if (!UiRegistry::instance().is_open(new_id)) @@ -538,9 +591,10 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl } auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); }; - auto* panel = new GUI::DockPanel(plater, html, std::move(msg_adapter), make_close_adapter(close_holder, plugin_key), - std::move(on_destroyed), wxString::FromUTF8(plugin_key)); - UiRegistry::instance().bind(new_id, panel, plugin_key); + auto* panel = new GUI::DockPanel(plater, html, std::move(msg_adapter), + make_close_adapter(close_holder, plugin_key, identity), + std::move(on_destroyed), wxString::FromUTF8(profile_id)); + UiRegistry::instance().bind(new_id, panel, plugin_key, lease); plater->add_dock_pane(panel, GUI::plugin_pane_name(plugin_key, title), wxString::FromUTF8(title), dock, wxSize(w, h), [panel]() { panel->fire_close(); }); }); @@ -661,6 +715,7 @@ void plater_notification(GUI::NotificationManager::NotificationLevel notificatio { const std::string plugin_key = PluginAuditManager::instance().current_plugin(); CallablePtr holder = make_holder(std::move(on_click)); + PluginBrowserProfileIdentityRef identity; if (holder) { // The click runs later, from a wx event with no plugin call on the stack. Without an // identity there is no audit context to restore, so refuse the callback rather than run @@ -668,14 +723,19 @@ void plater_notification(GUI::NotificationManager::NotificationLevel notificatio // keeps its previous behavior. if (plugin_key.empty()) throw std::runtime_error("orca.host.ui.push_notification on_click must be called from a plugin callback"); + identity = current_plugin_browser_profile_identity(plugin_key); + if (!identity) + throw std::runtime_error("The plugin is not loaded; its browser profile is unavailable"); UiRegistry::instance().bind_callback(holder, plugin_key); } std::function callback; if (holder) { - callback = [holder, plugin_key](wxEvtHandler*) -> bool { + callback = [holder, plugin_key, identity](wxEvtHandler*) -> bool { if (!holder->active.load(std::memory_order_acquire)) return false; + if (!browser_profile_callback_allowed(identity)) + return false; PythonGILState gil; if (!gil) diff --git a/src/slic3r/plugin/host/PluginPages.cpp b/src/slic3r/plugin/host/PluginPages.cpp index 65e2edde86..d3059cc630 100644 --- a/src/slic3r/plugin/host/PluginPages.cpp +++ b/src/slic3r/plugin/host/PluginPages.cpp @@ -19,6 +19,7 @@ #include #include +#include "slic3r/plugin/PluginBrowserProfile.hpp" #include "slic3r/plugin/pluginTypes/pages/PagesPluginCapability.hpp" #include "slic3r/GUI/WebPanel.hpp" #include @@ -77,11 +78,13 @@ constexpr char PLUGIN_PAGE_BRIDGE_JS[] = R"JS( } // namespace -PluginPage::PluginPage(wxWindow* parent, std::shared_ptr capability) - : GUI::WebPanel(parent, PLUGIN_PAGE_BRIDGE_JS, - wxString::FromUTF8(capability ? capability->identity().plugin_key : std::string())) +PluginPage::PluginPage(wxWindow* parent, std::shared_ptr capability, + PluginBrowserProfileIdentityRef identity, const wxString& profile, BrowserProfileLease lease) + : GUI::WebPanel(parent, PLUGIN_PAGE_BRIDGE_JS, profile) , m_cap(std::move(capability)) , m_lifetime(std::make_shared>(this)) + , m_lease(std::move(lease)) + , m_identity(std::move(identity)) { browser()->Bind(wxEVT_WEBVIEW_NEWWINDOW, &PluginPage::on_new_window, this); @@ -144,6 +147,8 @@ bool PluginPage::on_page_message(const std::string& kind, const nlohmann::json& return false; if (!m_cap) return true; + if (!plugin_browser_profile_is_current(m_identity)) + return true; try { m_cap->on_message(data.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)); @@ -222,6 +227,14 @@ bool PluginPages::create_page(const PluginCapabilityId& id) if (!capability) return false; + PluginBrowserProfileIdentityRef identity = current_plugin_browser_profile_identity(id.plugin_key); + if (!identity) { + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << " The plugin is not loaded; no browser profile for " + << id.plugin_key; + return false; + } + const std::string profile_id = identity->profile_id; + std::string icon; try { icon = capability->get_icon(); @@ -250,10 +263,21 @@ bool PluginPages::create_page(const PluginCapabilityId& id) // Built the first time its tab is shown, so a language switch never creates the page's browser // while the main window is being rebuilt. Never prebuilt: the idle queue cannot drop a page // that remove_page() destroys. - auto* page = new GUI::LazyPage(m_parent, GUI::into_u8(page_tab_id(id)), -1, - [capability = std::move(capability)](wxWindow* parent) { - return new PluginPage(parent, capability); - }); + auto* page = new GUI::LazyPage( + m_parent, GUI::into_u8(page_tab_id(id)), -1, + [capability = std::move(capability), identity, plugin_key = id.plugin_key, + profile = wxString::FromUTF8(profile_id)](wxWindow* parent) -> PluginPage* { + // Take the lease only when the page is actually built. A failed attempt returns null + // and LazyPage retries on the next show instead of permanently failing the tab. + BrowserProfileLease lease = acquire_plugin_browser_profile_lease(identity); + if (!lease) { + BOOST_LOG_TRIVIAL(warning) << "PluginPages: the plugin browser profile is in use by another " + << "OrcaSlicer instance: " << plugin_key; + warn_plugin_browser_profile_in_use(plugin_key); + return nullptr; + } + return new PluginPage(parent, capability, identity, profile, lease); + }); m_pages.emplace(id, Page{page, bitmap}); m_order.push_back(id); diff --git a/src/slic3r/plugin/host/PluginPages.hpp b/src/slic3r/plugin/host/PluginPages.hpp index 61c64f53d5..eb387cc133 100644 --- a/src/slic3r/plugin/host/PluginPages.hpp +++ b/src/slic3r/plugin/host/PluginPages.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -26,7 +27,8 @@ namespace Slic3r { class PluginPage : public GUI::WebPanel { public: - PluginPage(wxWindow* parent, std::shared_ptr capability); + PluginPage(wxWindow* parent, std::shared_ptr capability, + PluginBrowserProfileIdentityRef identity, const wxString& profile, BrowserProfileLease lease); ~PluginPage() override; PluginPage() = delete; @@ -41,8 +43,10 @@ protected: private: void on_new_window(wxWebViewEvent& event); - std::shared_ptr m_cap; + std::shared_ptr m_cap; std::shared_ptr> m_lifetime; + BrowserProfileLease m_lease; + PluginBrowserProfileIdentityRef m_identity; }; class PluginPages